context
stringlengths 2.52k
185k
| gt
stringclasses 1
value |
---|---|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Microsoft.Win32.SafeHandles;
using System.ComponentModel;
using System.Diagnostics;
using System.Threading;
namespace System.IO
{
public partial class FileSystemWatcher
{
/// <summary>Start monitoring the current directory.</summary>
private void StartRaisingEvents()
{
// If we're already running, don't do anything.
if (!IsHandleInvalid(_directoryHandle))
return;
// Create handle to directory being monitored
var defaultSecAttrs = default(Interop.mincore.SECURITY_ATTRIBUTES);
_directoryHandle = Interop.mincore.CreateFile(
lpFileName: _directory,
dwDesiredAccess: Interop.mincore.FileOperations.FILE_LIST_DIRECTORY,
dwShareMode: FileShare.Read | FileShare.Delete | FileShare.Write,
securityAttrs: ref defaultSecAttrs,
dwCreationDisposition: FileMode.Open,
dwFlagsAndAttributes: Interop.mincore.FileOperations.FILE_FLAG_BACKUP_SEMANTICS | Interop.mincore.FileOperations.FILE_FLAG_OVERLAPPED,
hTemplateFile: IntPtr.Zero);
if (IsHandleInvalid(_directoryHandle))
{
_directoryHandle = null;
throw new FileNotFoundException(SR.Format(SR.FSW_IOError, _directory));
}
// Create the state associated with the operation of monitoring the direction
AsyncReadState state;
try
{
// Start ignoring all events that were initiated before this, and
// allocate the buffer to be pinned and used for the duration of the operation
int session = Interlocked.Increment(ref _currentSession);
byte[] buffer = AllocateBuffer();
// Store all state, including a preallocated overlapped, into the state object that'll be
// passed from iteration to iteration during the lifetime of the operation. The buffer will be pinned
// from now until the end of the operation.
state = new AsyncReadState(session, buffer, _directoryHandle, ThreadPoolBoundHandle.BindHandle(_directoryHandle));
unsafe { state.PreAllocatedOverlapped = new PreAllocatedOverlapped(ReadDirectoryChangesCallback, state, buffer); }
}
catch
{
// Make sure we don't leave a valid directory handle set if we're not running
_directoryHandle.Dispose();
_directoryHandle = null;
throw;
}
// Start monitoring
_enabled = true;
Monitor(state);
}
/// <summary>Stop monitoring the current directory.</summary>
private void StopRaisingEvents()
{
_enabled = false;
// If we're not running, do nothing.
if (IsHandleInvalid(_directoryHandle))
return;
// Start ignoring all events occurring after this.
Interlocked.Increment(ref _currentSession);
// Close the directory handle. This will cause the async operation to stop processing.
// This operation doesn't need to be atomic because the API will deal with a closed
// handle appropriately. If we get here while asynchronously waiting on a change notification,
// closing the directory handle should cause ReadDirectoryChangesCallback be be called,
// cleaning up the operation. Note that it's critical to also null out the handle. If the
// handle is currently in use in a P/Invoke, it will have its reference count temporarily
// increased, such that the disposal operation won't take effect and close the handle
// until that P/Invoke returns; if during that time the FSW is restarted, the IsHandleInvalid
// check will see a valid handle, unless we also null it out.
_directoryHandle.Dispose();
_directoryHandle = null;
}
private void FinalizeDispose()
{
// We must explicitly dispose the handle to ensure it gets closed before this object is finalized.
// Otherwise, it is possible that the GC will decide to finalize the handle after this,
// leaving a window of time where our callback could be invoked on a non-existent object.
if (!IsHandleInvalid(_directoryHandle))
_directoryHandle.Dispose();
}
// -----------------------------
// ---- PAL layer ends here ----
// -----------------------------
// Current "session" ID to ignore old events whenever we stop then restart.
private int _currentSession;
// Unmanaged handle to monitored directory
private SafeFileHandle _directoryHandle;
private static bool IsHandleInvalid(SafeFileHandle handle)
{
return handle == null || handle.IsInvalid || handle.IsClosed;
}
/// <summary>
/// Initiates the next asynchronous read operation if monitoring is still desired.
/// If the directory handle has been closed due to an error or due to event monitoring
/// being disabled, this cleans up state associated with the operation.
/// </summary>
private unsafe void Monitor(AsyncReadState state)
{
// This method should only ever access the directory handle via the state object passed in, and not access it
// via _directoryHandle. While this function is executing asynchronously, another thread could set
// EnableRaisingEvents to false and then back to true, restarting the FSW and causing a new directory handle
// and thread pool binding to be stored. This function could then get into an inconsistent state by doing some
// operations against the old handles and some against the new.
NativeOverlapped* overlappedPointer = null;
bool continueExecuting = false;
try
{
// If shutdown has been requested, exit. The finally block will handle
// cleaning up the entire operation, as continueExecuting will remain false.
if (!_enabled || IsHandleInvalid(state.DirectoryHandle))
return;
// Get the overlapped pointer to use for this iteration.
overlappedPointer = state.ThreadPoolBinding.AllocateNativeOverlapped(state.PreAllocatedOverlapped);
int size;
continueExecuting = Interop.mincore.ReadDirectoryChangesW(
state.DirectoryHandle,
state.Buffer, // the buffer is kept pinned for the duration of the sync and async operation by the PreAllocatedOverlapped
_internalBufferSize,
_includeSubdirectories,
(int)_notifyFilters,
out size,
overlappedPointer,
IntPtr.Zero);
}
catch (ObjectDisposedException)
{
// Ignore. Disposing of the handle is the mechanism by which the FSW communicates
// to the asynchronous operation to stop processing.
}
catch (ArgumentNullException)
{
//Ignore. The disposed handle could also manifest as an ArgumentNullException.
Debug.Assert(IsHandleInvalid(state.DirectoryHandle), "ArgumentNullException from something other than SafeHandle?");
}
finally
{
// At this point the operation has either been initiated and we'll let the callback
// handle things from here, or the operation has been stopped or failed, in which case
// we need to cleanup because we're no longer executing.
if (!continueExecuting)
{
// Clean up the overlapped pointer created for this iteration
if (overlappedPointer != null)
{
state.ThreadPoolBinding.FreeNativeOverlapped(overlappedPointer);
}
// Clean up the thread pool binding created for the entire operation
state.PreAllocatedOverlapped.Dispose();
state.ThreadPoolBinding.Dispose();
// Finally, if the handle was for some reason changed or closed during this call,
// then don't throw an exception. Otherwise, it's a valid error.
if (!IsHandleInvalid(state.DirectoryHandle))
{
OnError(new ErrorEventArgs(new Win32Exception()));
}
}
}
}
/// <summary>Callback invoked when an asynchronous read on the directory handle completes.</summary>
private unsafe void ReadDirectoryChangesCallback(uint errorCode, uint numBytes, NativeOverlapped* overlappedPointer)
{
AsyncReadState state = (AsyncReadState)ThreadPoolBoundHandle.GetNativeOverlappedState(overlappedPointer);
try
{
if (IsHandleInvalid(state.DirectoryHandle))
return;
if (errorCode != 0)
{
// Inside a service the first completion status is false;
// need to monitor again.
const int ERROR_OPERATION_ABORTED = 995;
if (errorCode != ERROR_OPERATION_ABORTED)
{
OnError(new ErrorEventArgs(new Win32Exception((int)errorCode)));
EnableRaisingEvents = false;
}
return;
}
// Ignore any events that occurred before this "session",
// so we don't get changed or error events after we
// told FSW to stop. Even with this check, though, there's a small
// race condition, as immediately after we do the check, raising
// events could be disabled.
if (state.Session != Volatile.Read(ref _currentSession))
return;
if (numBytes == 0)
{
NotifyInternalBufferOverflowEvent();
}
else
{
ParseEventBufferAndNotifyForEach(state.Buffer);
}
}
finally
{
// Clean up state associated with this one iteration
state.ThreadPoolBinding.FreeNativeOverlapped(overlappedPointer);
// Then call Monitor again to either start the next iteration or
// clean up the whole operation.
Monitor(state);
}
}
private void ParseEventBufferAndNotifyForEach(byte[] buffer)
{
// Parse each event from the buffer and notify appropriate delegates
/******
Format for the buffer is the following C struct:
typedef struct _FILE_NOTIFY_INFORMATION {
DWORD NextEntryOffset;
DWORD Action;
DWORD FileNameLength;
WCHAR FileName[1];
} FILE_NOTIFY_INFORMATION;
NOTE1: FileNameLength is length in bytes.
NOTE2: The Filename is a Unicode string that's NOT NULL terminated.
NOTE3: A NextEntryOffset of zero means that it's the last entry
*******/
// Parse the file notify buffer:
int offset = 0;
int nextOffset, action, nameLength;
string oldName = null;
string name = null;
do
{
unsafe
{
fixed (byte* buffPtr = buffer)
{
// Get next offset:
nextOffset = *((int*)(buffPtr + offset));
// Get change flag:
action = *((int*)(buffPtr + offset + 4));
// Get filename length (in bytes):
nameLength = *((int*)(buffPtr + offset + 8));
name = new string((char*)(buffPtr + offset + 12), 0, nameLength / 2);
}
}
/* A slightly convoluted piece of code follows. Here's what's happening:
We wish to collapse the poorly done rename notifications from the
ReadDirectoryChangesW API into a nice rename event. So to do that,
it's assumed that a FILE_ACTION_RENAMED_OLD_NAME will be followed
immediately by a FILE_ACTION_RENAMED_NEW_NAME in the buffer, which is
all that the following code is doing.
On a FILE_ACTION_RENAMED_OLD_NAME, it asserts that no previous one existed
and saves its name. If there are no more events in the buffer, it'll
assert and fire a RenameEventArgs with the Name field null.
If a NEW_NAME action comes in with no previous OLD_NAME, we assert and fire
a rename event with the OldName field null.
If the OLD_NAME and NEW_NAME actions are indeed there one after the other,
we'll fire the RenamedEventArgs normally and clear oldName.
If the OLD_NAME is followed by another action, we assert and then fire the
rename event with the Name field null and then fire the next action.
In case it's not a OLD_NAME or NEW_NAME action, we just fire the event normally.
(Phew!)
*/
// If the action is RENAMED_FROM, save the name of the file
if (action == Interop.mincore.FileOperations.FILE_ACTION_RENAMED_OLD_NAME)
{
Debug.Assert(oldName == null, "Two FILE_ACTION_RENAMED_OLD_NAME in a row! [" + oldName + "], [ " + name + "]");
oldName = name;
}
else if (action == Interop.mincore.FileOperations.FILE_ACTION_RENAMED_NEW_NAME)
{
if (oldName != null)
{
NotifyRenameEventArgs(WatcherChangeTypes.Renamed, name, oldName);
oldName = null;
}
else
{
Debug.Fail("FILE_ACTION_RENAMED_NEW_NAME with no old name! [ " + name + "]");
NotifyRenameEventArgs(WatcherChangeTypes.Renamed, name, oldName);
oldName = null;
}
}
else
{
if (oldName != null)
{
Debug.Fail("Previous FILE_ACTION_RENAMED_OLD_NAME with no new name! [" + oldName + "]");
NotifyRenameEventArgs(WatcherChangeTypes.Renamed, null, oldName);
oldName = null;
}
switch (action)
{
case Interop.mincore.FileOperations.FILE_ACTION_ADDED:
NotifyFileSystemEventArgs(WatcherChangeTypes.Created, name);
break;
case Interop.mincore.FileOperations.FILE_ACTION_REMOVED:
NotifyFileSystemEventArgs(WatcherChangeTypes.Deleted, name);
break;
case Interop.mincore.FileOperations.FILE_ACTION_MODIFIED:
NotifyFileSystemEventArgs(WatcherChangeTypes.Changed, name);
break;
default:
Debug.Fail("Unknown FileSystemEvent action type! Value: " + action);
break;
}
}
offset += nextOffset;
} while (nextOffset != 0);
if (oldName != null)
{
Debug.Fail("FILE_ACTION_RENAMED_OLD_NAME with no new name! [" + oldName + "]");
NotifyRenameEventArgs(WatcherChangeTypes.Renamed, null, oldName);
oldName = null;
}
}
/// <summary>
/// State information used by the ReadDirectoryChangesW callback. A single instance of this is used
/// for an entire session, getting passed to each iterative call to ReadDirectoryChangesW.
/// </summary>
private sealed class AsyncReadState
{
internal AsyncReadState(int session, byte[] buffer, SafeFileHandle handle, ThreadPoolBoundHandle binding)
{
Debug.Assert(buffer != null);
Debug.Assert(handle != null);
Debug.Assert(binding != null);
Session = session;
Buffer = buffer;
DirectoryHandle = handle;
ThreadPoolBinding = binding;
}
internal int Session { get; private set; }
internal byte[] Buffer { get; private set; }
internal SafeFileHandle DirectoryHandle { get; private set; }
internal ThreadPoolBoundHandle ThreadPoolBinding { get; private set; }
internal PreAllocatedOverlapped PreAllocatedOverlapped { get; set; }
}
}
}
| |
//
// PKCS7.cs: PKCS #7 - Cryptographic Message Syntax Standard
// http://www.rsasecurity.com/rsalabs/pkcs/pkcs-7/index.html
//
// Authors:
// Sebastien Pouliot <[email protected]>
// Daniel Granath <dgranath#gmail.com>
//
// (C) 2002, 2003 Motus Technologies Inc. (http://www.motus.com)
// Copyright (C) 2004-2005 Novell, Inc (http://www.novell.com)
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.Collections;
using System.Security.Cryptography;
using Mono.Security.X509;
namespace Mono.Security {
#if INSIDE_CORLIB
internal
#else
public
#endif
sealed class PKCS7 {
public class Oid {
// pkcs 1
public const string rsaEncryption = "1.2.840.113549.1.1.1";
// pkcs 7
public const string data = "1.2.840.113549.1.7.1";
public const string signedData = "1.2.840.113549.1.7.2";
public const string envelopedData = "1.2.840.113549.1.7.3";
public const string signedAndEnvelopedData = "1.2.840.113549.1.7.4";
public const string digestedData = "1.2.840.113549.1.7.5";
public const string encryptedData = "1.2.840.113549.1.7.6";
// pkcs 9
public const string contentType = "1.2.840.113549.1.9.3";
public const string messageDigest = "1.2.840.113549.1.9.4";
public const string signingTime = "1.2.840.113549.1.9.5";
public const string countersignature = "1.2.840.113549.1.9.6";
public Oid ()
{
}
}
private PKCS7 ()
{
}
static public ASN1 Attribute (string oid, ASN1 value)
{
ASN1 attr = new ASN1 (0x30);
attr.Add (ASN1Convert.FromOid (oid));
ASN1 aset = attr.Add (new ASN1 (0x31));
aset.Add (value);
return attr;
}
static public ASN1 AlgorithmIdentifier (string oid)
{
ASN1 ai = new ASN1 (0x30);
ai.Add (ASN1Convert.FromOid (oid));
ai.Add (new ASN1 (0x05)); // NULL
return ai;
}
static public ASN1 AlgorithmIdentifier (string oid, ASN1 parameters)
{
ASN1 ai = new ASN1 (0x30);
ai.Add (ASN1Convert.FromOid (oid));
ai.Add (parameters);
return ai;
}
/*
* IssuerAndSerialNumber ::= SEQUENCE {
* issuer Name,
* serialNumber CertificateSerialNumber
* }
*/
static public ASN1 IssuerAndSerialNumber (X509Certificate x509)
{
ASN1 issuer = null;
ASN1 serial = null;
ASN1 cert = new ASN1 (x509.RawData);
int tbs = 0;
bool flag = false;
while (tbs < cert[0].Count) {
ASN1 e = cert[0][tbs++];
if (e.Tag == 0x02)
serial = e;
else if (e.Tag == 0x30) {
if (flag) {
issuer = e;
break;
}
flag = true;
}
}
ASN1 iasn = new ASN1 (0x30);
iasn.Add (issuer);
iasn.Add (serial);
return iasn;
}
/*
* ContentInfo ::= SEQUENCE {
* contentType ContentType,
* content [0] EXPLICIT ANY DEFINED BY contentType OPTIONAL
* }
* ContentType ::= OBJECT IDENTIFIER
*/
public class ContentInfo {
private string contentType;
private ASN1 content;
public ContentInfo ()
{
content = new ASN1 (0xA0);
}
public ContentInfo (string oid) : this ()
{
contentType = oid;
}
public ContentInfo (byte[] data)
: this (new ASN1 (data)) {}
public ContentInfo (ASN1 asn1)
{
// SEQUENCE with 1 or 2 elements
if ((asn1.Tag != 0x30) || ((asn1.Count < 1) && (asn1.Count > 2)))
throw new ArgumentException ("Invalid ASN1");
if (asn1[0].Tag != 0x06)
throw new ArgumentException ("Invalid contentType");
contentType = ASN1Convert.ToOid (asn1[0]);
if (asn1.Count > 1) {
if (asn1[1].Tag != 0xA0)
throw new ArgumentException ("Invalid content");
content = asn1[1];
}
}
public ASN1 ASN1 {
get { return GetASN1(); }
}
public ASN1 Content {
get { return content; }
set { content = value; }
}
public string ContentType {
get { return contentType; }
set { contentType = value; }
}
internal ASN1 GetASN1 ()
{
// ContentInfo ::= SEQUENCE {
ASN1 contentInfo = new ASN1 (0x30);
// contentType ContentType, -> ContentType ::= OBJECT IDENTIFIER
contentInfo.Add (ASN1Convert.FromOid (contentType));
// content [0] EXPLICIT ANY DEFINED BY contentType OPTIONAL
if ((content != null) && (content.Count > 0))
contentInfo.Add (content);
return contentInfo;
}
public byte[] GetBytes ()
{
return GetASN1 ().GetBytes ();
}
}
/*
* EncryptedData ::= SEQUENCE {
* version INTEGER {edVer0(0)} (edVer0),
* encryptedContentInfo EncryptedContentInfo
* }
*/
public class EncryptedData {
private byte _version;
private ContentInfo _content;
private ContentInfo _encryptionAlgorithm;
private byte[] _encrypted;
public EncryptedData ()
{
_version = 0;
}
public EncryptedData (byte[] data)
: this (new ASN1 (data))
{
}
public EncryptedData (ASN1 asn1) : this ()
{
if ((asn1.Tag != 0x30) || (asn1.Count < 2))
throw new ArgumentException ("Invalid EncryptedData");
if (asn1 [0].Tag != 0x02)
throw new ArgumentException ("Invalid version");
_version = asn1 [0].Value [0];
ASN1 encryptedContentInfo = asn1 [1];
if (encryptedContentInfo.Tag != 0x30)
throw new ArgumentException ("missing EncryptedContentInfo");
ASN1 contentType = encryptedContentInfo [0];
if (contentType.Tag != 0x06)
throw new ArgumentException ("missing EncryptedContentInfo.ContentType");
_content = new ContentInfo (ASN1Convert.ToOid (contentType));
ASN1 contentEncryptionAlgorithm = encryptedContentInfo [1];
if (contentEncryptionAlgorithm.Tag != 0x30)
throw new ArgumentException ("missing EncryptedContentInfo.ContentEncryptionAlgorithmIdentifier");
_encryptionAlgorithm = new ContentInfo (ASN1Convert.ToOid (contentEncryptionAlgorithm [0]));
_encryptionAlgorithm.Content = contentEncryptionAlgorithm [1];
ASN1 encryptedContent = encryptedContentInfo [2];
if (encryptedContent.Tag != 0x80)
throw new ArgumentException ("missing EncryptedContentInfo.EncryptedContent");
_encrypted = encryptedContent.Value;
}
public ASN1 ASN1 {
get { return GetASN1(); }
}
public ContentInfo ContentInfo {
get { return _content; }
}
public ContentInfo EncryptionAlgorithm {
get { return _encryptionAlgorithm; }
}
public byte[] EncryptedContent {
get {
if (_encrypted == null)
return null;
return (byte[]) _encrypted.Clone ();
}
}
public byte Version {
get { return _version; }
set { _version = value; }
}
// methods
internal ASN1 GetASN1 ()
{
return null;
}
public byte[] GetBytes ()
{
return GetASN1 ().GetBytes ();
}
}
/*
* EnvelopedData ::= SEQUENCE {
* version Version,
* recipientInfos RecipientInfos,
* encryptedContentInfo EncryptedContentInfo
* }
*
* RecipientInfos ::= SET OF RecipientInfo
*
* EncryptedContentInfo ::= SEQUENCE {
* contentType ContentType,
* contentEncryptionAlgorithm ContentEncryptionAlgorithmIdentifier,
* encryptedContent [0] IMPLICIT EncryptedContent OPTIONAL
* }
*
* EncryptedContent ::= OCTET STRING
*
*/
public class EnvelopedData {
private byte _version;
private ContentInfo _content;
private ContentInfo _encryptionAlgorithm;
private ArrayList _recipientInfos;
private byte[] _encrypted;
public EnvelopedData ()
{
_version = 0;
_content = new ContentInfo ();
_encryptionAlgorithm = new ContentInfo ();
_recipientInfos = new ArrayList ();
}
public EnvelopedData (byte[] data)
: this (new ASN1 (data))
{
}
public EnvelopedData (ASN1 asn1) : this ()
{
if ((asn1[0].Tag != 0x30) || (asn1[0].Count < 3))
throw new ArgumentException ("Invalid EnvelopedData");
if (asn1[0][0].Tag != 0x02)
throw new ArgumentException ("Invalid version");
_version = asn1[0][0].Value[0];
// recipientInfos
ASN1 recipientInfos = asn1 [0][1];
if (recipientInfos.Tag != 0x31)
throw new ArgumentException ("missing RecipientInfos");
for (int i=0; i < recipientInfos.Count; i++) {
ASN1 recipientInfo = recipientInfos [i];
_recipientInfos.Add (new RecipientInfo (recipientInfo));
}
ASN1 encryptedContentInfo = asn1[0][2];
if (encryptedContentInfo.Tag != 0x30)
throw new ArgumentException ("missing EncryptedContentInfo");
ASN1 contentType = encryptedContentInfo [0];
if (contentType.Tag != 0x06)
throw new ArgumentException ("missing EncryptedContentInfo.ContentType");
_content = new ContentInfo (ASN1Convert.ToOid (contentType));
ASN1 contentEncryptionAlgorithm = encryptedContentInfo [1];
if (contentEncryptionAlgorithm.Tag != 0x30)
throw new ArgumentException ("missing EncryptedContentInfo.ContentEncryptionAlgorithmIdentifier");
_encryptionAlgorithm = new ContentInfo (ASN1Convert.ToOid (contentEncryptionAlgorithm [0]));
_encryptionAlgorithm.Content = contentEncryptionAlgorithm [1];
ASN1 encryptedContent = encryptedContentInfo [2];
if (encryptedContent.Tag != 0x80)
throw new ArgumentException ("missing EncryptedContentInfo.EncryptedContent");
_encrypted = encryptedContent.Value;
}
public ArrayList RecipientInfos {
get { return _recipientInfos; }
}
public ASN1 ASN1 {
get { return GetASN1(); }
}
public ContentInfo ContentInfo {
get { return _content; }
}
public ContentInfo EncryptionAlgorithm {
get { return _encryptionAlgorithm; }
}
public byte[] EncryptedContent {
get {
if (_encrypted == null)
return null;
return (byte[]) _encrypted.Clone ();
}
}
public byte Version {
get { return _version; }
set { _version = value; }
}
internal ASN1 GetASN1 ()
{
// SignedData ::= SEQUENCE {
ASN1 signedData = new ASN1 (0x30);
// version Version -> Version ::= INTEGER
/* byte[] ver = { _version };
signedData.Add (new ASN1 (0x02, ver));
// digestAlgorithms DigestAlgorithmIdentifiers -> DigestAlgorithmIdentifiers ::= SET OF DigestAlgorithmIdentifier
ASN1 digestAlgorithms = signedData.Add (new ASN1 (0x31));
if (hashAlgorithm != null) {
string hashOid = CryptoConfig.MapNameToOid (hashAlgorithm);
digestAlgorithms.Add (AlgorithmIdentifier (hashOid));
}
// contentInfo ContentInfo,
ASN1 ci = contentInfo.ASN1;
signedData.Add (ci);
if ((mda == null) && (hashAlgorithm != null)) {
// automatically add the messageDigest authenticated attribute
HashAlgorithm ha = HashAlgorithm.Create (hashAlgorithm);
byte[] idcHash = ha.ComputeHash (ci[1][0].Value);
ASN1 md = new ASN1 (0x30);
mda = Attribute (messageDigest, md.Add (new ASN1 (0x04, idcHash)));
signerInfo.AuthenticatedAttributes.Add (mda);
}
// certificates [0] IMPLICIT ExtendedCertificatesAndCertificates OPTIONAL,
if (certs.Count > 0) {
ASN1 a0 = signedData.Add (new ASN1 (0xA0));
foreach (X509Certificate x in certs)
a0.Add (new ASN1 (x.RawData));
}
// crls [1] IMPLICIT CertificateRevocationLists OPTIONAL,
if (crls.Count > 0) {
ASN1 a1 = signedData.Add (new ASN1 (0xA1));
foreach (byte[] crl in crls)
a1.Add (new ASN1 (crl));
}
// signerInfos SignerInfos -> SignerInfos ::= SET OF SignerInfo
ASN1 signerInfos = signedData.Add (new ASN1 (0x31));
if (signerInfo.Key != null)
signerInfos.Add (signerInfo.ASN1);*/
return signedData;
}
public byte[] GetBytes () {
return GetASN1 ().GetBytes ();
}
}
/* RecipientInfo ::= SEQUENCE {
* version Version,
* issuerAndSerialNumber IssuerAndSerialNumber,
* keyEncryptionAlgorithm KeyEncryptionAlgorithmIdentifier,
* encryptedKey EncryptedKey
* }
*
* KeyEncryptionAlgorithmIdentifier ::= AlgorithmIdentifier
*
* EncryptedKey ::= OCTET STRING
*/
public class RecipientInfo {
private int _version;
private string _oid;
private byte[] _key;
private byte[] _ski;
private string _issuer;
private byte[] _serial;
public RecipientInfo () {}
public RecipientInfo (ASN1 data)
{
if (data.Tag != 0x30)
throw new ArgumentException ("Invalid RecipientInfo");
ASN1 version = data [0];
if (version.Tag != 0x02)
throw new ArgumentException ("missing Version");
_version = version.Value [0];
// issuerAndSerialNumber IssuerAndSerialNumber
ASN1 subjectIdentifierType = data [1];
if ((subjectIdentifierType.Tag == 0x80) && (_version == 3)) {
_ski = subjectIdentifierType.Value;
}
else {
_issuer = X501.ToString (subjectIdentifierType [0]);
_serial = subjectIdentifierType [1].Value;
}
ASN1 keyEncryptionAlgorithm = data [2];
_oid = ASN1Convert.ToOid (keyEncryptionAlgorithm [0]);
ASN1 encryptedKey = data [3];
_key = encryptedKey.Value;
}
public string Oid {
get { return _oid; }
}
public byte[] Key {
get {
if (_key == null)
return null;
return (byte[]) _key.Clone ();
}
}
public byte[] SubjectKeyIdentifier {
get {
if (_ski == null)
return null;
return (byte[]) _ski.Clone ();
}
}
public string Issuer {
get { return _issuer; }
}
public byte[] Serial {
get {
if (_serial == null)
return null;
return (byte[]) _serial.Clone ();
}
}
public int Version {
get { return _version; }
}
}
/*
* SignedData ::= SEQUENCE {
* version Version,
* digestAlgorithms DigestAlgorithmIdentifiers,
* contentInfo ContentInfo,
* certificates [0] IMPLICIT ExtendedCertificatesAndCertificates OPTIONAL,
* crls [1] IMPLICIT CertificateRevocationLists OPTIONAL,
* signerInfos SignerInfos
* }
*/
public class SignedData {
private byte version;
private string hashAlgorithm;
private ContentInfo contentInfo;
private X509CertificateCollection certs;
private ArrayList crls;
private SignerInfo signerInfo;
private bool mda;
private bool signed;
public SignedData ()
{
version = 1;
contentInfo = new ContentInfo ();
certs = new X509CertificateCollection ();
crls = new ArrayList ();
signerInfo = new SignerInfo ();
mda = true;
signed = false;
}
public SignedData (byte[] data)
: this (new ASN1 (data))
{
}
public SignedData (ASN1 asn1)
{
if ((asn1[0].Tag != 0x30) || (asn1[0].Count < 4))
throw new ArgumentException ("Invalid SignedData");
if (asn1[0][0].Tag != 0x02)
throw new ArgumentException ("Invalid version");
version = asn1[0][0].Value[0];
contentInfo = new ContentInfo (asn1[0][2]);
int n = 3;
certs = new X509CertificateCollection ();
if (asn1[0][n].Tag == 0xA0) {
for (int i=0; i < asn1[0][n].Count; i++)
certs.Add (new X509Certificate (asn1[0][n][i].GetBytes ()));
n++;
}
crls = new ArrayList ();
if (asn1[0][n].Tag == 0xA1) {
for (int i=0; i < asn1[0][n].Count; i++)
crls.Add (asn1[0][n][i].GetBytes ());
n++;
}
if (asn1[0][n].Count > 0)
signerInfo = new SignerInfo (asn1[0][n]);
else
signerInfo = new SignerInfo ();
// Exchange hash algorithm Oid from SignerInfo
if (signerInfo.HashName != null) {
HashName = OidToName(signerInfo.HashName);
}
// Check if SignerInfo has authenticated attributes
mda = (signerInfo.AuthenticatedAttributes.Count > 0);
}
public ASN1 ASN1 {
get { return GetASN1(); }
}
public X509CertificateCollection Certificates {
get { return certs; }
}
public ContentInfo ContentInfo {
get { return contentInfo; }
}
public ArrayList Crls {
get { return crls; }
}
public string HashName {
get { return hashAlgorithm; }
// todo add validation
set {
hashAlgorithm = value;
signerInfo.HashName = value;
}
}
public SignerInfo SignerInfo {
get { return signerInfo; }
}
public byte Version {
get { return version; }
set { version = value; }
}
public bool UseAuthenticatedAttributes {
get { return mda; }
set { mda = value; }
}
public bool VerifySignature (AsymmetricAlgorithm aa)
{
if (aa == null) {
return false;
}
RSAPKCS1SignatureDeformatter r = new RSAPKCS1SignatureDeformatter (aa);
r.SetHashAlgorithm (hashAlgorithm);
HashAlgorithm ha = HashAlgorithm.Create (hashAlgorithm);
byte[] signature = signerInfo.Signature;
byte[] hash = null;
if (mda) {
ASN1 asn = new ASN1 (0x31);
foreach (ASN1 attr in signerInfo.AuthenticatedAttributes)
asn.Add (attr);
hash = ha.ComputeHash (asn.GetBytes ());
} else {
hash = ha.ComputeHash (contentInfo.Content[0].Value);
}
if (hash != null && signature != null) {
return r.VerifySignature (hash, signature);
}
return false;
}
internal string OidToName (string oid)
{
switch (oid) {
case "1.3.14.3.2.26" :
return "SHA1";
case "1.2.840.113549.2.2" :
return "MD2";
case "1.2.840.113549.2.5" :
return "MD5";
case "2.16.840.1.101.3.4.1" :
return "SHA256";
case "2.16.840.1.101.3.4.2" :
return "SHA384";
case "2.16.840.1.101.3.4.3" :
return "SHA512";
default :
break;
}
// Unknown Oid
return oid;
}
internal ASN1 GetASN1 ()
{
// SignedData ::= SEQUENCE {
ASN1 signedData = new ASN1 (0x30);
// version Version -> Version ::= INTEGER
byte[] ver = { version };
signedData.Add (new ASN1 (0x02, ver));
// digestAlgorithms DigestAlgorithmIdentifiers -> DigestAlgorithmIdentifiers ::= SET OF DigestAlgorithmIdentifier
ASN1 digestAlgorithms = signedData.Add (new ASN1 (0x31));
if (hashAlgorithm != null) {
string hashOid = CryptoConfig.MapNameToOID (hashAlgorithm);
digestAlgorithms.Add (AlgorithmIdentifier (hashOid));
}
// contentInfo ContentInfo,
ASN1 ci = contentInfo.ASN1;
signedData.Add (ci);
if (!signed && (hashAlgorithm != null)) {
if (mda) {
// Use authenticated attributes for signature
// Automatically add the contentType authenticated attribute
ASN1 ctattr = Attribute (Oid.contentType, ci[0]);
signerInfo.AuthenticatedAttributes.Add (ctattr);
// Automatically add the messageDigest authenticated attribute
HashAlgorithm ha = HashAlgorithm.Create (hashAlgorithm);
byte[] idcHash = ha.ComputeHash (ci[1][0].Value);
ASN1 md = new ASN1 (0x30);
ASN1 mdattr = Attribute (Oid.messageDigest, md.Add (new ASN1 (0x04, idcHash)));
signerInfo.AuthenticatedAttributes.Add (mdattr);
} else {
// Don't use authenticated attributes for signature -- signature is content
RSAPKCS1SignatureFormatter r = new RSAPKCS1SignatureFormatter (signerInfo.Key);
r.SetHashAlgorithm (hashAlgorithm);
HashAlgorithm ha = HashAlgorithm.Create (hashAlgorithm);
byte[] sig = ha.ComputeHash (ci[1][0].Value);
signerInfo.Signature = r.CreateSignature (sig);
}
signed = true;
}
// certificates [0] IMPLICIT ExtendedCertificatesAndCertificates OPTIONAL,
if (certs.Count > 0) {
ASN1 a0 = signedData.Add (new ASN1 (0xA0));
foreach (X509Certificate x in certs)
a0.Add (new ASN1 (x.RawData));
}
// crls [1] IMPLICIT CertificateRevocationLists OPTIONAL,
if (crls.Count > 0) {
ASN1 a1 = signedData.Add (new ASN1 (0xA1));
foreach (byte[] crl in crls)
a1.Add (new ASN1 (crl));
}
// signerInfos SignerInfos -> SignerInfos ::= SET OF SignerInfo
ASN1 signerInfos = signedData.Add (new ASN1 (0x31));
if (signerInfo.Key != null)
signerInfos.Add (signerInfo.ASN1);
return signedData;
}
public byte[] GetBytes ()
{
return GetASN1 ().GetBytes ();
}
}
/*
* SignerInfo ::= SEQUENCE {
* version Version,
* issuerAndSerialNumber IssuerAndSerialNumber,
* digestAlgorithm DigestAlgorithmIdentifier,
* authenticatedAttributes [0] IMPLICIT Attributes OPTIONAL,
* digestEncryptionAlgorithm DigestEncryptionAlgorithmIdentifier,
* encryptedDigest EncryptedDigest,
* unauthenticatedAttributes [1] IMPLICIT Attributes OPTIONAL
* }
*
* For version == 3 issuerAndSerialNumber may be replaced by ...
*/
public class SignerInfo {
private byte version;
private X509Certificate x509;
private string hashAlgorithm;
private AsymmetricAlgorithm key;
private ArrayList authenticatedAttributes;
private ArrayList unauthenticatedAttributes;
private byte[] signature;
private string issuer;
private byte[] serial;
private byte[] ski;
public SignerInfo ()
{
version = 1;
authenticatedAttributes = new ArrayList ();
unauthenticatedAttributes = new ArrayList ();
}
public SignerInfo (byte[] data)
: this (new ASN1 (data)) {}
// TODO: INCOMPLETE
public SignerInfo (ASN1 asn1) : this ()
{
if ((asn1[0].Tag != 0x30) || (asn1[0].Count < 5))
throw new ArgumentException ("Invalid SignedData");
// version Version
if (asn1[0][0].Tag != 0x02)
throw new ArgumentException ("Invalid version");
version = asn1[0][0].Value[0];
// issuerAndSerialNumber IssuerAndSerialNumber
ASN1 subjectIdentifierType = asn1 [0][1];
if ((subjectIdentifierType.Tag == 0x80) && (version == 3)) {
ski = subjectIdentifierType.Value;
}
else {
issuer = X501.ToString (subjectIdentifierType [0]);
serial = subjectIdentifierType [1].Value;
}
// digestAlgorithm DigestAlgorithmIdentifier
ASN1 digestAlgorithm = asn1 [0][2];
hashAlgorithm = ASN1Convert.ToOid (digestAlgorithm [0]);
// authenticatedAttributes [0] IMPLICIT Attributes OPTIONAL
int n = 3;
ASN1 authAttributes = asn1 [0][n];
if (authAttributes.Tag == 0xA0) {
n++;
for (int i=0; i < authAttributes.Count; i++)
authenticatedAttributes.Add (authAttributes [i]);
}
// digestEncryptionAlgorithm DigestEncryptionAlgorithmIdentifier
n++;
// ASN1 digestEncryptionAlgorithm = asn1 [0][n++];
// string digestEncryptionAlgorithmOid = ASN1Convert.ToOid (digestEncryptionAlgorithm [0]);
// encryptedDigest EncryptedDigest
ASN1 encryptedDigest = asn1 [0][n++];
if (encryptedDigest.Tag == 0x04)
signature = encryptedDigest.Value;
// unauthenticatedAttributes [1] IMPLICIT Attributes OPTIONAL
ASN1 unauthAttributes = asn1 [0][n];
if ((unauthAttributes != null) && (unauthAttributes.Tag == 0xA1)) {
for (int i=0; i < unauthAttributes.Count; i++)
unauthenticatedAttributes.Add (unauthAttributes [i]);
}
}
public string IssuerName {
get { return issuer; }
}
public byte[] SerialNumber {
get {
if (serial == null)
return null;
return (byte[]) serial.Clone ();
}
}
public byte[] SubjectKeyIdentifier {
get {
if (ski == null)
return null;
return (byte[]) ski.Clone ();
}
}
public ASN1 ASN1 {
get { return GetASN1(); }
}
public ArrayList AuthenticatedAttributes {
get { return authenticatedAttributes; }
}
public X509Certificate Certificate {
get { return x509; }
set { x509 = value; }
}
public string HashName {
get { return hashAlgorithm; }
set { hashAlgorithm = value; }
}
public AsymmetricAlgorithm Key {
get { return key; }
set { key = value; }
}
public byte[] Signature {
get {
if (signature == null)
return null;
return (byte[]) signature.Clone ();
}
set {
if (value != null) {
signature = (byte[]) value.Clone ();
}
}
}
public ArrayList UnauthenticatedAttributes {
get { return unauthenticatedAttributes; }
}
public byte Version {
get { return version; }
set { version = value; }
}
internal ASN1 GetASN1 ()
{
if ((key == null) || (hashAlgorithm == null))
return null;
byte[] ver = { version };
ASN1 signerInfo = new ASN1 (0x30);
// version Version -> Version ::= INTEGER
signerInfo.Add (new ASN1 (0x02, ver));
// issuerAndSerialNumber IssuerAndSerialNumber,
signerInfo.Add (PKCS7.IssuerAndSerialNumber (x509));
// digestAlgorithm DigestAlgorithmIdentifier,
string hashOid = CryptoConfig.MapNameToOID (hashAlgorithm);
signerInfo.Add (AlgorithmIdentifier (hashOid));
// authenticatedAttributes [0] IMPLICIT Attributes OPTIONAL,
ASN1 aa = null;
if (authenticatedAttributes.Count > 0) {
aa = signerInfo.Add (new ASN1 (0xA0));
authenticatedAttributes.Sort(new SortedSet ());
foreach (ASN1 attr in authenticatedAttributes)
aa.Add (attr);
}
// digestEncryptionAlgorithm DigestEncryptionAlgorithmIdentifier,
if (key is RSA) {
signerInfo.Add (AlgorithmIdentifier (PKCS7.Oid.rsaEncryption));
if (aa != null) {
// Calculate the signature here; otherwise it must be set from SignedData
RSAPKCS1SignatureFormatter r = new RSAPKCS1SignatureFormatter (key);
r.SetHashAlgorithm (hashAlgorithm);
byte[] tbs = aa.GetBytes ();
tbs [0] = 0x31; // not 0xA0 for signature
HashAlgorithm ha = HashAlgorithm.Create (hashAlgorithm);
byte[] tbsHash = ha.ComputeHash (tbs);
signature = r.CreateSignature (tbsHash);
}
}
else if (key is DSA) {
throw new NotImplementedException ("not yet");
}
else
throw new CryptographicException ("Unknown assymetric algorithm");
// encryptedDigest EncryptedDigest,
signerInfo.Add (new ASN1 (0x04, signature));
// unauthenticatedAttributes [1] IMPLICIT Attributes OPTIONAL
if (unauthenticatedAttributes.Count > 0) {
ASN1 ua = signerInfo.Add (new ASN1 (0xA1));
unauthenticatedAttributes.Sort(new SortedSet ());
foreach (ASN1 attr in unauthenticatedAttributes)
ua.Add (attr);
}
return signerInfo;
}
public byte[] GetBytes ()
{
return GetASN1 ().GetBytes ();
}
}
internal class SortedSet : IComparer {
public int Compare (object x, object y)
{
if (x == null)
return (y == null) ? 0 : -1;
else if (y == null)
return 1;
ASN1 xx = x as ASN1;
ASN1 yy = y as ASN1;
if ((xx == null) || (yy == null)) {
throw new ArgumentException ("Invalid objects.");
}
byte[] xb = xx.GetBytes ();
byte[] yb = yy.GetBytes ();
for (int i = 0; i < xb.Length; i++) {
if (i == yb.Length)
break;
if (xb[i] == yb[i])
continue;
return (xb[i] < yb[i]) ? -1 : 1;
}
// The arrays are equal up to the shortest of them.
if (xb.Length > yb.Length)
return 1;
else if (xb.Length < yb.Length)
return -1;
return 0;
}
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Reflection;
namespace odatav4webapi.Areas.HelpPage
{
/// <summary>
/// This class will create an object of a given type and populate it with sample data.
/// </summary>
public class ObjectGenerator
{
internal const int DefaultCollectionSize = 2;
private readonly SimpleTypeObjectGenerator SimpleObjectGenerator = new SimpleTypeObjectGenerator();
/// <summary>
/// Generates an object for a given type. The type needs to be public, have a public default constructor and settable public properties/fields. Currently it supports the following types:
/// Simple types: <see cref="int"/>, <see cref="string"/>, <see cref="Enum"/>, <see cref="DateTime"/>, <see cref="Uri"/>, etc.
/// Complex types: POCO types.
/// Nullables: <see cref="Nullable{T}"/>.
/// Arrays: arrays of simple types or complex types.
/// Key value pairs: <see cref="KeyValuePair{TKey,TValue}"/>
/// Tuples: <see cref="Tuple{T1}"/>, <see cref="Tuple{T1,T2}"/>, etc
/// Dictionaries: <see cref="IDictionary{TKey,TValue}"/> or anything deriving from <see cref="IDictionary{TKey,TValue}"/>.
/// Collections: <see cref="IList{T}"/>, <see cref="IEnumerable{T}"/>, <see cref="ICollection{T}"/>, <see cref="IList"/>, <see cref="IEnumerable"/>, <see cref="ICollection"/> or anything deriving from <see cref="ICollection{T}"/> or <see cref="IList"/>.
/// Queryables: <see cref="IQueryable"/>, <see cref="IQueryable{T}"/>.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>An object of the given type.</returns>
public object GenerateObject(Type type)
{
return GenerateObject(type, new Dictionary<Type, object>());
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Here we just want to return null if anything goes wrong.")]
private object GenerateObject(Type type, Dictionary<Type, object> createdObjectReferences)
{
try
{
if (SimpleTypeObjectGenerator.CanGenerateObject(type))
{
return SimpleObjectGenerator.GenerateObject(type);
}
if (type.IsArray)
{
return GenerateArray(type, DefaultCollectionSize, createdObjectReferences);
}
if (type.IsGenericType)
{
return GenerateGenericType(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IDictionary))
{
return GenerateDictionary(typeof(Hashtable), DefaultCollectionSize, createdObjectReferences);
}
if (typeof(IDictionary).IsAssignableFrom(type))
{
return GenerateDictionary(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IList) ||
type == typeof(IEnumerable) ||
type == typeof(ICollection))
{
return GenerateCollection(typeof(ArrayList), DefaultCollectionSize, createdObjectReferences);
}
if (typeof(IList).IsAssignableFrom(type))
{
return GenerateCollection(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IQueryable))
{
return GenerateQueryable(type, DefaultCollectionSize, createdObjectReferences);
}
if (type.IsEnum)
{
return GenerateEnum(type);
}
if (type.IsPublic || type.IsNestedPublic)
{
return GenerateComplexObject(type, createdObjectReferences);
}
}
catch
{
// Returns null if anything fails
return null;
}
return null;
}
private static object GenerateGenericType(Type type, int collectionSize, Dictionary<Type, object> createdObjectReferences)
{
Type genericTypeDefinition = type.GetGenericTypeDefinition();
if (genericTypeDefinition == typeof(Nullable<>))
{
return GenerateNullable(type, createdObjectReferences);
}
if (genericTypeDefinition == typeof(KeyValuePair<,>))
{
return GenerateKeyValuePair(type, createdObjectReferences);
}
if (IsTuple(genericTypeDefinition))
{
return GenerateTuple(type, createdObjectReferences);
}
Type[] genericArguments = type.GetGenericArguments();
if (genericArguments.Length == 1)
{
if (genericTypeDefinition == typeof(IList<>) ||
genericTypeDefinition == typeof(IEnumerable<>) ||
genericTypeDefinition == typeof(ICollection<>))
{
Type collectionType = typeof(List<>).MakeGenericType(genericArguments);
return GenerateCollection(collectionType, collectionSize, createdObjectReferences);
}
if (genericTypeDefinition == typeof(IQueryable<>))
{
return GenerateQueryable(type, collectionSize, createdObjectReferences);
}
Type closedCollectionType = typeof(ICollection<>).MakeGenericType(genericArguments[0]);
if (closedCollectionType.IsAssignableFrom(type))
{
return GenerateCollection(type, collectionSize, createdObjectReferences);
}
}
if (genericArguments.Length == 2)
{
if (genericTypeDefinition == typeof(IDictionary<,>))
{
Type dictionaryType = typeof(Dictionary<,>).MakeGenericType(genericArguments);
return GenerateDictionary(dictionaryType, collectionSize, createdObjectReferences);
}
Type closedDictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments[0], genericArguments[1]);
if (closedDictionaryType.IsAssignableFrom(type))
{
return GenerateDictionary(type, collectionSize, createdObjectReferences);
}
}
if (type.IsPublic || type.IsNestedPublic)
{
return GenerateComplexObject(type, createdObjectReferences);
}
return null;
}
private static object GenerateTuple(Type type, Dictionary<Type, object> createdObjectReferences)
{
Type[] genericArgs = type.GetGenericArguments();
object[] parameterValues = new object[genericArgs.Length];
bool failedToCreateTuple = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < genericArgs.Length; i++)
{
parameterValues[i] = objectGenerator.GenerateObject(genericArgs[i], createdObjectReferences);
failedToCreateTuple &= parameterValues[i] == null;
}
if (failedToCreateTuple)
{
return null;
}
object result = Activator.CreateInstance(type, parameterValues);
return result;
}
private static bool IsTuple(Type genericTypeDefinition)
{
return genericTypeDefinition == typeof(Tuple<>) ||
genericTypeDefinition == typeof(Tuple<,>) ||
genericTypeDefinition == typeof(Tuple<,,>) ||
genericTypeDefinition == typeof(Tuple<,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,,,>);
}
private static object GenerateKeyValuePair(Type keyValuePairType, Dictionary<Type, object> createdObjectReferences)
{
Type[] genericArgs = keyValuePairType.GetGenericArguments();
Type typeK = genericArgs[0];
Type typeV = genericArgs[1];
ObjectGenerator objectGenerator = new ObjectGenerator();
object keyObject = objectGenerator.GenerateObject(typeK, createdObjectReferences);
object valueObject = objectGenerator.GenerateObject(typeV, createdObjectReferences);
if (keyObject == null && valueObject == null)
{
// Failed to create key and values
return null;
}
object result = Activator.CreateInstance(keyValuePairType, keyObject, valueObject);
return result;
}
private static object GenerateArray(Type arrayType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type type = arrayType.GetElementType();
Array result = Array.CreateInstance(type, size);
bool areAllElementsNull = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object element = objectGenerator.GenerateObject(type, createdObjectReferences);
result.SetValue(element, i);
areAllElementsNull &= element == null;
}
if (areAllElementsNull)
{
return null;
}
return result;
}
private static object GenerateDictionary(Type dictionaryType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type typeK = typeof(object);
Type typeV = typeof(object);
if (dictionaryType.IsGenericType)
{
Type[] genericArgs = dictionaryType.GetGenericArguments();
typeK = genericArgs[0];
typeV = genericArgs[1];
}
object result = Activator.CreateInstance(dictionaryType);
MethodInfo addMethod = dictionaryType.GetMethod("Add") ?? dictionaryType.GetMethod("TryAdd");
MethodInfo containsMethod = dictionaryType.GetMethod("Contains") ?? dictionaryType.GetMethod("ContainsKey");
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object newKey = objectGenerator.GenerateObject(typeK, createdObjectReferences);
if (newKey == null)
{
// Cannot generate a valid key
return null;
}
bool containsKey = (bool)containsMethod.Invoke(result, new object[] { newKey });
if (!containsKey)
{
object newValue = objectGenerator.GenerateObject(typeV, createdObjectReferences);
addMethod.Invoke(result, new object[] { newKey, newValue });
}
}
return result;
}
private static object GenerateEnum(Type enumType)
{
Array possibleValues = Enum.GetValues(enumType);
if (possibleValues.Length > 0)
{
return possibleValues.GetValue(0);
}
return null;
}
private static object GenerateQueryable(Type queryableType, int size, Dictionary<Type, object> createdObjectReferences)
{
bool isGeneric = queryableType.IsGenericType;
object list;
if (isGeneric)
{
Type listType = typeof(List<>).MakeGenericType(queryableType.GetGenericArguments());
list = GenerateCollection(listType, size, createdObjectReferences);
}
else
{
list = GenerateArray(typeof(object[]), size, createdObjectReferences);
}
if (list == null)
{
return null;
}
if (isGeneric)
{
Type argumentType = typeof(IEnumerable<>).MakeGenericType(queryableType.GetGenericArguments());
MethodInfo asQueryableMethod = typeof(Queryable).GetMethod("AsQueryable", new[] { argumentType });
return asQueryableMethod.Invoke(null, new[] { list });
}
return Queryable.AsQueryable((IEnumerable)list);
}
private static object GenerateCollection(Type collectionType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type type = collectionType.IsGenericType ?
collectionType.GetGenericArguments()[0] :
typeof(object);
object result = Activator.CreateInstance(collectionType);
MethodInfo addMethod = collectionType.GetMethod("Add");
bool areAllElementsNull = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object element = objectGenerator.GenerateObject(type, createdObjectReferences);
addMethod.Invoke(result, new object[] { element });
areAllElementsNull &= element == null;
}
if (areAllElementsNull)
{
return null;
}
return result;
}
private static object GenerateNullable(Type nullableType, Dictionary<Type, object> createdObjectReferences)
{
Type type = nullableType.GetGenericArguments()[0];
ObjectGenerator objectGenerator = new ObjectGenerator();
return objectGenerator.GenerateObject(type, createdObjectReferences);
}
private static object GenerateComplexObject(Type type, Dictionary<Type, object> createdObjectReferences)
{
object result = null;
if (createdObjectReferences.TryGetValue(type, out result))
{
// The object has been created already, just return it. This will handle the circular reference case.
return result;
}
if (type.IsValueType)
{
result = Activator.CreateInstance(type);
}
else
{
ConstructorInfo defaultCtor = type.GetConstructor(Type.EmptyTypes);
if (defaultCtor == null)
{
// Cannot instantiate the type because it doesn't have a default constructor
return null;
}
result = defaultCtor.Invoke(new object[0]);
}
createdObjectReferences.Add(type, result);
SetPublicProperties(type, result, createdObjectReferences);
SetPublicFields(type, result, createdObjectReferences);
return result;
}
private static void SetPublicProperties(Type type, object obj, Dictionary<Type, object> createdObjectReferences)
{
PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance);
ObjectGenerator objectGenerator = new ObjectGenerator();
foreach (PropertyInfo property in properties)
{
if (property.CanWrite)
{
object propertyValue = objectGenerator.GenerateObject(property.PropertyType, createdObjectReferences);
property.SetValue(obj, propertyValue, null);
}
}
}
private static void SetPublicFields(Type type, object obj, Dictionary<Type, object> createdObjectReferences)
{
FieldInfo[] fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance);
ObjectGenerator objectGenerator = new ObjectGenerator();
foreach (FieldInfo field in fields)
{
object fieldValue = objectGenerator.GenerateObject(field.FieldType, createdObjectReferences);
field.SetValue(obj, fieldValue);
}
}
private class SimpleTypeObjectGenerator
{
private long _index = 0;
private static readonly Dictionary<Type, Func<long, object>> DefaultGenerators = InitializeGenerators();
[SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "These are simple type factories and cannot be split up.")]
private static Dictionary<Type, Func<long, object>> InitializeGenerators()
{
return new Dictionary<Type, Func<long, object>>
{
{ typeof(Boolean), index => true },
{ typeof(Byte), index => (Byte)64 },
{ typeof(Char), index => (Char)65 },
{ typeof(DateTime), index => DateTime.Now },
{ typeof(DateTimeOffset), index => new DateTimeOffset(DateTime.Now) },
{ typeof(DBNull), index => DBNull.Value },
{ typeof(Decimal), index => (Decimal)index },
{ typeof(Double), index => (Double)(index + 0.1) },
{ typeof(Guid), index => Guid.NewGuid() },
{ typeof(Int16), index => (Int16)(index % Int16.MaxValue) },
{ typeof(Int32), index => (Int32)(index % Int32.MaxValue) },
{ typeof(Int64), index => (Int64)index },
{ typeof(Object), index => new object() },
{ typeof(SByte), index => (SByte)64 },
{ typeof(Single), index => (Single)(index + 0.1) },
{
typeof(String), index =>
{
return String.Format(CultureInfo.CurrentCulture, "sample string {0}", index);
}
},
{
typeof(TimeSpan), index =>
{
return TimeSpan.FromTicks(1234567);
}
},
{ typeof(UInt16), index => (UInt16)(index % UInt16.MaxValue) },
{ typeof(UInt32), index => (UInt32)(index % UInt32.MaxValue) },
{ typeof(UInt64), index => (UInt64)index },
{
typeof(Uri), index =>
{
return new Uri(String.Format(CultureInfo.CurrentCulture, "http://webapihelppage{0}.com", index));
}
},
};
}
public static bool CanGenerateObject(Type type)
{
return DefaultGenerators.ContainsKey(type);
}
public object GenerateObject(Type type)
{
return DefaultGenerators[type](++_index);
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Globalization;
using System.Text;
using System.Text.Unicode.Tests;
using Xunit;
using Xunit.Sdk;
namespace System.Tests
{
public class CharTests
{
[Theory]
[InlineData('h', 'h', 0)]
[InlineData('h', 'a', 1)]
[InlineData('h', 'z', -1)]
[InlineData('h', null, 1)]
public void CompareTo_Other_ReturnsExpected(char c, object value, int expected)
{
if (value is char charValue)
{
Assert.Equal(expected, Math.Sign(c.CompareTo(charValue)));
}
Assert.Equal(expected, Math.Sign(c.CompareTo(value)));
}
[Theory]
[InlineData("a")]
[InlineData(234)]
public void CompareTo_ObjectNotDouble_ThrowsArgumentException(object value)
{
AssertExtensions.Throws<ArgumentException>(null, () => ((char)123).CompareTo(value));
}
public static IEnumerable<object[]> ConvertFromUtf32_TestData()
{
yield return new object[] { 0x10000, "\uD800\uDC00" };
yield return new object[] { 0x103FF, "\uD800\uDFFF" };
yield return new object[] { 0xFFFFF, "\uDBBF\uDFFF" };
yield return new object[] { 0x10FC00, "\uDBFF\uDC00" };
yield return new object[] { 0x10FFFF, "\uDBFF\uDFFF" };
yield return new object[] { 0, "\0" };
yield return new object[] { 0x3FF, "\u03FF" };
yield return new object[] { 0xE000, "\uE000" };
yield return new object[] { 0xFFFF, "\uFFFF" };
}
[Theory]
[MemberData(nameof(ConvertFromUtf32_TestData))]
public static void ConvertFromUtf32(int utf32, string expected)
{
Assert.Equal(expected, char.ConvertFromUtf32(utf32));
}
[Theory]
[InlineData(0xD800)]
[InlineData(0xDC00)]
[InlineData(0xDFFF)]
[InlineData(0x110000)]
[InlineData(-1)]
[InlineData(int.MaxValue)]
[InlineData(int.MinValue)]
public static void ConvertFromUtf32_InvalidUtf32_ThrowsArgumentOutOfRangeException(int utf32)
{
AssertExtensions.Throws<ArgumentOutOfRangeException>("utf32", () => char.ConvertFromUtf32(utf32));
}
public static IEnumerable<object[]> ConvertToUtf32_String_Int_TestData()
{
yield return new object[] { "\uD800\uDC00", 0, 0x10000 };
yield return new object[] { "\uDBBF\uDFFF", 0, 0xFFFFF };
yield return new object[] { "\uDBFF\uDC00", 0, 0x10FC00 };
yield return new object[] { "\uDBFF\uDFFF", 0, 0x10FFFF };
yield return new object[] { "\u0000\u0001", 0, 0 };
yield return new object[] { "\u0000\u0001", 1, 1 };
yield return new object[] { "\u0000", 0, 0 };
yield return new object[] { "\u0020\uD7FF", 0, 32 };
yield return new object[] { "\u0020\uD7FF", 1, 0xD7FF };
yield return new object[] { "abcde", 4, 'e' };
// Invalid unicode
yield return new object[] { "\uD800\uD800\uDFFF", 1, 0x103FF };
yield return new object[] { "\uD800\uD7FF", 1, 0xD7FF }; // High, non-surrogate
yield return new object[] { "\uD800\u0000", 1, 0 }; // High, non-surrogate
yield return new object[] { "\uDF01\u0000", 1, 0 }; // Low, non-surrogate
}
[Theory]
[MemberData(nameof(ConvertToUtf32_String_Int_TestData))]
public static void ConvertToUtf32_String_Int(string s, int index, int expected)
{
Assert.Equal(expected, char.ConvertToUtf32(s, index));
}
[Fact]
public static void ConvertToUtf32_String_Int_Invalid()
{
AssertExtensions.Throws<ArgumentNullException>("s", () => char.ConvertToUtf32(null, 0)); // String is null
AssertExtensions.Throws<ArgumentException>("s", () => char.ConvertToUtf32("\uD800\uD800", 0)); // High, high
AssertExtensions.Throws<ArgumentException>("s", () => char.ConvertToUtf32("\uD800\uD800", 1)); // High, high
AssertExtensions.Throws<ArgumentException>("s", () => char.ConvertToUtf32("\uD800\uD7FF", 0)); // High, non-surrogate
AssertExtensions.Throws<ArgumentException>("s", () => char.ConvertToUtf32("\uD800\u0000", 0)); // High, non-surrogate
AssertExtensions.Throws<ArgumentException>("s", () => char.ConvertToUtf32("\uDC01\uD940", 0)); // Low, high
AssertExtensions.Throws<ArgumentException>("s", () => char.ConvertToUtf32("\uDC01\uD940", 1)); // Low, high
AssertExtensions.Throws<ArgumentException>("s", () => char.ConvertToUtf32("\uDD00\uDE00", 0)); // Low, low
AssertExtensions.Throws<ArgumentException>("s", () => char.ConvertToUtf32("\uDD00\uDE00", 1)); // Low, hig
AssertExtensions.Throws<ArgumentException>("s", () => char.ConvertToUtf32("\uDF01\u0000", 0)); // Low, non-surrogateh
AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => char.ConvertToUtf32("abcde", -1)); // Index < 0
AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => char.ConvertToUtf32("abcde", 5)); // Index >= string.Length
AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => char.ConvertToUtf32("", 0)); // Index >= string.Length
}
public static IEnumerable<object[]> ConvertToUtf32_Char_Char_TestData()
{
yield return new object[] { '\uD800', '\uDC00', 0x10000 };
yield return new object[] { '\uD800', '\uDFFF', 0x103FF };
yield return new object[] { '\uDBBF', '\uDFFF', 0xFFFFF };
yield return new object[] { '\uDBFF', '\uDC00', 0x10FC00 };
yield return new object[] { '\uDBFF', '\uDFFF', 0x10FFFF };
}
[Theory]
[MemberData(nameof(ConvertToUtf32_Char_Char_TestData))]
public static void ConvertToUtf32_Char_Char(char highSurrogate, char lowSurrogate, int expected)
{
Assert.Equal(expected, char.ConvertToUtf32(highSurrogate, lowSurrogate));
}
[Fact]
public static void ConvertToUtf32_Char_Char_Invalid()
{
AssertExtensions.Throws<ArgumentOutOfRangeException>("lowSurrogate", () => char.ConvertToUtf32('\uD800', '\uD800')); // High, high
AssertExtensions.Throws<ArgumentOutOfRangeException>("lowSurrogate", () => char.ConvertToUtf32('\uD800', '\uD7FF')); // High, non-surrogate
AssertExtensions.Throws<ArgumentOutOfRangeException>("lowSurrogate", () => char.ConvertToUtf32('\uD800', '\u0000')); // High, non-surrogate
AssertExtensions.Throws<ArgumentOutOfRangeException>("highSurrogate", () => char.ConvertToUtf32('\uDD00', '\uDE00')); // Low, low
AssertExtensions.Throws<ArgumentOutOfRangeException>("highSurrogate", () => char.ConvertToUtf32('\uDC01', '\uD940')); // Low, high
AssertExtensions.Throws<ArgumentOutOfRangeException>("highSurrogate", () => char.ConvertToUtf32('\uDF01', '\u0000')); // Low, non-surrogate
AssertExtensions.Throws<ArgumentOutOfRangeException>("highSurrogate", () => char.ConvertToUtf32('\u0032', '\uD7FF')); // Non-surrogate, non-surrogate
AssertExtensions.Throws<ArgumentOutOfRangeException>("highSurrogate", () => char.ConvertToUtf32('\u0000', '\u0000')); // Non-surrogate, non-surrogate
}
[Theory]
[InlineData('a', 'a', true)]
[InlineData('a', 'A', false)]
[InlineData('a', 'b', false)]
[InlineData('a', (int)'a', false)]
[InlineData('a', "a", false)]
[InlineData('a', null, false)]
public static void Equals(char c, object obj, bool expected)
{
if (obj is char)
{
Assert.Equal(expected, c.Equals((char)obj));
Assert.Equal(expected, c.GetHashCode().Equals(obj.GetHashCode()));
}
Assert.Equal(expected, c.Equals(obj));
}
[Theory]
[InlineData('0', 0)]
[InlineData('9', 9)]
[InlineData('T', -1)]
public static void GetNumericValue_Char(char c, int expected)
{
Assert.Equal(expected, char.GetNumericValue(c));
}
[Theory]
[InlineData("\uD800\uDD07", 0, 1)]
[InlineData("9", 0, 9)]
[InlineData("99", 1, 9)]
[InlineData(" 7 ", 1, 7)]
[InlineData("Test 7", 5, 7)]
[InlineData("T", 0, -1)]
public static void GetNumericValue_String_Int(string s, int index, int expected)
{
Assert.Equal(expected, char.GetNumericValue(s, index));
}
[Fact]
public static void GetNumericValue_String_Int_Invalid()
{
AssertExtensions.Throws<ArgumentNullException>("s", () => char.GetNumericValue(null, 0)); // String is null
AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => char.GetNumericValue("abc", -1)); // Index < 0
AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => char.GetNumericValue("abc", 3)); // Index >= string.Length
}
[Fact]
public void GetTypeCode_Invoke_ReturnsBoolean()
{
Assert.Equal(TypeCode.Char, 'a'.GetTypeCode());
}
[Fact]
public static void IsControl_Char()
{
foreach (char c in GetTestChars(UnicodeCategory.Control))
Assert.True(char.IsControl(c));
foreach (char c in GetTestCharsNotInCategory(UnicodeCategory.Control))
Assert.False(char.IsControl(c));
}
[Fact]
public static void IsControl_String_Int()
{
foreach (char c in GetTestChars(UnicodeCategory.Control))
Assert.True(char.IsControl(c.ToString(), 0));
foreach (char c in GetTestCharsNotInCategory(UnicodeCategory.Control))
Assert.False(char.IsControl(c.ToString(), 0));
}
[Fact]
public static void IsControl_String_Int_Invalid()
{
AssertExtensions.Throws<ArgumentNullException>("s", () => char.IsControl(null, 0)); // String is null
AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => char.IsControl("abc", -1)); // Index < 0
AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => char.IsControl("abc", 3)); // Index >= string.Length
}
[Fact]
public static void IsDigit_Char()
{
foreach (char c in GetTestChars(UnicodeCategory.DecimalDigitNumber))
Assert.True(char.IsDigit(c));
foreach (char c in GetTestCharsNotInCategory(UnicodeCategory.DecimalDigitNumber))
Assert.False(char.IsDigit(c));
}
[Fact]
public static void IsDigit_String_Int()
{
foreach (char c in GetTestChars(UnicodeCategory.DecimalDigitNumber))
Assert.True(char.IsDigit(c.ToString(), 0));
foreach (char c in GetTestCharsNotInCategory(UnicodeCategory.DecimalDigitNumber))
Assert.False(char.IsDigit(c.ToString(), 0));
}
[Fact]
public static void IsDigit_String_Int_Invalid()
{
AssertExtensions.Throws<ArgumentNullException>("s", () => char.IsDigit(null, 0)); // String is null
AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => char.IsDigit("abc", -1)); // Index < 0
AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => char.IsDigit("abc", 3)); // Index >= string.Length
}
[Fact]
public static void IsLetter_Char()
{
var categories = new UnicodeCategory[]
{
UnicodeCategory.UppercaseLetter,
UnicodeCategory.LowercaseLetter,
UnicodeCategory.TitlecaseLetter,
UnicodeCategory.ModifierLetter,
UnicodeCategory.OtherLetter
};
foreach (char c in GetTestChars(categories))
Assert.True(char.IsLetter(c));
foreach (char c in GetTestCharsNotInCategory(categories))
Assert.False(char.IsLetter(c));
}
[Fact]
public static void IsLetter_String_Int()
{
var categories = new UnicodeCategory[]
{
UnicodeCategory.UppercaseLetter,
UnicodeCategory.LowercaseLetter,
UnicodeCategory.TitlecaseLetter,
UnicodeCategory.ModifierLetter,
UnicodeCategory.OtherLetter
};
foreach (char c in GetTestChars(categories))
Assert.True(char.IsLetter(c.ToString(), 0));
foreach (char c in GetTestCharsNotInCategory(categories))
Assert.False(char.IsLetter(c.ToString(), 0));
}
[Fact]
public static void IsLetter_String_Int_Invalid()
{
AssertExtensions.Throws<ArgumentNullException>("s", () => char.IsLetter(null, 0)); // String is null
AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => char.IsLetter("abc", -1)); // Index < 0
AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => char.IsLetter("abc", 3)); // Index >= string.Length
}
[Fact]
public static void IsLetterOrDigit_Char()
{
var categories = new UnicodeCategory[]
{
UnicodeCategory.UppercaseLetter,
UnicodeCategory.LowercaseLetter,
UnicodeCategory.TitlecaseLetter,
UnicodeCategory.ModifierLetter,
UnicodeCategory.OtherLetter,
UnicodeCategory.DecimalDigitNumber
};
foreach (char c in GetTestChars(categories))
Assert.True(char.IsLetterOrDigit(c));
foreach (char c in GetTestCharsNotInCategory(categories))
Assert.False(char.IsLetterOrDigit(c));
}
[Fact]
public static void IsLetterOrDigit_String_Int()
{
var categories = new UnicodeCategory[]
{
UnicodeCategory.UppercaseLetter,
UnicodeCategory.LowercaseLetter,
UnicodeCategory.TitlecaseLetter,
UnicodeCategory.ModifierLetter,
UnicodeCategory.OtherLetter,
UnicodeCategory.DecimalDigitNumber
};
foreach (char c in GetTestChars(categories))
Assert.True(char.IsLetterOrDigit(c.ToString(), 0));
foreach (char c in GetTestCharsNotInCategory(categories))
Assert.False(char.IsLetterOrDigit(c.ToString(), 0));
}
[Fact]
public static void IsLetterOrDigit_String_Int_Invalid()
{
AssertExtensions.Throws<ArgumentNullException>("s", () => char.IsLetterOrDigit(null, 0)); // String is null
AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => char.IsLetterOrDigit("abc", -1)); // Index < 0
AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => char.IsLetterOrDigit("abc", 3)); // Index >= string.Length
}
[Fact]
public static void IsLower_Char()
{
foreach (char c in GetTestChars(UnicodeCategory.LowercaseLetter))
Assert.True(char.IsLower(c));
foreach (char c in GetTestCharsNotInCategory(UnicodeCategory.LowercaseLetter))
Assert.False(char.IsLower(c));
}
[Fact]
public static void IsLower_String_Int()
{
foreach (char c in GetTestChars(UnicodeCategory.LowercaseLetter))
Assert.True(char.IsLower(c.ToString(), 0));
foreach (char c in GetTestCharsNotInCategory(UnicodeCategory.LowercaseLetter))
Assert.False(char.IsLower(c.ToString(), 0));
}
[Fact]
public static void IsLower_String_Int_Invalid()
{
AssertExtensions.Throws<ArgumentNullException>("s", () => char.IsLower(null, 0)); // String is null
AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => char.IsLower("abc", -1)); // Index < 0
AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => char.IsLower("abc", 3)); // Index >= string.Length
}
[Fact]
public static void IsNumber_Char()
{
var categories = new UnicodeCategory[]
{
UnicodeCategory.DecimalDigitNumber,
UnicodeCategory.LetterNumber,
UnicodeCategory.OtherNumber
};
foreach (char c in GetTestChars(categories))
Assert.True(char.IsNumber(c));
foreach (char c in GetTestCharsNotInCategory(categories))
Assert.False(char.IsNumber(c));
}
[Fact]
public static void IsNumber_String_Int()
{
var categories = new UnicodeCategory[]
{
UnicodeCategory.DecimalDigitNumber,
UnicodeCategory.LetterNumber,
UnicodeCategory.OtherNumber
};
foreach (char c in GetTestChars(categories))
Assert.True(char.IsNumber(c.ToString(), 0));
foreach (char c in GetTestCharsNotInCategory(categories))
Assert.False(char.IsNumber(c.ToString(), 0));
}
[Fact]
public static void IsNumber_String_Int_Invalid()
{
AssertExtensions.Throws<ArgumentNullException>("s", () => char.IsNumber(null, 0)); // String is null
AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => char.IsNumber("abc", -1)); // Index < 0
AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => char.IsNumber("abc", 3)); // Index >= string.Length
}
[Fact]
public static void IsPunctuation_Char()
{
var categories = new UnicodeCategory[]
{
UnicodeCategory.ConnectorPunctuation,
UnicodeCategory.DashPunctuation,
UnicodeCategory.OpenPunctuation,
UnicodeCategory.ClosePunctuation,
UnicodeCategory.InitialQuotePunctuation,
UnicodeCategory.FinalQuotePunctuation,
UnicodeCategory.OtherPunctuation
};
foreach (char c in GetTestChars(categories))
Assert.True(char.IsPunctuation(c));
foreach (char c in GetTestCharsNotInCategory(categories))
Assert.False(char.IsPunctuation(c));
}
[Fact]
public static void IsPunctuation_String_Int()
{
var categories = new UnicodeCategory[]
{
UnicodeCategory.ConnectorPunctuation,
UnicodeCategory.DashPunctuation,
UnicodeCategory.OpenPunctuation,
UnicodeCategory.ClosePunctuation,
UnicodeCategory.InitialQuotePunctuation,
UnicodeCategory.FinalQuotePunctuation,
UnicodeCategory.OtherPunctuation
};
foreach (char c in GetTestChars(categories))
Assert.True(char.IsPunctuation(c.ToString(), 0));
foreach (char c in GetTestCharsNotInCategory(categories))
Assert.False(char.IsPunctuation(c.ToString(), 0));
}
[Fact]
public static void IsPunctuation_String_Int_Invalid()
{
AssertExtensions.Throws<ArgumentNullException>("s", () => char.IsPunctuation(null, 0)); // String is null
AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => char.IsPunctuation("abc", -1)); // Index < 0
AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => char.IsPunctuation("abc", 3)); // Index >= string.Length
}
[Fact]
public static void IsSeparator_Char()
{
var categories = new UnicodeCategory[]
{
UnicodeCategory.SpaceSeparator,
UnicodeCategory.LineSeparator,
UnicodeCategory.ParagraphSeparator
};
foreach (char c in GetTestChars(categories))
Assert.True(char.IsSeparator(c));
foreach (char c in GetTestCharsNotInCategory(categories))
Assert.False(char.IsSeparator(c));
}
[Fact]
public static void IsSeparator_String_Int()
{
var categories = new UnicodeCategory[]
{
UnicodeCategory.SpaceSeparator,
UnicodeCategory.LineSeparator,
UnicodeCategory.ParagraphSeparator
};
foreach (char c in GetTestChars(categories))
Assert.True(char.IsSeparator(c.ToString(), 0));
foreach (char c in GetTestCharsNotInCategory(categories))
Assert.False(char.IsSeparator(c.ToString(), 0));
}
[Fact]
public static void IsSeparator_String_Int_Invalid()
{
AssertExtensions.Throws<ArgumentNullException>("s", () => char.IsSeparator(null, 0)); // String is null
AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => char.IsSeparator("abc", -1)); // Index < 0
AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => char.IsSeparator("abc", 3)); // Index >= string.Length
}
[Fact]
public static void IsLowSurrogate_Char()
{
foreach (char c in s_lowSurrogates)
Assert.True(char.IsLowSurrogate(c));
foreach (char c in s_highSurrogates)
Assert.False(char.IsLowSurrogate(c));
foreach (char c in s_nonSurrogates)
Assert.False(char.IsLowSurrogate(c));
}
[Fact]
public static void IsLowSurrogate_String_Int()
{
foreach (char c in s_lowSurrogates)
Assert.True(char.IsLowSurrogate(c.ToString(), 0));
foreach (char c in s_highSurrogates)
Assert.False(char.IsLowSurrogate(c.ToString(), 0));
foreach (char c in s_nonSurrogates)
Assert.False(char.IsLowSurrogate(c.ToString(), 0));
}
[Fact]
public static void IsLowSurrogate_String_Int_Invalid()
{
AssertExtensions.Throws<ArgumentNullException>("s", () => char.IsLowSurrogate(null, 0)); // String is null
AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => char.IsLowSurrogate("abc", -1)); // Index < 0
AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => char.IsLowSurrogate("abc", 3)); // Index >= string.Length
}
[Fact]
public static void IsHighSurrogate_Char()
{
foreach (char c in s_highSurrogates)
Assert.True(char.IsHighSurrogate(c));
foreach (char c in s_lowSurrogates)
Assert.False(char.IsHighSurrogate(c));
foreach (char c in s_nonSurrogates)
Assert.False(char.IsHighSurrogate(c));
}
[Fact]
public static void IsHighSurrogate_String_Int()
{
foreach (char c in s_highSurrogates)
Assert.True(char.IsHighSurrogate(c.ToString(), 0));
foreach (char c in s_lowSurrogates)
Assert.False(char.IsHighSurrogate(c.ToString(), 0));
foreach (char c in s_nonSurrogates)
Assert.False(char.IsHighSurrogate(c.ToString(), 0));
}
[Fact]
public static void IsHighSurrogate_String_Int_Invalid()
{
AssertExtensions.Throws<ArgumentNullException>("s", () => char.IsHighSurrogate(null, 0)); // String is null
AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => char.IsHighSurrogate("abc", -1)); // Index < 0
AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => char.IsHighSurrogate("abc", 3)); // Index >= string.Length
}
[Fact]
public static void IsSurrogate_Char()
{
foreach (char c in s_highSurrogates)
Assert.True(char.IsSurrogate(c));
foreach (char c in s_lowSurrogates)
Assert.True(char.IsSurrogate(c));
foreach (char c in s_nonSurrogates)
Assert.False(char.IsSurrogate(c));
}
[Fact]
public static void IsSurrogate_String_Int()
{
foreach (char c in s_highSurrogates)
Assert.True(char.IsSurrogate(c.ToString(), 0));
foreach (char c in s_lowSurrogates)
Assert.True(char.IsSurrogate(c.ToString(), 0));
foreach (char c in s_nonSurrogates)
Assert.False(char.IsSurrogate(c.ToString(), 0));
}
[Fact]
public static void IsSurrogate_String_Int_Invalid()
{
AssertExtensions.Throws<ArgumentNullException>("s", () => char.IsSurrogate(null, 0)); // String is null
AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => char.IsSurrogate("abc", -1)); // Index < 0
AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => char.IsSurrogate("abc", 3)); // Index >= string.Length
}
[Fact]
public static void IsSurrogatePair_Char()
{
foreach (char hs in s_highSurrogates)
foreach (char ls in s_lowSurrogates)
Assert.True(char.IsSurrogatePair(hs, ls));
foreach (char hs in s_nonSurrogates)
foreach (char ls in s_lowSurrogates)
Assert.False(char.IsSurrogatePair(hs, ls));
foreach (char hs in s_highSurrogates)
foreach (char ls in s_nonSurrogates)
Assert.False(char.IsSurrogatePair(hs, ls));
}
[Fact]
public static void IsSurrogatePair_String_Int()
{
foreach (char hs in s_highSurrogates)
foreach (char ls in s_lowSurrogates)
Assert.True(char.IsSurrogatePair(hs.ToString() + ls, 0));
foreach (char hs in s_nonSurrogates)
foreach (char ls in s_lowSurrogates)
Assert.False(char.IsSurrogatePair(hs.ToString() + ls, 0));
foreach (char hs in s_highSurrogates)
foreach (char ls in s_nonSurrogates)
Assert.False(char.IsSurrogatePair(hs.ToString() + ls, 0));
Assert.False(char.IsSurrogatePair("\ud800\udc00", 1)); // Index + 1 >= s.Length
}
[Fact]
public static void IsSurrogatePair_String_Int_Invalid()
{
AssertExtensions.Throws<ArgumentNullException>("s", () => char.IsSurrogatePair(null, 0)); // String is null
AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => char.IsSurrogatePair("abc", -1)); // Index < 0
AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => char.IsSurrogatePair("abc", 3)); // Index >= string.Length
}
[Fact]
public static void IsSymbol_Char()
{
var categories = new UnicodeCategory[]
{
UnicodeCategory.MathSymbol,
UnicodeCategory.ModifierSymbol,
UnicodeCategory.CurrencySymbol,
UnicodeCategory.OtherSymbol
};
foreach (char c in GetTestChars(categories))
Assert.True(char.IsSymbol(c));
foreach (char c in GetTestCharsNotInCategory(categories))
Assert.False(char.IsSymbol(c));
}
[Fact]
public static void IsSymbol_String_Int()
{
var categories = new UnicodeCategory[]
{
UnicodeCategory.MathSymbol,
UnicodeCategory.ModifierSymbol,
UnicodeCategory.CurrencySymbol,
UnicodeCategory.OtherSymbol
};
foreach (char c in GetTestChars(categories))
Assert.True(char.IsSymbol(c.ToString(), 0));
foreach (char c in GetTestCharsNotInCategory(categories))
Assert.False(char.IsSymbol(c.ToString(), 0));
}
[Fact]
public static void IsSymbol_String_Int_Invalid()
{
AssertExtensions.Throws<ArgumentNullException>("s", () => char.IsSymbol(null, 0)); // String is null
AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => char.IsSymbol("abc", -1)); // Index < 0
AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => char.IsSymbol("abc", 3)); // Index >= string.Length
}
[Fact]
public static void IsUpper_Char()
{
foreach (char c in GetTestChars(UnicodeCategory.UppercaseLetter))
Assert.True(char.IsUpper(c));
foreach (char c in GetTestCharsNotInCategory(UnicodeCategory.UppercaseLetter))
Assert.False(char.IsUpper(c));
}
[Fact]
public static void IsUpper_String_Int()
{
foreach (char c in GetTestChars(UnicodeCategory.UppercaseLetter))
Assert.True(char.IsUpper(c.ToString(), 0));
foreach (char c in GetTestCharsNotInCategory(UnicodeCategory.UppercaseLetter))
Assert.False(char.IsUpper(c.ToString(), 0));
}
[Fact]
public static void IsUpper_String_Int_Invalid()
{
AssertExtensions.Throws<ArgumentNullException>("s", () => char.IsUpper(null, 0)); // String is null
AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => char.IsUpper("abc", -1)); // Index < 0
AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => char.IsUpper("abc", 3)); // Index >= string.Length
}
[Fact]
public static void IsWhitespace_Char()
{
var categories = new UnicodeCategory[]
{
UnicodeCategory.SpaceSeparator,
UnicodeCategory.LineSeparator,
UnicodeCategory.ParagraphSeparator
};
foreach (char c in GetTestChars(categories))
Assert.True(char.IsWhiteSpace(c));
foreach (char c in GetTestCharsNotInCategory(categories))
{
// Need to special case some control chars that are treated as whitespace
if ((c >= '\x0009' && c <= '\x000d') || c == '\x0085') continue;
Assert.False(char.IsWhiteSpace(c));
}
}
[Fact]
public static void IsWhiteSpace_String_Int()
{
var categories = new UnicodeCategory[]
{
UnicodeCategory.SpaceSeparator,
UnicodeCategory.LineSeparator,
UnicodeCategory.ParagraphSeparator
};
foreach (char c in GetTestChars(categories))
Assert.True(char.IsWhiteSpace(c.ToString(), 0));
// Some control chars are also considered whitespace for legacy reasons.
// if ((c >= '\x0009' && c <= '\x000d') || c == '\x0085')
Assert.True(char.IsWhiteSpace("\u000b", 0));
Assert.True(char.IsWhiteSpace("\u0085", 0));
foreach (char c in GetTestCharsNotInCategory(categories))
{
// Need to special case some control chars that are treated as whitespace
if ((c >= '\x0009' && c <= '\x000d') || c == '\x0085') continue;
Assert.False(char.IsWhiteSpace(c.ToString(), 0));
}
}
[Fact]
public static void IsWhiteSpace_String_Int_Invalid()
{
AssertExtensions.Throws<ArgumentNullException>("s", () => char.IsWhiteSpace(null, 0)); // String is null
AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => char.IsWhiteSpace("abc", -1)); // Index < 0
AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => char.IsWhiteSpace("abc", 3)); // Index >= string.Length
}
[Fact]
public static void MaxValue()
{
Assert.Equal(0xffff, char.MaxValue);
}
[Fact]
public static void MinValue()
{
Assert.Equal(0, char.MinValue);
}
[Fact]
public static void ToLower()
{
Assert.Equal('a', char.ToLower('A'));
Assert.Equal('a', char.ToLower('a'));
foreach (char c in GetTestChars(UnicodeCategory.UppercaseLetter))
{
char lc = char.ToLower(c);
Assert.NotEqual(c, lc);
Assert.True(char.IsLower(lc));
}
// TitlecaseLetter can have a lower case form (e.g. \u01C8 'Lj' letter which will be 'lj')
// LetterNumber can have a lower case form (e.g. \u2162 'III' letter which will be 'iii')
foreach (char c in GetTestCharsNotInCategory(UnicodeCategory.UppercaseLetter, UnicodeCategory.TitlecaseLetter, UnicodeCategory.LetterNumber))
{
Assert.Equal(c, char.ToLower(c));
}
}
[Fact]
public static void ToLowerInvariant()
{
Assert.Equal('a', char.ToLowerInvariant('A'));
Assert.Equal('a', char.ToLowerInvariant('a'));
foreach (char c in GetTestChars(UnicodeCategory.UppercaseLetter))
{
char lc = char.ToLowerInvariant(c);
Assert.NotEqual(c, lc);
Assert.True(char.IsLower(lc));
}
// TitlecaseLetter can have a lower case form (e.g. \u01C8 'Lj' letter which will be 'lj')
// LetterNumber can have a lower case form (e.g. \u2162 'III' letter which will be 'iii')
foreach (char c in GetTestCharsNotInCategory(UnicodeCategory.UppercaseLetter, UnicodeCategory.TitlecaseLetter, UnicodeCategory.LetterNumber))
{
Assert.Equal(c, char.ToLowerInvariant(c));
}
}
[Theory]
[InlineData('a', "a")]
[InlineData('\uabcd', "\uabcd")]
public static void ToString(char c, string expected)
{
Assert.Equal(expected, c.ToString());
Assert.Equal(expected, char.ToString(c));
}
[Fact]
public static void ToUpper()
{
Assert.Equal('A', char.ToUpper('A'));
Assert.Equal('A', char.ToUpper('a'));
foreach (char c in GetTestChars(UnicodeCategory.LowercaseLetter))
{
char lc = char.ToUpper(c);
Assert.NotEqual(c, lc);
Assert.True(char.IsUpper(lc));
}
// TitlecaseLetter can have a uppercase form (e.g. \u01C8 'Lj' letter which will be 'LJ')
// LetterNumber can have a uppercase form (e.g. \u2172 'iii' letter which will be 'III')
foreach (char c in GetTestCharsNotInCategory(UnicodeCategory.LowercaseLetter, UnicodeCategory.TitlecaseLetter, UnicodeCategory.LetterNumber))
{
Assert.Equal(c, char.ToUpper(c));
}
}
[Fact]
public static void ToUpperInvariant()
{
Assert.Equal('A', char.ToUpperInvariant('A'));
Assert.Equal('A', char.ToUpperInvariant('a'));
foreach (char c in GetTestChars(UnicodeCategory.LowercaseLetter))
{
char lc = char.ToUpperInvariant(c);
Assert.NotEqual(c, lc);
Assert.True(char.IsUpper(lc));
}
// TitlecaseLetter can have a uppercase form (e.g. \u01C8 'Lj' letter which will be 'LJ')
// LetterNumber can have a uppercase form (e.g. \u2172 'iii' letter which will be 'III')
foreach (char c in GetTestCharsNotInCategory(UnicodeCategory.LowercaseLetter, UnicodeCategory.TitlecaseLetter, UnicodeCategory.LetterNumber))
{
Assert.Equal(c, char.ToUpperInvariant(c));
}
}
public static IEnumerable<object[]> Parse_TestData()
{
yield return new object[] { "a", 'a' };
yield return new object[] { "4", '4' };
yield return new object[] { " ", ' ' };
yield return new object[] { "\n", '\n' };
yield return new object[] { "\0", '\0' };
yield return new object[] { "\u0135", '\u0135' };
yield return new object[] { "\u05d9", '\u05d9' };
yield return new object[] { "\ue001", '\ue001' }; // Private use codepoint
// Lone surrogate
yield return new object[] { "\ud801", '\ud801' }; // High surrogate
yield return new object[] { "\udc01", '\udc01' }; // Low surrogate
}
[Theory]
[MemberData(nameof(Parse_TestData))]
public static void Parse(string s, char expected)
{
char c;
Assert.True(char.TryParse(s, out c));
Assert.Equal(expected, c);
Assert.Equal(expected, char.Parse(s));
}
[Theory]
[InlineData(null, typeof(ArgumentNullException))]
[InlineData("", typeof(FormatException))]
[InlineData("\n\r", typeof(FormatException))]
[InlineData("kj", typeof(FormatException))]
[InlineData(" a", typeof(FormatException))]
[InlineData("a ", typeof(FormatException))]
[InlineData("\\u0135", typeof(FormatException))]
[InlineData("\u01356", typeof(FormatException))]
[InlineData("\ud801\udc01", typeof(FormatException))] // Surrogate pair
public static void Parse_Invalid(string s, Type exceptionType)
{
char c;
Assert.False(char.TryParse(s, out c));
Assert.Equal(default(char), c);
Assert.Throws(exceptionType, () => char.Parse(s));
}
private static IEnumerable<char> GetTestCharsNotInCategory(params UnicodeCategory[] categories)
{
Assert.Equal(s_latinTestSet.Length, s_unicodeTestSet.Length);
for (int i = 0; i < s_latinTestSet.Length; i++)
{
if (Array.Exists(categories, uc => uc == (UnicodeCategory)i))
continue;
char[] latinSet = s_latinTestSet[i];
for (int j = 0; j < latinSet.Length; j++)
yield return latinSet[j];
char[] unicodeSet = s_unicodeTestSet[i];
for (int k = 0; k < unicodeSet.Length; k++)
yield return unicodeSet[k];
}
}
private static IEnumerable<char> GetTestChars(params UnicodeCategory[] categories)
{
for (int i = 0; i < categories.Length; i++)
{
char[] latinSet = s_latinTestSet[(int)categories[i]];
for (int j = 0; j < latinSet.Length; j++)
yield return latinSet[j];
char[] unicodeSet = s_unicodeTestSet[(int)categories[i]];
for (int k = 0; k < unicodeSet.Length; k++)
yield return unicodeSet[k];
}
}
private static char[][] s_latinTestSet = new char[][]
{
new char[] {'\u0047','\u004c','\u0051','\u0056','\u00c0','\u00c5','\u00ca','\u00cf','\u00d4','\u00da'}, // UnicodeCategory.UppercaseLetter
new char[] {'\u0062','\u0068','\u006e','\u0074','\u007a','\u00e1','\u00e7','\u00ed','\u00f3','\u00fa'}, // UnicodeCategory.LowercaseLetter
new char[] {}, // UnicodeCategory.TitlecaseLetter
new char[] {}, // UnicodeCategory.ModifierLetter
new char[] {}, // UnicodeCategory.OtherLetter
new char[] {}, // UnicodeCategory.NonSpacingMark
new char[] {}, // UnicodeCategory.SpacingCombiningMark
new char[] {}, // UnicodeCategory.EnclosingMark
new char[] {'\u0030','\u0031','\u0032','\u0033','\u0034','\u0035','\u0036','\u0037','\u0038','\u0039'}, // UnicodeCategory.DecimalDigitNumber
new char[] {}, // UnicodeCategory.LetterNumber
new char[] {'\u00b2','\u00b3','\u00b9','\u00bc','\u00bd','\u00be'}, // UnicodeCategory.OtherNumber
new char[] {'\u0020','\u00a0'}, // UnicodeCategory.SpaceSeparator
new char[] {}, // UnicodeCategory.LineSeparator
new char[] {}, // UnicodeCategory.ParagraphSeparator
new char[] {'\u0005','\u000b','\u0011','\u0017','\u001d','\u0082','\u0085','\u008e','\u0094','\u009a'}, // UnicodeCategory.Control
new char[] {}, // UnicodeCategory.Format
new char[] {}, // UnicodeCategory.Surrogate
new char[] {}, // UnicodeCategory.PrivateUse
new char[] {'\u005f'}, // UnicodeCategory.ConnectorPunctuation
new char[] {'\u002d','\u00ad'}, // UnicodeCategory.DashPunctuation
new char[] {'\u0028','\u005b','\u007b'}, // UnicodeCategory.OpenPunctuation
new char[] {'\u0029','\u005d','\u007d'}, // UnicodeCategory.ClosePunctuation
new char[] {'\u00ab'}, // UnicodeCategory.InitialQuotePunctuation
new char[] {'\u00bb'}, // UnicodeCategory.FinalQuotePunctuation
new char[] {'\u002e','\u002f','\u003a','\u003b','\u003f','\u0040','\u005c','\u00a1','\u00b7','\u00bf'}, // UnicodeCategory.OtherPunctuation
new char[] {'\u002b','\u003c','\u003d','\u003e','\u007c','\u007e','\u00ac','\u00b1','\u00d7','\u00f7'}, // UnicodeCategory.MathSymbol
new char[] {'\u0024','\u00a2','\u00a3','\u00a4','\u00a5'}, // UnicodeCategory.CurrencySymbol
new char[] {'\u005e','\u0060','\u00a8','\u00af','\u00b4','\u00b8'}, // UnicodeCategory.ModifierSymbol
new char[] {'\u00a6','\u00a7','\u00a9','\u00ae','\u00b0','\u00b6'}, // UnicodeCategory.OtherSymbol
new char[] {}, // UnicodeCategory.OtherNotAssigned
};
private static char[][] s_unicodeTestSet = new char[][]
{
new char[] {'\u0102','\u01ac','\u0392','\u0428','\u0508','\u10c4','\u1eb4','\u1fba','\u2c28','\ua668'}, // UnicodeCategory.UppercaseLetter
new char[] { '\u0107', '\u012D', '\u0140', '\u0151', '\u013A', '\u01A1', '\u01F9', '\u022D', '\u1E09','\uFF45' }, // UnicodeCategory.LowercaseLetter
new char[] {'\u01c8','\u1f88','\u1f8b','\u1f8e','\u1f99','\u1f9c','\u1f9f','\u1faa','\u1fad','\u1fbc'}, // UnicodeCategory.TitlecaseLetter
new char[] {'\u02b7','\u02cd','\u07f4','\u1d2f','\u1d41','\u1d53','\u1d9d','\u1daf','\u2091','\u30fe'}, // UnicodeCategory.ModifierLetter
new char[] {'\u01c0','\u37be','\u4970','\u5b6c','\u6d1e','\u7ed0','\u9082','\ua271','\ub985','\ucb37'}, // UnicodeCategory.OtherLetter
new char[] {'\u0303','\u034e','\u05b5','\u0738','\u0a4d','\u0e49','\u0fad','\u180b','\u1dd5','\u2dfd'}, // UnicodeCategory.NonSpacingMark
new char[] {'\u0982','\u0b03','\u0c41','\u0d40','\u0df3','\u1083','\u1925','\u1b44','\ua8b5' }, // UnicodeCategory.SpacingCombiningMark
new char[] {'\u20dd','\u20de','\u20df','\u20e0','\u20e2','\u20e3','\u20e4','\ua670','\ua671','\ua672'}, // UnicodeCategory.EnclosingMark
new char[] {'\u0660','\u0966','\u0ae6','\u0c66','\u0e50','\u1040','\u1810','\u1b50','\u1c50','\ua900'}, // UnicodeCategory.DecimalDigitNumber
new char[] {'\u2162','\u2167','\u216c','\u2171','\u2176','\u217b','\u2180','\u2187','\u3023','\u3028'}, // UnicodeCategory.LetterNumber
new char[] {'\u0c78','\u136b','\u17f7','\u2158','\u2471','\u248a','\u24f1','\u2780','\u3220','\u3280'}, // UnicodeCategory.OtherNumber
new char[] {'\u2004','\u2005','\u2006','\u2007','\u2008','\u2009','\u200a','\u202f','\u205f','\u3000'}, // UnicodeCategory.SpaceSeparator
new char[] {'\u2028'}, // UnicodeCategory.LineSeparator
new char[] {'\u2029'}, // UnicodeCategory.ParagraphSeparator
new char[] {}, // UnicodeCategory.Control
new char[] {'\u0603','\u17b4','\u200c','\u200f','\u202c','\u2060','\u2063','\u206b','\u206e','\ufff9'}, // UnicodeCategory.Format
new char[] {'\ud808','\ud8d4','\ud9a0','\uda6c','\udb38','\udc04','\udcd0','\udd9c','\ude68','\udf34'}, // UnicodeCategory.Surrogate
new char[] {'\ue000','\ue280','\ue500','\ue780','\uea00','\uec80','\uef00','\uf180','\uf400','\uf680'}, // UnicodeCategory.PrivateUse
new char[] {'\u203f','\u2040','\u2054','\ufe33','\ufe34','\ufe4d','\ufe4e','\ufe4f','\uff3f'}, // UnicodeCategory.ConnectorPunctuation
new char[] {'\u2e17','\u2e1a','\u301c','\u3030','\u30a0','\ufe31','\ufe32','\ufe58','\ufe63','\uff0d'}, // UnicodeCategory.DashPunctuation
new char[] {'\u2768','\u2774','\u27ee','\u298d','\u29d8','\u2e28','\u3014','\ufe17','\ufe3f','\ufe5d'}, // UnicodeCategory.OpenPunctuation
new char[] {'\u276b','\u27c6','\u2984','\u2990','\u29db','\u3009','\u3017','\ufe18','\ufe40','\ufe5e'}, // UnicodeCategory.ClosePunctuation
new char[] {'\u201b','\u201c','\u201f','\u2039','\u2e02','\u2e04','\u2e09','\u2e0c','\u2e1c','\u2e20'}, // UnicodeCategory.InitialQuotePunctuation
new char[] {'\u2019','\u201d','\u203a','\u2e03','\u2e05','\u2e0a','\u2e0d','\u2e1d','\u2e21'}, // UnicodeCategory.FinalQuotePunctuation
new char[] {'\u0589','\u0709','\u0f10','\u16ec','\u1b5b','\u2034','\u2058','\u2e16','\ua8cf','\ufe55'}, // UnicodeCategory.OtherPunctuation
new char[] {'\u2052','\u2234','\u2290','\u22ec','\u27dd','\u2943','\u29b5','\u2a17','\u2a73','\u2acf'}, // UnicodeCategory.MathSymbol
new char[] {'\u17db','\u20a2','\u20a5','\u20a8','\u20ab','\u20ae','\u20b1','\u20b4','\ufe69','\uffe1'}, // UnicodeCategory.CurrencySymbol
new char[] {'\u02c5','\u02da','\u02e8','\u02f3','\u02fc','\u1fc0','\u1fee','\ua703','\ua70c','\ua715'}, // UnicodeCategory.ModifierSymbol
new char[] {'\u0bf3','\u2316','\u24ac','\u25b2','\u26af','\u285c','\u2e8f','\u2f8c','\u3292','\u3392'}, // UnicodeCategory.OtherSymbol
new char[] {'\u09c6','\u0dfa','\u2e5c'}, // UnicodeCategory.OtherNotAssigned
};
private static char[] s_highSurrogates = new char[] { '\ud800', '\udaaa', '\udbff' }; // Range from '\ud800' to '\udbff'
private static char[] s_lowSurrogates = new char[] { '\udc00', '\udeee', '\udfff' }; // Range from '\udc00' to '\udfff'
private static char[] s_nonSurrogates = new char[] { '\u0000', '\ud7ff', '\ue000', '\uffff' };
private static readonly UnicodeCategory[] s_categoryForLatin1 =
{
UnicodeCategory.Control, UnicodeCategory.Control, UnicodeCategory.Control, UnicodeCategory.Control, UnicodeCategory.Control, UnicodeCategory.Control, UnicodeCategory.Control, UnicodeCategory.Control, // 0000 - 0007
UnicodeCategory.Control, UnicodeCategory.Control, UnicodeCategory.Control, UnicodeCategory.Control, UnicodeCategory.Control, UnicodeCategory.Control, UnicodeCategory.Control, UnicodeCategory.Control, // 0008 - 000F
UnicodeCategory.Control, UnicodeCategory.Control, UnicodeCategory.Control, UnicodeCategory.Control, UnicodeCategory.Control, UnicodeCategory.Control, UnicodeCategory.Control, UnicodeCategory.Control, // 0010 - 0017
UnicodeCategory.Control, UnicodeCategory.Control, UnicodeCategory.Control, UnicodeCategory.Control, UnicodeCategory.Control, UnicodeCategory.Control, UnicodeCategory.Control, UnicodeCategory.Control, // 0018 - 001F
UnicodeCategory.SpaceSeparator, UnicodeCategory.OtherPunctuation, UnicodeCategory.OtherPunctuation, UnicodeCategory.OtherPunctuation, UnicodeCategory.CurrencySymbol, UnicodeCategory.OtherPunctuation, UnicodeCategory.OtherPunctuation, UnicodeCategory.OtherPunctuation, // 0020 - 0027
UnicodeCategory.OpenPunctuation, UnicodeCategory.ClosePunctuation, UnicodeCategory.OtherPunctuation, UnicodeCategory.MathSymbol, UnicodeCategory.OtherPunctuation, UnicodeCategory.DashPunctuation, UnicodeCategory.OtherPunctuation, UnicodeCategory.OtherPunctuation, // 0028 - 002F
UnicodeCategory.DecimalDigitNumber, UnicodeCategory.DecimalDigitNumber, UnicodeCategory.DecimalDigitNumber, UnicodeCategory.DecimalDigitNumber, UnicodeCategory.DecimalDigitNumber, UnicodeCategory.DecimalDigitNumber, UnicodeCategory.DecimalDigitNumber, UnicodeCategory.DecimalDigitNumber, // 0030 - 0037
UnicodeCategory.DecimalDigitNumber, UnicodeCategory.DecimalDigitNumber, UnicodeCategory.OtherPunctuation, UnicodeCategory.OtherPunctuation, UnicodeCategory.MathSymbol, UnicodeCategory.MathSymbol, UnicodeCategory.MathSymbol, UnicodeCategory.OtherPunctuation, // 0038 - 003F
UnicodeCategory.OtherPunctuation, UnicodeCategory.UppercaseLetter, UnicodeCategory.UppercaseLetter, UnicodeCategory.UppercaseLetter, UnicodeCategory.UppercaseLetter, UnicodeCategory.UppercaseLetter, UnicodeCategory.UppercaseLetter, UnicodeCategory.UppercaseLetter, // 0040 - 0047
UnicodeCategory.UppercaseLetter, UnicodeCategory.UppercaseLetter, UnicodeCategory.UppercaseLetter, UnicodeCategory.UppercaseLetter, UnicodeCategory.UppercaseLetter, UnicodeCategory.UppercaseLetter, UnicodeCategory.UppercaseLetter, UnicodeCategory.UppercaseLetter, // 0048 - 004F
UnicodeCategory.UppercaseLetter, UnicodeCategory.UppercaseLetter, UnicodeCategory.UppercaseLetter, UnicodeCategory.UppercaseLetter, UnicodeCategory.UppercaseLetter, UnicodeCategory.UppercaseLetter, UnicodeCategory.UppercaseLetter, UnicodeCategory.UppercaseLetter, // 0050 - 0057
UnicodeCategory.UppercaseLetter, UnicodeCategory.UppercaseLetter, UnicodeCategory.UppercaseLetter, UnicodeCategory.OpenPunctuation, UnicodeCategory.OtherPunctuation, UnicodeCategory.ClosePunctuation, UnicodeCategory.ModifierSymbol, UnicodeCategory.ConnectorPunctuation, // 0058 - 005F
UnicodeCategory.ModifierSymbol, UnicodeCategory.LowercaseLetter, UnicodeCategory.LowercaseLetter, UnicodeCategory.LowercaseLetter, UnicodeCategory.LowercaseLetter, UnicodeCategory.LowercaseLetter, UnicodeCategory.LowercaseLetter, UnicodeCategory.LowercaseLetter, // 0060 - 0067
UnicodeCategory.LowercaseLetter, UnicodeCategory.LowercaseLetter, UnicodeCategory.LowercaseLetter, UnicodeCategory.LowercaseLetter, UnicodeCategory.LowercaseLetter, UnicodeCategory.LowercaseLetter, UnicodeCategory.LowercaseLetter, UnicodeCategory.LowercaseLetter, // 0068 - 006F
UnicodeCategory.LowercaseLetter, UnicodeCategory.LowercaseLetter, UnicodeCategory.LowercaseLetter, UnicodeCategory.LowercaseLetter, UnicodeCategory.LowercaseLetter, UnicodeCategory.LowercaseLetter, UnicodeCategory.LowercaseLetter, UnicodeCategory.LowercaseLetter, // 0070 - 0077
UnicodeCategory.LowercaseLetter, UnicodeCategory.LowercaseLetter, UnicodeCategory.LowercaseLetter, UnicodeCategory.OpenPunctuation, UnicodeCategory.MathSymbol, UnicodeCategory.ClosePunctuation, UnicodeCategory.MathSymbol, UnicodeCategory.Control, // 0078 - 007F
UnicodeCategory.Control, UnicodeCategory.Control, UnicodeCategory.Control, UnicodeCategory.Control, UnicodeCategory.Control, UnicodeCategory.Control, UnicodeCategory.Control, UnicodeCategory.Control, // 0080 - 0087
UnicodeCategory.Control, UnicodeCategory.Control, UnicodeCategory.Control, UnicodeCategory.Control, UnicodeCategory.Control, UnicodeCategory.Control, UnicodeCategory.Control, UnicodeCategory.Control, // 0088 - 008F
UnicodeCategory.Control, UnicodeCategory.Control, UnicodeCategory.Control, UnicodeCategory.Control, UnicodeCategory.Control, UnicodeCategory.Control, UnicodeCategory.Control, UnicodeCategory.Control, // 0090 - 0097
UnicodeCategory.Control, UnicodeCategory.Control, UnicodeCategory.Control, UnicodeCategory.Control, UnicodeCategory.Control, UnicodeCategory.Control, UnicodeCategory.Control, UnicodeCategory.Control, // 0098 - 009F
UnicodeCategory.SpaceSeparator, UnicodeCategory.OtherPunctuation, UnicodeCategory.CurrencySymbol, UnicodeCategory.CurrencySymbol, UnicodeCategory.CurrencySymbol, UnicodeCategory.CurrencySymbol, UnicodeCategory.OtherSymbol, UnicodeCategory.OtherSymbol, // 00A0 - 00A7
UnicodeCategory.ModifierSymbol, UnicodeCategory.OtherSymbol, UnicodeCategory.LowercaseLetter, UnicodeCategory.InitialQuotePunctuation, UnicodeCategory.MathSymbol, UnicodeCategory.DashPunctuation, UnicodeCategory.OtherSymbol, UnicodeCategory.ModifierSymbol, // 00A8 - 00AF
UnicodeCategory.OtherSymbol, UnicodeCategory.MathSymbol, UnicodeCategory.OtherNumber, UnicodeCategory.OtherNumber, UnicodeCategory.ModifierSymbol, UnicodeCategory.LowercaseLetter, UnicodeCategory.OtherSymbol, UnicodeCategory.OtherPunctuation, // 00B0 - 00B7
UnicodeCategory.ModifierSymbol, UnicodeCategory.OtherNumber, UnicodeCategory.LowercaseLetter, UnicodeCategory.FinalQuotePunctuation, UnicodeCategory.OtherNumber, UnicodeCategory.OtherNumber, UnicodeCategory.OtherNumber, UnicodeCategory.OtherPunctuation, // 00B8 - 00BF
UnicodeCategory.UppercaseLetter, UnicodeCategory.UppercaseLetter, UnicodeCategory.UppercaseLetter, UnicodeCategory.UppercaseLetter, UnicodeCategory.UppercaseLetter, UnicodeCategory.UppercaseLetter, UnicodeCategory.UppercaseLetter, UnicodeCategory.UppercaseLetter, // 00C0 - 00C7
UnicodeCategory.UppercaseLetter, UnicodeCategory.UppercaseLetter, UnicodeCategory.UppercaseLetter, UnicodeCategory.UppercaseLetter, UnicodeCategory.UppercaseLetter, UnicodeCategory.UppercaseLetter, UnicodeCategory.UppercaseLetter, UnicodeCategory.UppercaseLetter, // 00C8 - 00CF
UnicodeCategory.UppercaseLetter, UnicodeCategory.UppercaseLetter, UnicodeCategory.UppercaseLetter, UnicodeCategory.UppercaseLetter, UnicodeCategory.UppercaseLetter, UnicodeCategory.UppercaseLetter, UnicodeCategory.UppercaseLetter, UnicodeCategory.MathSymbol, // 00D0 - 00D7
UnicodeCategory.UppercaseLetter, UnicodeCategory.UppercaseLetter, UnicodeCategory.UppercaseLetter, UnicodeCategory.UppercaseLetter, UnicodeCategory.UppercaseLetter, UnicodeCategory.UppercaseLetter, UnicodeCategory.UppercaseLetter, UnicodeCategory.LowercaseLetter, // 00D8 - 00DF
UnicodeCategory.LowercaseLetter, UnicodeCategory.LowercaseLetter, UnicodeCategory.LowercaseLetter, UnicodeCategory.LowercaseLetter, UnicodeCategory.LowercaseLetter, UnicodeCategory.LowercaseLetter, UnicodeCategory.LowercaseLetter, UnicodeCategory.LowercaseLetter, // 00E0 - 00E7
UnicodeCategory.LowercaseLetter, UnicodeCategory.LowercaseLetter, UnicodeCategory.LowercaseLetter, UnicodeCategory.LowercaseLetter, UnicodeCategory.LowercaseLetter, UnicodeCategory.LowercaseLetter, UnicodeCategory.LowercaseLetter, UnicodeCategory.LowercaseLetter, // 00E8 - 00EF
UnicodeCategory.LowercaseLetter, UnicodeCategory.LowercaseLetter, UnicodeCategory.LowercaseLetter, UnicodeCategory.LowercaseLetter, UnicodeCategory.LowercaseLetter, UnicodeCategory.LowercaseLetter, UnicodeCategory.LowercaseLetter, UnicodeCategory.MathSymbol, // 00F0 - 00F7
UnicodeCategory.LowercaseLetter, UnicodeCategory.LowercaseLetter, UnicodeCategory.LowercaseLetter, UnicodeCategory.LowercaseLetter, UnicodeCategory.LowercaseLetter, UnicodeCategory.LowercaseLetter, UnicodeCategory.LowercaseLetter, UnicodeCategory.LowercaseLetter, // 00F8 - 00FF
};
public static IEnumerable<object[]> UpperLowerCasing_TestData()
{
// lower upper Culture
yield return new object[] { 'a', 'A', "en-US" };
yield return new object[] { 'i', 'I', "en-US" };
yield return new object[] { '\u0131', 'I', "tr-TR" };
yield return new object[] { 'i', '\u0130', "tr-TR" };
yield return new object[] { '\u0660', '\u0660', "en-US" };
}
[Fact]
public static void LatinRangeTest()
{
StringBuilder sb = new StringBuilder(256);
string latineString = sb.ToString();
for (int i=0; i < latineString.Length; i++)
{
Assert.Equal(s_categoryForLatin1[i], char.GetUnicodeCategory(latineString[i]));
Assert.Equal(s_categoryForLatin1[i], char.GetUnicodeCategory(latineString, i));
}
}
[Fact]
public static void NonLatinRangeTest()
{
for (int i=256; i <= 0xFFFF; i++)
{
Assert.Equal(CharUnicodeInfo.GetUnicodeCategory((char)i), char.GetUnicodeCategory((char)i));
}
string nonLatinString = "\u0100\u0200\u0300\u0400\u0500\u0600\u0700\u0800\u0900\u0A00\u0B00\u0C00\u0D00\u0E00\u0F00" +
"\u1000\u2000\u3000\u4000\u5000\u6000\u7000\u8000\u9000\uA000\uB000\uC000\uD000\uE000\uF000";
for (int i=0; i < nonLatinString.Length; i++)
{
Assert.Equal(CharUnicodeInfo.GetUnicodeCategory(nonLatinString[i]), char.GetUnicodeCategory(nonLatinString, i));
}
}
[Theory]
[MemberData(nameof(UpperLowerCasing_TestData))]
public static void CasingTest(char lowerForm, char upperForm, string cultureName)
{
CultureInfo ci = CultureInfo.GetCultureInfo(cultureName);
Assert.Equal(lowerForm, char.ToLower(upperForm, ci));
Assert.Equal(upperForm, char.ToUpper(lowerForm, ci));
}
[OuterLoop]
[Fact]
public static void GetUnicodeCategory_Char_AllInputs()
{
// This tests calls char.GetUnicodeCategory for every possible input, ensuring that
// the runtime agrees with the data in the core Unicode files.
for (uint i = 0; i <= char.MaxValue; i++)
{
UnicodeCategory expected;
// The code points in the switch block below must be special-cased
// because they switched categories between versions of the Unicode
// specification. For compatibility reasons Char keeps its own copy
// of the categories for the first 256 code points, as it's locked
// to an earlier version of the standard. For an example of a code
// point that switched categories, see the discussion on U+00AD
// SOFT HYPHEN at https://www.unicode.org/versions/Unicode4.0.0/.
switch (i)
{
case '\u00a7':
case '\u00b6':
expected = UnicodeCategory.OtherSymbol;
break;
case '\u00aa':
case '\u00ba':
expected = UnicodeCategory.LowercaseLetter;
break;
case '\u00ad':
expected = UnicodeCategory.DashPunctuation;
break;
default:
expected = UnicodeData.GetUnicodeCategory(i);
break;
}
if (expected != char.GetUnicodeCategory((char)i))
{
// We'll build up the exception message ourselves so the dev knows what code point failed.
throw new AssertActualExpectedException(
expected: expected,
actual: char.GetUnicodeCategory((char)i),
userMessage: FormattableString.Invariant($@"char.GetUnicodeCategory('\u{i:X4}') returned wrong value."));
}
}
}
[OuterLoop]
[Fact]
public static void IsLetter_Char_AllInputs()
{
// This tests calls char.IsLetter for every possible input, ensuring that
// the runtime agrees with the data in the core Unicode files.
for (uint i = 0; i <= char.MaxValue; i++)
{
if (UnicodeData.IsLetter((char)i) != char.IsLetter((char)i))
{
// We'll build up the exception message ourselves so the dev knows what code point failed.
throw new AssertActualExpectedException(
expected: UnicodeData.IsLetter((char)i),
actual: char.IsLetter((char)i),
userMessage: FormattableString.Invariant($@"char.IsLetter('\u{i:X4}') returned wrong value."));
}
}
}
[OuterLoop]
[Fact]
public static void IsLower_Char_AllInputs()
{
// This tests calls char.IsLower for every possible input, ensuring that
// the runtime agrees with the data in the core Unicode files.
for (uint i = 0; i <= char.MaxValue; i++)
{
bool expected;
switch (i)
{
case '\u00AA': // FEMININE ORDINAL INDICATOR
case '\u00BA': // MASCULINE ORDINAL INDICATOR
// In Unicode 6.1 the code points U+00AA and U+00BA were reassigned
// from category Ll to category Lo. However, for compatibility reasons,
// Char uses the older version of the Unicode standard for code points
// in the range U+0000..U+00FF. So we'll special-case these here.
// More info: https://www.unicode.org/review/pri181/
expected = true;
break;
default:
expected = UnicodeData.GetUnicodeCategory((char)i) == UnicodeCategory.LowercaseLetter;
break;
}
if (expected != char.IsLower((char)i))
{
// We'll build up the exception message ourselves so the dev knows what code point failed.
throw new AssertActualExpectedException(
expected: expected,
actual: char.IsLower((char)i),
userMessage: FormattableString.Invariant($@"char.IsLower('\u{i:X4}') returned wrong value."));
}
}
}
[OuterLoop]
[Fact]
public static void IsUpper_Char_AllInputs()
{
// This tests calls char.IsUpper for every possible input, ensuring that
// the runtime agrees with the data in the core Unicode files.
for (uint i = 0; i <= char.MaxValue; i++)
{
bool expected = UnicodeData.GetUnicodeCategory((char)i) == UnicodeCategory.UppercaseLetter;
if (expected != char.IsUpper((char)i))
{
// We'll build up the exception message ourselves so the dev knows what code point failed.
throw new AssertActualExpectedException(
expected: expected,
actual: char.IsUpper((char)i),
userMessage: FormattableString.Invariant($@"char.IsUpper('\u{i:X4}') returned wrong value."));
}
}
}
[OuterLoop]
[Fact]
public static void IsWhiteSpace_Char_AllInputs()
{
// This tests calls char.IsWhiteSpace for every possible input, ensuring that
// the runtime agrees with the data in the core Unicode files.
for (uint i = 0; i <= char.MaxValue; i++)
{
if (UnicodeData.IsWhiteSpace(i) != char.IsWhiteSpace((char)i))
{
// We'll build up the exception message ourselves so the dev knows what code point failed.
throw new AssertActualExpectedException(
expected: UnicodeData.IsWhiteSpace(i),
actual: char.IsWhiteSpace((char)i),
userMessage: FormattableString.Invariant($@"char.IsWhiteSpace('\u{i:X4}') returned wrong value."));
}
}
}
}
}
| |
// <file>
// <copyright see="prj:///doc/copyright.txt"/>
// <license see="prj:///doc/license.txt"/>
// <owner name="Daniel Grunwald" email="[email protected]"/>
// <version>$Revision: 3349 $</version>
// </file>
using System;
using System.Collections.Generic;
using System.Diagnostics;
using ICSharpCode.SharpDevelop.Dom.Refactoring;
namespace ICSharpCode.SharpDevelop.Dom
{
public class LanguageProperties
{
/// <summary>
/// A case-sensitive dummy language that returns false for all Supports.. properties,
/// uses a dummy code generator and refactoring provider and returns null for CodeDomProvider.
/// </summary>
public readonly static LanguageProperties None = new LanguageProperties(StringComparer.InvariantCulture);
/// <summary>
/// C# 3.0 language properties.
/// </summary>
public readonly static LanguageProperties CSharp = new CSharpProperties();
/// <summary>
/// VB.Net 8 language properties.
/// </summary>
public readonly static LanguageProperties VBNet = new VBNetProperties();
public LanguageProperties(StringComparer nameComparer)
{
this.nameComparer = nameComparer;
}
#region Language-specific service providers
readonly StringComparer nameComparer;
public StringComparer NameComparer {
get {
return nameComparer;
}
}
public virtual CodeGenerator CodeGenerator {
get {
return CodeGenerator.DummyCodeGenerator;
}
}
public virtual RefactoringProvider RefactoringProvider {
get {
return RefactoringProvider.DummyProvider;
}
}
/// <summary>
/// Gets the ambience for this language. Because the IAmbience interface is not thread-safe, every call
/// creates a new instance.
/// </summary>
public virtual IAmbience GetAmbience()
{
return new CSharp.CSharpAmbience();
}
/// <summary>
/// Gets the CodeDomProvider for this language. Can return null!
/// </summary>
public virtual System.CodeDom.Compiler.CodeDomProvider CodeDomProvider {
get {
return null;
}
}
sealed class DummyCodeDomProvider : System.CodeDom.Compiler.CodeDomProvider
{
public static readonly DummyCodeDomProvider Instance = new DummyCodeDomProvider();
[Obsolete("Callers should not use the ICodeGenerator interface and should instead use the methods directly on the CodeDomProvider class.")]
public override System.CodeDom.Compiler.ICodeGenerator CreateGenerator()
{
return null;
}
[Obsolete("Callers should not use the ICodeCompiler interface and should instead use the methods directly on the CodeDomProvider class.")]
public override System.CodeDom.Compiler.ICodeCompiler CreateCompiler()
{
return null;
}
}
#endregion
#region Supports...
/// <summary>
/// Gets if the language supports calling C# 3-style extension methods
/// (first parameter = instance parameter)
/// </summary>
public virtual bool SupportsExtensionMethods {
get { return false; }
}
/// <summary>
/// Gets if the language supports calling extension properties
/// (first parameter = instance parameter)
/// </summary>
public virtual bool SupportsExtensionProperties {
get { return false; }
}
/// <summary>
/// Gets if extension methods/properties are searched in imported classes (returns true) or if
/// only the extensions from the current class, imported classes and imported modules are used
/// (returns false). This property has no effect if the language doesn't support extension methods or properties.
/// </summary>
public virtual bool SearchExtensionsInClasses {
get { return false; }
}
/// <summary>
/// Gets if namespaces are imported (i.e. Imports System, Dim a As Collections.ArrayList)
/// </summary>
public virtual bool ImportNamespaces {
get { return false; }
}
/// <summary>
/// Gets if modules are imported with their namespace (i.e. Microsoft.VisualBasic.Randomize()).
/// </summary>
public virtual bool ImportModules {
get { return false; }
}
/// <summary>
/// Gets if classes can be imported (i.e. Imports System.Math)
/// </summary>
public virtual bool CanImportClasses {
get { return false; }
}
/// <summary>
/// Gets if the language allows partial classes where the partial modifier is not
/// used on any part.
/// </summary>
public virtual bool ImplicitPartialClasses {
get { return false; }
}
/// <summary>
/// Allow invoking an object constructor outside of ExpressionContext.ObjectCreation.
/// Used for Boo, which creates instances like this: 'self.Size = Size(10, 20)'
/// </summary>
public virtual bool AllowObjectConstructionOutsideContext {
get { return false; }
}
/// <summary>
/// Gets if the language supports implicit interface implementations.
/// </summary>
public virtual bool SupportsImplicitInterfaceImplementation {
get { return false; }
}
/// <summary>
/// Gets if the language enforces that explicit interface implementations are uncallable except through
/// the interface itself.
/// If this property is false, code generators may assume that multiple explicit interface implementations
/// with conflicting return types are invalid unless they are renamed.
/// </summary>
public virtual bool ExplicitInterfaceImplementationIsPrivateScope {
get { return false; }
}
/// <summary>
/// Gets if events explicitly implementing an interface require add {} remove {} regions.
/// </summary>
public virtual bool RequiresAddRemoveRegionInExplicitInterfaceImplementation {
get { return false; }
}
/// <summary>
/// Gets the start token of an indexer expression in the language. Usually '[' or '('.
/// </summary>
public virtual string IndexerExpressionStartToken {
get { return "["; }
}
public virtual TextFinder GetFindClassReferencesTextFinder(IClass c)
{
// when finding attribute references, also look for the short form of the name
if (c.Name.Length > 9 && nameComparer.Equals(c.Name.Substring(c.Name.Length - 9), "Attribute")) {
return new CombinedTextFinder(
new WholeWordTextFinder(c.Name.Substring(0, c.Name.Length - 9), nameComparer),
new WholeWordTextFinder(c.Name, nameComparer)
);
}
return new WholeWordTextFinder(c.Name, nameComparer);
}
public virtual TextFinder GetFindMemberReferencesTextFinder(IMember member)
{
IProperty property = member as IProperty;
if (property != null && property.IsIndexer) {
return new IndexBeforeTextFinder(IndexerExpressionStartToken);
} else {
return new WholeWordTextFinder(member.Name, nameComparer);
}
}
public virtual bool IsClassWithImplicitlyStaticMembers(IClass c)
{
return false;
}
#endregion
#region Code-completion filters
public virtual bool ShowInNamespaceCompletion(IClass c)
{
return true;
}
public virtual bool ShowMember(IMember member, bool showStatic)
{
if (member is IProperty && ((IProperty)member).IsIndexer) {
return false;
}
if (member is IMethod && ((IMethod)member).IsConstructor) {
return false;
}
return member.IsStatic == showStatic;
}
#endregion
/// <summary>
/// Generates the default imports statements a new application for this language should use.
/// </summary>
public virtual IUsing CreateDefaultImports(IProjectContent pc)
{
return null;
}
public override string ToString()
{
return "[" + base.ToString() + "]";
}
#region CSharpProperties
internal sealed class CSharpProperties : LanguageProperties
{
public CSharpProperties() : base(StringComparer.InvariantCulture) {}
public override RefactoringProvider RefactoringProvider {
get {
return NRefactoryRefactoringProvider.NRefactoryCSharpProviderInstance;
}
}
public override CodeGenerator CodeGenerator {
get {
return CSharpCodeGenerator.Instance;
}
}
public override System.CodeDom.Compiler.CodeDomProvider CodeDomProvider {
get {
return new Microsoft.CSharp.CSharpCodeProvider();
}
}
public override bool SupportsImplicitInterfaceImplementation {
get { return true; }
}
public override bool ExplicitInterfaceImplementationIsPrivateScope {
get { return true; }
}
/// <summary>
/// Gets if events explicitly implementing an interface require add {} remove {} regions.
/// </summary>
public override bool RequiresAddRemoveRegionInExplicitInterfaceImplementation {
get { return true; }
}
public override bool SupportsExtensionMethods {
get { return true; }
}
public override bool SearchExtensionsInClasses {
get { return true; }
}
public override string ToString()
{
return "[LanguageProperties: C#]";
}
public override TextFinder GetFindMemberReferencesTextFinder(IMember member)
{
IMethod method = member as IMethod;
if (method != null && method.IsConstructor) {
return new CombinedTextFinder(
new WholeWordTextFinder(member.DeclaringType.Name, this.NameComparer),
new WholeWordTextFinder("this", this.NameComparer),
new WholeWordTextFinder("base", this.NameComparer)
);
} else {
return base.GetFindMemberReferencesTextFinder(member);
}
}
}
#endregion
#region VBNetProperties
internal sealed class VBNetProperties : LanguageProperties
{
public VBNetProperties() : base(StringComparer.InvariantCultureIgnoreCase) {}
public override bool ShowMember(IMember member, bool showStatic)
{
if (member is ArrayReturnType.ArrayIndexer) {
return false;
}
if (member is IMethod && ((IMethod)member).IsConstructor) {
return false;
}
return member.IsStatic || !showStatic;
}
public override bool ImportNamespaces {
get {
return true;
}
}
public override bool ImportModules {
get {
return true;
}
}
public override bool CanImportClasses {
get {
return true;
}
}
public override bool IsClassWithImplicitlyStaticMembers(IClass c)
{
return c.ClassType == ClassType.Module;
}
public override bool ShowInNamespaceCompletion(IClass c)
{
foreach (IAttribute attr in c.Attributes) {
if (attr.AttributeType.FullyQualifiedName == "Microsoft.VisualBasic.HideModuleNameAttribute")
return false;
}
return base.ShowInNamespaceCompletion(c);
}
public override IUsing CreateDefaultImports(IProjectContent pc)
{
DefaultUsing u = new DefaultUsing(pc);
u.Usings.Add("Microsoft.VisualBasic");
u.Usings.Add("System");
u.Usings.Add("System.Collections");
u.Usings.Add("System.Collections.Generic");
u.Usings.Add("System.Drawing");
u.Usings.Add("System.Diagnostics");
u.Usings.Add("System.Windows.Forms");
return u;
}
public override RefactoringProvider RefactoringProvider {
get {
return NRefactoryRefactoringProvider.NRefactoryVBNetProviderInstance;
}
}
public override CodeGenerator CodeGenerator {
get {
return VBNetCodeGenerator.Instance;
}
}
public override System.CodeDom.Compiler.CodeDomProvider CodeDomProvider {
get {
return new Microsoft.VisualBasic.VBCodeProvider();
}
}
public override IAmbience GetAmbience()
{
return new VBNet.VBNetAmbience();
}
public override string IndexerExpressionStartToken {
get { return "("; }
}
public override string ToString()
{
return "[LanguageProperties: VB.NET]";
}
}
#endregion
#region Text Finder
protected sealed class WholeWordTextFinder : TextFinder
{
readonly string searchedText;
readonly bool caseInsensitive;
public WholeWordTextFinder(string word, StringComparer nameComparer)
{
if (word == null) word = string.Empty;
caseInsensitive = nameComparer.Equals("a", "A");
if (caseInsensitive)
this.searchedText = word.ToLowerInvariant();
else
this.searchedText = word;
}
public override string PrepareInputText(string inputText)
{
if (caseInsensitive)
return inputText.ToLowerInvariant();
else
return inputText;
}
public override TextFinderMatch Find(string inputText, int startPosition)
{
if (searchedText.Length == 0)
return TextFinderMatch.Empty;
int pos = startPosition - 1;
while ((pos = inputText.IndexOf(searchedText, pos + 1)) >= 0) {
if (pos > 0 && char.IsLetterOrDigit(inputText, pos - 1)) {
continue; // memberName is not a whole word (a.SomeName cannot reference Name)
}
if (pos < inputText.Length - searchedText.Length - 1
&& char.IsLetterOrDigit(inputText, pos + searchedText.Length))
{
continue; // memberName is not a whole word (a.Name2 cannot reference Name)
}
return new TextFinderMatch(pos, searchedText.Length);
}
return TextFinderMatch.Empty;
}
}
protected sealed class CombinedTextFinder : TextFinder
{
readonly TextFinder[] finders;
public CombinedTextFinder(params TextFinder[] finders)
{
if (finders == null)
throw new ArgumentNullException("finders");
if (finders.Length == 0)
throw new ArgumentException("finders.Length must be > 0");
this.finders = finders;
}
public override string PrepareInputText(string inputText)
{
return finders[0].PrepareInputText(inputText);
}
public override TextFinderMatch Find(string inputText, int startPosition)
{
TextFinderMatch best = TextFinderMatch.Empty;
foreach (TextFinder f in finders) {
TextFinderMatch r = f.Find(inputText, startPosition);
if (r.Position >= 0 && (best.Position < 0 || r.Position < best.Position)) {
best = r;
}
}
return best;
}
}
protected sealed class IndexBeforeTextFinder : TextFinder
{
readonly string searchText;
public IndexBeforeTextFinder(string searchText)
{
this.searchText = searchText;
}
public override TextFinderMatch Find(string inputText, int startPosition)
{
int pos = inputText.IndexOf(searchText, startPosition);
if (pos >= 0) {
return new TextFinderMatch(pos, searchText.Length, pos - 1);
} else {
return TextFinderMatch.Empty;
}
}
}
#endregion
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Xml;
using System.Text;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Text.RegularExpressions;
using System.Threading;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Microsoft.Build.BackEnd;
using Microsoft.Build.Collections;
using Microsoft.Build.Exceptions;
using Microsoft.Build.Execution;
using Microsoft.Build.Evaluation;
using Microsoft.Build.Unittest;
using TaskItem = Microsoft.Build.Execution.ProjectItemInstance.TaskItem;
using ProjectLoggingContext = Microsoft.Build.BackEnd.Logging.ProjectLoggingContext;
using System.Threading.Tasks;
namespace Microsoft.Build.UnitTests.QA
{
/// <summary>
/// The mock component TargetBuilder object.
/// </summary>
internal class QAMockTargetBuilder : ITargetBuilder, IBuildComponent
{
/// <summary>
/// The component host.
/// </summary>
private IBuildComponentHost _host;
/// <summary>
/// The BuildRequestEntry for which we are building targets.
/// </summary>
private BuildRequestEntry _requestEntry;
/// <summary>
/// The project logging context
/// </summary>
private ProjectLoggingContext _projectLoggingContext;
/// <summary>
/// Request Callback
/// </summary>
private IRequestBuilderCallback _requestCallBack;
/// <summary>
/// The test data provider
/// </summary>
private ITestDataProvider _testDataProvider;
/// <summary>
/// Test definition associated with the project that we are building
/// </summary>
private RequestDefinition _testDefinition;
/// <summary>
/// Event to notify that the build has been completed
/// </summary>
private AutoResetEvent _buildDone;
/// <summary>
/// The cancellation token
/// </summary>
private CancellationToken _cancellationToken;
public QAMockTargetBuilder()
{
_host = null;
_testDataProvider = null;
_testDefinition = null;
_requestCallBack = null;
_requestEntry = null;
_projectLoggingContext = null;
_buildDone = new AutoResetEvent(false);
}
/// <summary>
/// Builds the specified targets of an entry. The cancel event should only be set to true if we are planning
/// on simulating execution time when a target is built
/// </summary>
public Task<BuildResult> BuildTargets(ProjectLoggingContext loggingContext, BuildRequestEntry entry, IRequestBuilderCallback callback, string[] targetNames, Lookup baseLookup, CancellationToken cancellationToken)
{
_requestEntry = entry;
_projectLoggingContext = loggingContext;
_requestCallBack = callback;
_testDefinition = _testDataProvider[entry.Request.ConfigurationId];
_cancellationToken = cancellationToken;
BuildResult result = GenerateResults(targetNames);
return Task<BuildResult>.FromResult(result);
}
#region IBuildComponent Members
/// <summary>
/// Sets the component host.
/// </summary>
/// <param name="host">The component host.</param>
public void InitializeComponent(IBuildComponentHost host)
{
_host = host;
_testDataProvider = (ITestDataProvider)host.GetComponent(BuildComponentType.TestDataProvider);
}
/// <summary>
/// Shuts down the component.
/// </summary>
public void ShutdownComponent()
{
_host = null;
_testDataProvider = null;
_testDefinition = null;
_requestCallBack = null;
_requestEntry = null;
_projectLoggingContext = null;
}
/// <summary>
/// Returns the tools version associated which the project configuration
/// </summary>
public string GetToolsVersion(string filename, string elementname, string attributename)
{
return _testDefinition.ToolsVersion;
}
#endregion
#region Private Method
/// <summary>
/// Generate results for the targets requested to be built. Using the TestDataProvider also simulate any
/// P2P callbacks on the first target. In order to test the cancels there is also functionality to allow the
/// target execution to wait on a cancel event before exiting
/// </summary>
private BuildResult GenerateResults(string[] targetNames)
{
bool simulatedResults = false;
BuildResult result = new BuildResult(_requestEntry.Request);
foreach (string target in targetNames)
{
if (!simulatedResults)
{
SimulateCallBacks();
simulatedResults = true;
}
// Wait for this to be cancelled
if (_testDefinition.WaitForCancel)
{
_cancellationToken.WaitHandle.WaitOne();
_buildDone.Set();
throw new BuildAbortedException();
}
if (_testDefinition.ExecutionTime > 0)
{
Thread.Sleep(_testDefinition.ExecutionTime);
}
TaskItem[] items = new TaskItem[] { new TaskItem("itemValue", _requestEntry.RequestConfiguration.ProjectFullPath) };
TargetResult targetResult = new TargetResult(items, TestUtilities.GetSuccessResult());
result.AddResultsForTarget(target, targetResult);
}
_buildDone.Set();
return result;
}
/// <summary>
/// Simulates callback. Access the configuration for the primary project. Retrieve the test test data definition.
/// Get the child definitions if available and simulate a callback for each of the child definitions. Note that the
/// targets to build parameter is the same for all the projects - that is we instruct to build the same set of targets
/// for all of the projects. Thus the child test definitions of the entry should have the same set of targets available
/// or a common set of targets available
/// </summary>
private void SimulateCallBacks()
{
if (_testDefinition.ChildDefinitions == null || _testDefinition.ChildDefinitions.Count < 1)
{
return;
}
int count = _testDefinition.ChildDefinitions.Count;
string[] projectFiles = new string[count];
PropertyDictionary<ProjectPropertyInstance>[] properties = new PropertyDictionary<ProjectPropertyInstance>[count];
string[] toolsVersions = new string[count];
string[] targetsToBuild = null;
count = 0;
foreach (RequestDefinition d in _testDefinition.ChildDefinitions)
{
projectFiles[count] = d.FileName;
properties[count] = d.GlobalProperties;
toolsVersions[count] = d.ToolsVersion;
targetsToBuild = d.TargetsToBuild;
count++;
}
_requestCallBack.BuildProjects(projectFiles, properties, toolsVersions, targetsToBuild, true);
}
#endregion
}
}
| |
// Copyright (c) 2006-2007 Frank Laub
// All rights reserved.
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// 1. Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// 3. The name of the author may not be used to endorse or promote products
// derived from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
// IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
// OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
// IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
// NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
// THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.InteropServices;
using OpenSSL.Core;
using OpenSSL.Crypto;
namespace OpenSSL.X509
{
/// <summary>
/// Wraps the X509 object
/// </summary>
public class X509Certificate : BaseCopyableRef<X509Certificate>, IComparable<X509Certificate>, IStackable
{
#region Initialization
internal X509Certificate(IStack stack, IntPtr ptr)
: base(ptr, true)
{ }
internal X509Certificate(IntPtr ptr, bool owner)
: base(ptr, owner)
{ }
/// <summary>
/// Calls X509_new()
/// </summary>
public X509Certificate()
: base(Native.ExpectNonNull(Native.X509_new()), true)
{ }
/// <summary>
/// Calls PEM_read_bio_X509()
/// </summary>
/// <param name="bio"></param>
public X509Certificate(BIO bio)
: base(Native.ExpectNonNull(Native.PEM_read_bio_X509(bio.Handle, IntPtr.Zero, null, IntPtr.Zero)), true)
{ }
/// <summary>
/// Factory method that returns a X509 using d2i_X509_bio()
/// </summary>
/// <param name="bio"></param>
/// <returns></returns>
public static X509Certificate FromDER(BIO bio)
{
IntPtr pX509 = IntPtr.Zero;
IntPtr ptr = Native.ExpectNonNull(Native.d2i_X509_bio(bio.Handle, ref pX509));
return new X509Certificate(ptr, true);
}
/// <summary>
/// Factory method to create a X509Certificate from a PKCS7 encoded in PEM
/// </summary>
/// <param name="bio"></param>
/// <returns></returns>
public static X509Certificate FromPKCS7_PEM(BIO bio)
{
PKCS7 pkcs7 = PKCS7.FromPEM(bio);
X509Chain chain = pkcs7.Certificates;
if (chain != null && chain.Count > 0)
{
return new X509Certificate(chain[0].Handle, false);
}
else
{
throw new OpenSslException();
}
}
/// <summary>
/// Factory method to create a X509Certificate from a PKCS7 encoded in DER
/// </summary>
/// <param name="bio"></param>
/// <returns></returns>
public static X509Certificate FromPKCS7_DER(BIO bio)
{
PKCS7 pkcs7 = PKCS7.FromDER(bio);
X509Chain chain = pkcs7.Certificates;
if (chain != null && chain.Count > 0)
{
return new X509Certificate(chain[0].Handle, false);
}
return null;
}
/// <summary>
/// Factory method to create a X509Certificate from a PKCS12
/// </summary>
/// <param name="bio"></param>
/// <param name="password"></param>
/// <returns></returns>
public static X509Certificate FromPKCS12(BIO bio, string password)
{
using (PKCS12 p12 = new PKCS12(bio, password))
{
return p12.Certificate;
}
}
/// <summary>
/// Creates a new X509 certificate
/// </summary>
/// <param name="serial"></param>
/// <param name="subject"></param>
/// <param name="issuer"></param>
/// <param name="pubkey"></param>
/// <param name="start"></param>
/// <param name="end"></param>
public X509Certificate(
int serial,
X509Name subject,
X509Name issuer,
CryptoKey pubkey,
DateTime start,
DateTime end)
: this()
{
this.Version = 2;
this.SerialNumber = serial;
this.Subject = subject;
this.Issuer = issuer;
this.PublicKey = pubkey;
this.NotBefore = start;
this.NotAfter = end;
}
#endregion
#region Raw Structures
#region X509_VAL
[StructLayout(LayoutKind.Sequential)]
private struct X509_VAL
{
public IntPtr notBefore;
public IntPtr notAfter;
}
#endregion
#region X509_CINF
[StructLayout(LayoutKind.Sequential)]
private struct X509_CINF
{
public IntPtr version;
public IntPtr serialNumber;
public IntPtr signature;
public IntPtr issuer;
public IntPtr validity;
public IntPtr subject;
public IntPtr key;
public IntPtr issuerUID;
public IntPtr subjectUID;
public IntPtr extensions;
}
#endregion
#region X509
[StructLayout(LayoutKind.Sequential)]
private struct X509
{
public IntPtr cert_info;
public IntPtr sig_alg;
public IntPtr signature;
public int valid;
public int references;
public IntPtr name;
#region CRYPTO_EX_DATA ex_data
public IntPtr ex_data_sk;
public int ex_data_dummy;
#endregion
public int ex_pathlen;
public int ex_pcpathlen;
public uint ex_flags;
public uint ex_kusage;
public uint ex_xkusage;
public uint ex_nscert;
public IntPtr skid;
public IntPtr akid;
public IntPtr policy_cache;
public IntPtr rfc3779_addr;
public IntPtr rfc3779_asid;
[MarshalAs(UnmanagedType.ByValArray, SizeConst = Native.SHA_DIGEST_LENGTH)]
public byte[] sha1_hash;
public IntPtr aux;
}
#endregion
#endregion
#region Properties
private X509 Raw
{
get { return (X509)Marshal.PtrToStructure(this.ptr, typeof(X509)); }
}
private X509_CINF RawCertInfo
{
get { return (X509_CINF)Marshal.PtrToStructure(this.Raw.cert_info, typeof(X509_CINF)); }
}
private X509_VAL RawValidity
{
get { return (X509_VAL)Marshal.PtrToStructure(this.RawCertInfo.validity, typeof(X509_VAL)); }
}
/// <summary>
/// Uses X509_get_subject_name() and X509_set_issuer_name()
/// </summary>
public X509Name Subject
{
get
{
// Get the native pointer for the subject name
IntPtr name_ptr = Native.ExpectNonNull(Native.X509_get_subject_name(this.ptr));
X509Name ret = new X509Name(name_ptr, true);
// Duplicate the native pointer, as the X509_get_subject_name returns a pointer
// that is owned by the X509 object
ret.AddRef();
return ret;
}
set { Native.ExpectSuccess(Native.X509_set_subject_name(this.ptr, value.Handle)); }
}
/// <summary>
/// Uses X509_get_issuer_name() and X509_set_issuer_name()
/// </summary>
public X509Name Issuer
{
get
{
IntPtr name_ptr = Native.ExpectNonNull(Native.X509_get_issuer_name(this.ptr));
X509Name name = new X509Name(name_ptr, true);
name.AddRef();
return name;
}
set { Native.ExpectSuccess(Native.X509_set_issuer_name(this.ptr, value.Handle)); }
}
/// <summary>
/// Uses X509_get_serialNumber() and X509_set_serialNumber()
/// </summary>
public int SerialNumber
{
get { return Asn1Integer.ToInt32(Native.X509_get_serialNumber(this.ptr)); }
set
{
using (Asn1Integer asnInt = new Asn1Integer(value))
{
Native.ExpectSuccess(Native.X509_set_serialNumber(this.ptr, asnInt.Handle));
}
}
}
/// <summary>
/// Uses the notBefore field and X509_set_notBefore()
/// </summary>
public DateTime NotBefore
{
get { return Asn1DateTime.ToDateTime(this.RawValidity.notBefore); }
set
{
using (Asn1DateTime asnDateTime = new Asn1DateTime(value))
{
Native.ExpectSuccess(Native.X509_set_notBefore(this.ptr, asnDateTime.Handle));
}
}
}
/// <summary>
/// Uses the notAfter field and X509_set_notAfter()
/// </summary>
public DateTime NotAfter
{
get { return Asn1DateTime.ToDateTime(this.RawValidity.notAfter); }
set
{
using (Asn1DateTime asnDateTime = new Asn1DateTime(value))
{
Native.ExpectSuccess(Native.X509_set_notAfter(this.ptr, asnDateTime.Handle));
}
}
}
/// <summary>
/// Uses the version field and X509_set_version()
/// </summary>
public int Version
{
get { return Native.ASN1_INTEGER_get(this.RawCertInfo.version); }
set { Native.ExpectSuccess(Native.X509_set_version(this.ptr, value)); }
}
/// <summary>
/// Uses X509_get_pubkey() and X509_set_pubkey()
/// </summary>
public CryptoKey PublicKey
{
get
{
// X509_get_pubkey() will increment the refcount internally
IntPtr key_ptr = Native.ExpectNonNull(Native.X509_get_pubkey(this.ptr));
return new CryptoKey(key_ptr, true);
}
set { Native.ExpectSuccess(Native.X509_set_pubkey(this.ptr, value.Handle)); }
}
/// <summary>
/// Returns whether or not a Private Key is attached to this Certificate
/// </summary>
public bool HasPrivateKey
{
get { return privateKey != null; }
}
/// <summary>
/// Gets and Sets the Private Key for this Certificate.
/// The Private Key MUST match the Public Key.
/// </summary>
public CryptoKey PrivateKey
{
get { return privateKey.CopyRef(); }
set
{
if (CheckPrivateKey(value))
{
privateKey = value.CopyRef();
}
else
{
throw new ArgumentException("Private key doesn't correspond to the this certificate");
}
}
}
/// <summary>
/// Returns the PEM formatted string of this object
/// </summary>
public string PEM
{
get
{
using (BIO bio = BIO.MemoryBuffer())
{
this.Write(bio);
return bio.ReadString();
}
}
}
#endregion
#region Methods
/// <summary>
/// Calls X509_sign()
/// </summary>
/// <param name="pkey"></param>
/// <param name="digest"></param>
public void Sign(CryptoKey pkey, MessageDigest digest)
{
if (Native.X509_sign(this.ptr, pkey.Handle, digest.Handle) == 0)
throw new OpenSslException();
}
/// <summary>
/// Returns X509_check_private_key()
/// </summary>
/// <param name="pkey"></param>
/// <returns></returns>
public bool CheckPrivateKey(CryptoKey pkey)
{
return Native.X509_check_private_key(this.ptr, pkey.Handle) == 1;
}
/// <summary>
/// Returns X509_check_trust()
/// </summary>
/// <param name="id"></param>
/// <param name="flags"></param>
/// <returns></returns>
public bool CheckTrust(int id, int flags)
{
return Native.X509_check_trust(this.ptr, id, flags) == 1;
}
/// <summary>
/// Returns X509_verify()
/// </summary>
/// <param name="pkey"></param>
/// <returns></returns>
public bool Verify(CryptoKey pkey)
{
int ret = Native.X509_verify(this.ptr, pkey.Handle);
if (ret < 0)
throw new OpenSslException();
return ret == 1;
}
/// <summary>
/// Returns X509_digest()
/// </summary>
/// <param name="type"></param>
/// <param name="digest"></param>
/// <returns></returns>
public ArraySegment<byte> Digest(IntPtr type, byte[] digest)
{
uint len = (uint)digest.Length;
Native.ExpectSuccess(Native.X509_digest(this.ptr, type, digest, ref len));
return new ArraySegment<byte>(digest, 0, (int)len);
}
/// <summary>
/// Returns X509_pubkey_digest()
/// </summary>
/// <param name="type"></param>
/// <param name="digest"></param>
/// <returns></returns>
public ArraySegment<byte> DigestPublicKey(IntPtr type, byte[] digest)
{
uint len = (uint)digest.Length;
Native.ExpectSuccess(Native.X509_pubkey_digest(this.ptr, type, digest, ref len));
return new ArraySegment<byte>(digest, 0, (int)len);
}
/// <summary>
/// Calls PEM_write_bio_X509()
/// </summary>
/// <param name="bio"></param>
public void Write(BIO bio)
{
Native.ExpectSuccess(Native.PEM_write_bio_X509(bio.Handle, this.ptr));
}
/// <summary>
/// Calls X509_print()
/// </summary>
/// <param name="bio"></param>
public override void Print(BIO bio)
{
Native.ExpectSuccess(Native.X509_print(bio.Handle, this.ptr));
}
/// <summary>
/// Converts a X509 into a request using X509_to_X509_REQ()
/// </summary>
/// <param name="pkey"></param>
/// <param name="digest"></param>
/// <returns></returns>
public X509Request CreateRequest(CryptoKey pkey, MessageDigest digest)
{
return new X509Request(Native.ExpectNonNull(Native.X509_to_X509_REQ(this.ptr, pkey.Handle, digest.Handle)), true);
}
/// <summary>
/// Calls X509_add_ext()
/// </summary>
/// <param name="ext"></param>
public void AddExtension(X509Extension ext)
{
Native.ExpectSuccess(Native.X509_add_ext(this.ptr, ext.Handle, -1));
}
/// <summary>
/// Calls X509_add1_ext_i2d()
/// </summary>
/// <param name="name"></param>
/// <param name="value"></param>
/// <param name="crit"></param>
/// <param name="flags"></param>
public void AddExtension(string name, byte[] value, int crit, uint flags)
{
Native.ExpectSuccess(Native.X509_add1_ext_i2d(this.ptr, Native.TextToNID(name), value, crit, flags));
}
/// <summary>
///
/// </summary>
public Core.Stack<X509Extension> Extensions
{
get
{
if (RawCertInfo.extensions != IntPtr.Zero)
{
return new Core.Stack<X509Extension>(RawCertInfo.extensions, false);
}
return null;
}
}
/// <summary>
///
/// </summary>
/// <param name="sk_ext"></param>
public void AddExtensions(Core.Stack<X509Extension> sk_ext)
{
foreach (X509Extension ext in sk_ext)
{
AddExtension(ext);
}
}
#endregion
#region Overrides
/// <summary>
/// Calls X509_free()
/// </summary>
protected override void OnDispose()
{
Native.X509_free(this.ptr);
if (privateKey != null)
{
privateKey.Dispose();
privateKey = null;
}
}
/// <summary>
/// Compares X509Certificate
/// </summary>
/// <param name="obj"></param>
/// <returns></returns>
public override bool Equals(object obj)
{
X509Certificate rhs = obj as X509Certificate;
if (rhs == null)
return false;
return this.CompareTo(rhs) == 0;
}
/// <summary>
/// Returns the hash code of the issuer's oneline xor'd with the serial number
/// </summary>
/// <returns></returns>
public override int GetHashCode()
{
return this.Issuer.OneLine.GetHashCode() ^ this.SerialNumber;
}
internal override CryptoLockTypes LockType
{
get { return CryptoLockTypes.CRYPTO_LOCK_X509; }
}
internal override Type RawReferenceType
{
get { return typeof(X509); }
}
#endregion
#region IComparable Members
/// <summary>
/// Returns X509_cmp()
/// </summary>
/// <param name="other"></param>
/// <returns></returns>
public int CompareTo(X509Certificate other)
{
return Native.X509_cmp(this.ptr, other.ptr);
}
#endregion
#region Fields
private CryptoKey privateKey;
#endregion
}
}
| |
// "Therefore those skilled at the unorthodox
// are infinite as heaven and earth,
// inexhaustible as the great rivers.
// When they come to an end,
// they begin again,
// like the days and months;
// they die and are reborn,
// like the four seasons."
//
// - Sun Tsu,
// "The Art of War"
using System;
using System.Globalization;
using Scientia.HtmlRenderer.Adapters.Entities;
using Scientia.HtmlRenderer.Core.Dom;
using Scientia.HtmlRenderer.Core.Entities;
using Scientia.HtmlRenderer.Core.Handlers;
using Scientia.HtmlRenderer.Core.Utils;
namespace Scientia.HtmlRenderer.Core.Parse
{
/// <summary>
/// Handle css DOM tree generation from raw html and stylesheet.
/// </summary>
internal sealed class DomParser
{
#region Fields and Consts
/// <summary>
/// Parser for CSS
/// </summary>
private readonly CssParser CssParser;
#endregion
/// <summary>
/// Init.
/// </summary>
public DomParser(CssParser cssParser)
{
ArgChecker.AssertArgNotNull(cssParser, "cssParser");
this.CssParser = cssParser;
}
/// <summary>
/// Generate css tree by parsing the given html and applying the given css style data on it.
/// </summary>
/// <param name="html">the html to parse</param>
/// <param name="htmlContainer">the html container to use for reference resolve</param>
/// <param name="cssData">the css data to use</param>
/// <returns>the root of the generated tree</returns>
public CssBox GenerateCssTree(string html, HtmlContainerInt htmlContainer, ref CssData cssData)
{
var root = HtmlParser.ParseDocument(html);
if (root != null)
{
root.HtmlContainer = htmlContainer;
bool cssDataChanged = false;
this.CascadeParseStyles(root, htmlContainer, ref cssData, ref cssDataChanged);
this.CascadeApplyStyles(root, cssData);
this.SetTextSelectionStyle(htmlContainer, cssData);
CorrectTextBoxes(root);
CorrectImgBoxes(root);
bool followingBlock = true;
CorrectLineBreaksBlocks(root, ref followingBlock);
CorrectInlineBoxesParent(root);
CorrectBlockInsideInline(root);
CorrectInlineBoxesParent(root);
}
return root;
}
#region Private methods
/// <summary>
/// Read styles defined inside the dom structure in links and style elements.<br/>
/// If the html tag is "style" tag parse it content and add to the css data for all future tags parsing.<br/>
/// If the html tag is "link" that point to style data parse it content and add to the css data for all future tags parsing.<br/>
/// </summary>
/// <param name="box">the box to parse style data in</param>
/// <param name="htmlContainer">the html container to use for reference resolve</param>
/// <param name="cssData">the style data to fill with found styles</param>
/// <param name="cssDataChanged">check if the css data has been modified by the handled html not to change the base css data</param>
private void CascadeParseStyles(CssBox box, HtmlContainerInt htmlContainer, ref CssData cssData, ref bool cssDataChanged)
{
if (box.HtmlTag != null)
{
// Check for the <link rel=stylesheet> tag
if (box.HtmlTag.Name.Equals("link", StringComparison.CurrentCultureIgnoreCase) &&
box.GetAttribute("rel", string.Empty).Equals("stylesheet", StringComparison.CurrentCultureIgnoreCase))
{
CloneCssData(ref cssData, ref cssDataChanged);
string stylesheet;
CssData stylesheetData;
StylesheetLoadHandler.LoadStylesheet(htmlContainer, box.GetAttribute("href", string.Empty), box.HtmlTag.Attributes, out stylesheet, out stylesheetData);
if (stylesheet != null)
this.CssParser.ParseStyleSheet(cssData, stylesheet);
else if (stylesheetData != null)
cssData.Combine(stylesheetData);
}
// Check for the <style> tag
if (box.HtmlTag.Name.Equals("style", StringComparison.CurrentCultureIgnoreCase) && box.Boxes.Count > 0)
{
CloneCssData(ref cssData, ref cssDataChanged);
foreach (var child in box.Boxes)
this.CssParser.ParseStyleSheet(cssData, child.Text.CutSubstring());
}
}
foreach (var childBox in box.Boxes)
{
this.CascadeParseStyles(childBox, htmlContainer, ref cssData, ref cssDataChanged);
}
}
/// <summary>
/// Applies style to all boxes in the tree.<br/>
/// If the html tag has style defined for each apply that style to the css box of the tag.<br/>
/// If the html tag has "class" attribute and the class name has style defined apply that style on the tag css box.<br/>
/// If the html tag has "style" attribute parse it and apply the parsed style on the tag css box.<br/>
/// </summary>
/// <param name="box">the box to apply the style to</param>
/// <param name="cssData">the style data for the html</param>
private void CascadeApplyStyles(CssBox box, CssData cssData)
{
box.InheritStyle();
if (box.HtmlTag != null)
{
// try assign style using all wildcard
AssignCssBlocks(box, cssData, "*");
// try assign style using the html element tag
AssignCssBlocks(box, cssData, box.HtmlTag.Name);
// try assign style using the "class" attribute of the html element
if (box.HtmlTag.HasAttribute("class"))
{
AssignClassCssBlocks(box, cssData);
}
// try assign style using the "id" attribute of the html element
if (box.HtmlTag.HasAttribute("id"))
{
var id = box.HtmlTag.TryGetAttribute("id");
AssignCssBlocks(box, cssData, "#" + id);
}
this.TranslateAttributes(box.HtmlTag, box);
// Check for the style="" attribute
if (box.HtmlTag.HasAttribute("style"))
{
var block = this.CssParser.ParseCssBlock(box.HtmlTag.Name, box.HtmlTag.TryGetAttribute("style"));
if (block != null)
AssignCssBlock(box, block);
}
}
// cascade text decoration only to boxes that actually have text so it will be handled correctly.
if (box.TextDecoration != String.Empty && box.Text == null)
{
foreach (var childBox in box.Boxes)
childBox.TextDecoration = box.TextDecoration;
box.TextDecoration = string.Empty;
}
foreach (var childBox in box.Boxes)
{
this.CascadeApplyStyles(childBox, cssData);
}
}
/// <summary>
/// Set the selected text style (selection text color and background color).
/// </summary>
/// <param name="htmlContainer"> </param>
/// <param name="cssData">the style data</param>
private void SetTextSelectionStyle(HtmlContainerInt htmlContainer, CssData cssData)
{
htmlContainer.SelectionForeColor = RColor.Empty;
htmlContainer.SelectionBackColor = RColor.Empty;
if (cssData.ContainsCssBlock("::selection"))
{
var blocks = cssData.GetCssBlock("::selection");
foreach (var block in blocks)
{
if (block.Properties.ContainsKey("color"))
htmlContainer.SelectionForeColor = this.CssParser.ParseColor(block.Properties["color"]);
if (block.Properties.ContainsKey("background-color"))
htmlContainer.SelectionBackColor = this.CssParser.ParseColor(block.Properties["background-color"]);
}
}
}
/// <summary>
/// Assigns the given css classes to the given css box checking if matching.<br/>
/// Support multiple classes in single attribute separated by whitespace.
/// </summary>
/// <param name="box">the css box to assign css to</param>
/// <param name="cssData">the css data to use to get the matching css blocks</param>
private static void AssignClassCssBlocks(CssBox box, CssData cssData)
{
var classes = box.HtmlTag.TryGetAttribute("class");
var startIdx = 0;
while (startIdx < classes.Length)
{
while (startIdx < classes.Length && classes[startIdx] == ' ')
startIdx++;
if (startIdx < classes.Length)
{
var endIdx = classes.IndexOf(' ', startIdx);
if (endIdx < 0)
endIdx = classes.Length;
var cls = "." + classes.Substring(startIdx, endIdx - startIdx);
AssignCssBlocks(box, cssData, cls);
AssignCssBlocks(box, cssData, box.HtmlTag.Name + cls);
startIdx = endIdx + 1;
}
}
}
/// <summary>
/// Assigns the given css style blocks to the given css box checking if matching.
/// </summary>
/// <param name="box">the css box to assign css to</param>
/// <param name="cssData">the css data to use to get the matching css blocks</param>
/// <param name="className">the class selector to search for css blocks</param>
private static void AssignCssBlocks(CssBox box, CssData cssData, string className)
{
var blocks = cssData.GetCssBlock(className);
foreach (var block in blocks)
{
if (IsBlockAssignableToBox(box, block))
{
AssignCssBlock(box, block);
}
}
}
/// <summary>
/// Check if the given css block is assignable to the given css box.<br/>
/// the block is assignable if it has no hierarchical selectors or if the hierarchy matches.<br/>
/// Special handling for ":hover" pseudo-class.<br/>
/// </summary>
/// <param name="box">the box to check assign to</param>
/// <param name="block">the block to check assign of</param>
/// <returns>true - the block is assignable to the box, false - otherwise</returns>
private static bool IsBlockAssignableToBox(CssBox box, CssBlock block)
{
bool assignable = true;
if (block.Selectors != null)
{
assignable = IsBlockAssignableToBoxWithSelector(box, block);
}
else if (box.HtmlTag.Name.Equals("a", StringComparison.OrdinalIgnoreCase) && block.Class.Equals("a", StringComparison.OrdinalIgnoreCase) && !box.HtmlTag.HasAttribute("href"))
{
assignable = false;
}
if (assignable && block.Hover)
{
box.HtmlContainer.AddHoverBox(box, block);
assignable = false;
}
return assignable;
}
/// <summary>
/// Check if the given css block is assignable to the given css box by validating the selector.<br/>
/// </summary>
/// <param name="box">the box to check assign to</param>
/// <param name="block">the block to check assign of</param>
/// <returns>true - the block is assignable to the box, false - otherwise</returns>
private static bool IsBlockAssignableToBoxWithSelector(CssBox box, CssBlock block)
{
foreach (var selector in block.Selectors)
{
bool matched = false;
while (!matched)
{
box = box.ParentBox;
while (box != null && box.HtmlTag == null)
box = box.ParentBox;
if (box == null)
return false;
if (box.HtmlTag.Name.Equals(selector.Class, StringComparison.InvariantCultureIgnoreCase))
matched = true;
if (!matched && box.HtmlTag.HasAttribute("class"))
{
var className = box.HtmlTag.TryGetAttribute("class");
if (selector.Class.Equals("." + className, StringComparison.InvariantCultureIgnoreCase) || selector.Class.Equals(box.HtmlTag.Name + "." + className, StringComparison.InvariantCultureIgnoreCase))
matched = true;
}
if (!matched && box.HtmlTag.HasAttribute("id"))
{
var id = box.HtmlTag.TryGetAttribute("id");
if (selector.Class.Equals("#" + id, StringComparison.InvariantCultureIgnoreCase))
matched = true;
}
if (!matched && selector.DirectParent)
return false;
}
}
return true;
}
/// <summary>
/// Assigns the given css style block properties to the given css box.
/// </summary>
/// <param name="box">the css box to assign css to</param>
/// <param name="block">the css block to assign</param>
private static void AssignCssBlock(CssBox box, CssBlock block)
{
foreach (var prop in block.Properties)
{
var value = prop.Value;
if (prop.Value == CssConstants.Inherit && box.ParentBox != null)
{
value = CssUtils.GetPropertyValue(box.ParentBox, prop.Key);
}
if (IsStyleOnElementAllowed(box, prop.Key, value))
{
CssUtils.SetPropertyValue(box, prop.Key, value);
}
}
}
/// <summary>
/// Check if the given style is allowed to be set on the given css box.<br/>
/// Used to prevent invalid CssBoxes creation like table with inline display style.
/// </summary>
/// <param name="box">the css box to assign css to</param>
/// <param name="key">the style key to cehck</param>
/// <param name="value">the style value to check</param>
/// <returns>true - style allowed, false - not allowed</returns>
private static bool IsStyleOnElementAllowed(CssBox box, string key, string value)
{
if (box.HtmlTag != null && key == HtmlConstants.Display)
{
switch (box.HtmlTag.Name)
{
case HtmlConstants.Table:
return value == CssConstants.Table;
case HtmlConstants.Tr:
return value == CssConstants.TableRow;
case HtmlConstants.Tbody:
return value == CssConstants.TableRowGroup;
case HtmlConstants.Thead:
return value == CssConstants.TableHeaderGroup;
case HtmlConstants.Tfoot:
return value == CssConstants.TableFooterGroup;
case HtmlConstants.Col:
return value == CssConstants.TableColumn;
case HtmlConstants.Colgroup:
return value == CssConstants.TableColumnGroup;
case HtmlConstants.Td:
case HtmlConstants.Th:
return value == CssConstants.TableCell;
case HtmlConstants.Caption:
return value == CssConstants.TableCaption;
}
}
return true;
}
/// <summary>
/// Clone css data if it has not already been cloned.<br/>
/// Used to preserve the base css data used when changed by style inside html.
/// </summary>
private static void CloneCssData(ref CssData cssData, ref bool cssDataChanged)
{
if (!cssDataChanged)
{
cssDataChanged = true;
cssData = cssData.Clone();
}
}
/// <summary>
///
/// </summary>
/// <param name="tag"></param>
/// <param name="box"></param>
private void TranslateAttributes(HtmlTag tag, CssBox box)
{
if (tag.HasAttributes())
{
foreach (string att in tag.Attributes.Keys)
{
string value = tag.Attributes[att];
switch (att)
{
case HtmlConstants.Align:
if (value == HtmlConstants.Left || value == HtmlConstants.Center || value == HtmlConstants.Right || value == HtmlConstants.Justify)
box.TextAlign = value.ToLower();
else
box.VerticalAlign = value.ToLower();
break;
case HtmlConstants.Background:
box.BackgroundImage = value.ToLower();
break;
case HtmlConstants.Bgcolor:
box.BackgroundColor = value.ToLower();
break;
case HtmlConstants.Border:
if (!string.IsNullOrEmpty(value) && value != "0")
box.BorderLeftStyle = box.BorderTopStyle = box.BorderRightStyle = box.BorderBottomStyle = CssConstants.Solid;
box.BorderLeftWidth = box.BorderTopWidth = box.BorderRightWidth = box.BorderBottomWidth = TranslateLength(value);
if (tag.Name == HtmlConstants.Table)
{
if (value != "0")
ApplyTableBorder(box, "1px");
}
else
{
box.BorderTopStyle = box.BorderLeftStyle = box.BorderRightStyle = box.BorderBottomStyle = CssConstants.Solid;
}
break;
case HtmlConstants.Bordercolor:
box.BorderLeftColor = box.BorderTopColor = box.BorderRightColor = box.BorderBottomColor = value.ToLower();
break;
case HtmlConstants.Cellspacing:
box.BorderSpacing = TranslateLength(value);
break;
case HtmlConstants.Cellpadding:
ApplyTablePadding(box, value);
break;
case HtmlConstants.Color:
box.Color = value.ToLower();
break;
case HtmlConstants.Dir:
box.Direction = value.ToLower();
break;
case HtmlConstants.Face:
box.FontFamily = this.CssParser.ParseFontFamily(value);
break;
case HtmlConstants.Height:
box.Height = TranslateLength(value);
break;
case HtmlConstants.Hspace:
box.MarginRight = box.MarginLeft = TranslateLength(value);
break;
case HtmlConstants.Nowrap:
box.WhiteSpace = CssConstants.NoWrap;
break;
case HtmlConstants.Size:
if (tag.Name.Equals(HtmlConstants.Hr, StringComparison.OrdinalIgnoreCase))
box.Height = TranslateLength(value);
else if (tag.Name.Equals(HtmlConstants.Font, StringComparison.OrdinalIgnoreCase))
box.FontSize = value;
break;
case HtmlConstants.Valign:
box.VerticalAlign = value.ToLower();
break;
case HtmlConstants.Vspace:
box.MarginTop = box.MarginBottom = TranslateLength(value);
break;
case HtmlConstants.Width:
box.Width = TranslateLength(value);
break;
}
}
}
}
/// <summary>
/// Converts an HTML length into a Css length
/// </summary>
/// <param name="htmlLength"></param>
/// <returns></returns>
private static string TranslateLength(string htmlLength)
{
CssLength len = new CssLength(htmlLength);
if (len.HasError)
{
return string.Format(NumberFormatInfo.InvariantInfo, "{0}px", htmlLength);
}
return htmlLength;
}
/// <summary>
/// Cascades to the TD's the border spacified in the TABLE tag.
/// </summary>
/// <param name="table"></param>
/// <param name="border"></param>
private static void ApplyTableBorder(CssBox table, string border)
{
SetForAllCells(table, cell =>
{
cell.BorderLeftStyle = cell.BorderTopStyle = cell.BorderRightStyle = cell.BorderBottomStyle = CssConstants.Solid;
cell.BorderLeftWidth = cell.BorderTopWidth = cell.BorderRightWidth = cell.BorderBottomWidth = border;
});
}
/// <summary>
/// Cascades to the TD's the border spacified in the TABLE tag.
/// </summary>
/// <param name="table"></param>
/// <param name="padding"></param>
private static void ApplyTablePadding(CssBox table, string padding)
{
var length = TranslateLength(padding);
SetForAllCells(table, cell => cell.PaddingLeft = cell.PaddingTop = cell.PaddingRight = cell.PaddingBottom = length);
}
/// <summary>
/// Execute action on all the "td" cells of the table.<br/>
/// Handle if there is "theader" or "tbody" exists.
/// </summary>
/// <param name="table">the table element</param>
/// <param name="action">the action to execute</param>
private static void SetForAllCells(CssBox table, ActionInt<CssBox> action)
{
foreach (var l1 in table.Boxes)
{
foreach (var l2 in l1.Boxes)
{
if (l2.HtmlTag != null && l2.HtmlTag.Name == "td")
{
action(l2);
}
else
{
foreach (var l3 in l2.Boxes)
{
action(l3);
}
}
}
}
}
/// <summary>
/// Go over all the text boxes (boxes that have some text that will be rendered) and
/// remove all boxes that have only white-spaces but are not 'preformatted' so they do not effect
/// the rendered html.
/// </summary>
/// <param name="box">the current box to correct its sub-tree</param>
private static void CorrectTextBoxes(CssBox box)
{
for (int i = box.Boxes.Count - 1; i >= 0; i--)
{
var childBox = box.Boxes[i];
if (childBox.Text != null)
{
// is the box has text
var keepBox = !childBox.Text.IsEmptyOrWhitespace();
// is the box is pre-formatted
keepBox = keepBox || childBox.WhiteSpace == CssConstants.Pre || childBox.WhiteSpace == CssConstants.PreWrap;
// is the box is only one in the parent
keepBox = keepBox || box.Boxes.Count == 1;
// is it a whitespace between two inline boxes
keepBox = keepBox || (i > 0 && i < box.Boxes.Count - 1 && box.Boxes[i - 1].IsInline && box.Boxes[i + 1].IsInline);
// is first/last box where is in inline box and it's next/previous box is inline
keepBox = keepBox || (i == 0 && box.Boxes.Count > 1 && box.Boxes[1].IsInline && box.IsInline) || (i == box.Boxes.Count - 1 && box.Boxes.Count > 1 && box.Boxes[i - 1].IsInline && box.IsInline);
if (keepBox)
{
// valid text box, parse it to words
childBox.ParseToWords();
}
else
{
// remove text box that has no
childBox.ParentBox.Boxes.RemoveAt(i);
}
}
else
{
// recursive
CorrectTextBoxes(childBox);
}
}
}
/// <summary>
/// Go over all image boxes and if its display style is set to block, put it inside another block but set the image to inline.
/// </summary>
/// <param name="box">the current box to correct its sub-tree</param>
private static void CorrectImgBoxes(CssBox box)
{
for (int i = box.Boxes.Count - 1; i >= 0; i--)
{
var childBox = box.Boxes[i];
if (childBox is CssBoxImage && childBox.Display == CssConstants.Block)
{
var block = CssBox.CreateBlock(childBox.ParentBox, null, childBox);
childBox.ParentBox = block;
childBox.Display = CssConstants.Inline;
}
else
{
// recursive
CorrectImgBoxes(childBox);
}
}
}
/// <summary>
/// Correct the DOM tree recursively by replacing "br" html boxes with anonymous blocks that respect br spec.<br/>
/// If the "br" tag is after inline box then the anon block will have zero height only acting as newline,
/// but if it is after block box then it will have min-height of the font size so it will create empty line.
/// </summary>
/// <param name="box">the current box to correct its sub-tree</param>
/// <param name="followingBlock">used to know if the br is following a box so it should create an empty line or not so it only
/// move to a new line</param>
private static void CorrectLineBreaksBlocks(CssBox box, ref bool followingBlock)
{
followingBlock = followingBlock || box.IsBlock;
foreach (var childBox in box.Boxes)
{
CorrectLineBreaksBlocks(childBox, ref followingBlock);
followingBlock = childBox.Words.Count == 0 && (followingBlock || childBox.IsBlock);
}
int lastBr = -1;
CssBox brBox;
do
{
brBox = null;
for (int i = 0; i < box.Boxes.Count && brBox == null; i++)
{
if (i > lastBr && box.Boxes[i].IsBrElement)
{
brBox = box.Boxes[i];
lastBr = i;
}
else if (box.Boxes[i].Words.Count > 0)
{
followingBlock = false;
}
else if (box.Boxes[i].IsBlock)
{
followingBlock = true;
}
}
if (brBox != null)
{
brBox.Display = CssConstants.Block;
if (followingBlock)
brBox.Height = ".95em"; // TODO:a check the height to min-height when it is supported
}
}
while (brBox != null);
}
/// <summary>
/// Correct DOM tree if there is block boxes that are inside inline blocks.<br/>
/// Need to rearrange the tree so block box will be only the child of other block box.
/// </summary>
/// <param name="box">the current box to correct its sub-tree</param>
private static void CorrectBlockInsideInline(CssBox box)
{
try
{
if (DomUtils.ContainsInlinesOnly(box) && !ContainsInlinesOnlyDeep(box))
{
var tempRightBox = CorrectBlockInsideInlineImp(box);
while (tempRightBox != null)
{
// loop on the created temp right box for the fixed box until no more need (optimization remove recursion)
CssBox newTempRightBox = null;
if (DomUtils.ContainsInlinesOnly(tempRightBox) && !ContainsInlinesOnlyDeep(tempRightBox))
newTempRightBox = CorrectBlockInsideInlineImp(tempRightBox);
tempRightBox.ParentBox.SetAllBoxes(tempRightBox);
tempRightBox.ParentBox = null;
tempRightBox = newTempRightBox;
}
}
if (!DomUtils.ContainsInlinesOnly(box))
{
foreach (var childBox in box.Boxes)
{
CorrectBlockInsideInline(childBox);
}
}
}
catch (Exception ex)
{
box.HtmlContainer.ReportError(HtmlRenderErrorType.HtmlParsing, "Failed in block inside inline box correction", ex);
}
}
/// <summary>
/// Rearrange the DOM of the box to have block box with boxes before the inner block box and after.
/// </summary>
/// <param name="box">the box that has the problem</param>
private static CssBox CorrectBlockInsideInlineImp(CssBox box)
{
if (box.Display == CssConstants.Inline)
box.Display = CssConstants.Block;
if (box.Boxes.Count > 1 || box.Boxes[0].Boxes.Count > 1)
{
var leftBlock = CssBox.CreateBlock(box);
while (ContainsInlinesOnlyDeep(box.Boxes[0]))
box.Boxes[0].ParentBox = leftBlock;
leftBlock.SetBeforeBox(box.Boxes[0]);
var splitBox = box.Boxes[1];
splitBox.ParentBox = null;
CorrectBlockSplitBadBox(box, splitBox, leftBlock);
// remove block that did not get any inner elements
if (leftBlock.Boxes.Count < 1)
leftBlock.ParentBox = null;
int minBoxes = leftBlock.ParentBox != null ? 2 : 1;
if (box.Boxes.Count > minBoxes)
{
// create temp box to handle the tail elements and then get them back so no deep hierarchy is created
var tempRightBox = CssBox.CreateBox(box, null, box.Boxes[minBoxes]);
while (box.Boxes.Count > minBoxes + 1)
box.Boxes[minBoxes + 1].ParentBox = tempRightBox;
return tempRightBox;
}
}
else if (box.Boxes[0].Display == CssConstants.Inline)
{
box.Boxes[0].Display = CssConstants.Block;
}
return null;
}
/// <summary>
/// Split bad box that has inline and block boxes into two parts, the left - before the block box
/// and right - after the block box.
/// </summary>
/// <param name="parentBox">the parent box that has the problem</param>
/// <param name="badBox">the box to split into different boxes</param>
/// <param name="leftBlock">the left block box that is created for the split</param>
private static void CorrectBlockSplitBadBox(CssBox parentBox, CssBox badBox, CssBox leftBlock)
{
CssBox leftbox = null;
while (badBox.Boxes[0].IsInline && ContainsInlinesOnlyDeep(badBox.Boxes[0]))
{
if (leftbox == null)
{
// if there is no elements in the left box there is no reason to keep it
leftbox = CssBox.CreateBox(leftBlock, badBox.HtmlTag);
leftbox.InheritStyle(badBox, true);
}
badBox.Boxes[0].ParentBox = leftbox;
}
var splitBox = badBox.Boxes[0];
if (!ContainsInlinesOnlyDeep(splitBox))
{
CorrectBlockSplitBadBox(parentBox, splitBox, leftBlock);
splitBox.ParentBox = null;
}
else
{
splitBox.ParentBox = parentBox;
}
if (badBox.Boxes.Count > 0)
{
CssBox rightBox;
if (splitBox.ParentBox != null || parentBox.Boxes.Count < 3)
{
rightBox = CssBox.CreateBox(parentBox, badBox.HtmlTag);
rightBox.InheritStyle(badBox, true);
if (parentBox.Boxes.Count > 2)
rightBox.SetBeforeBox(parentBox.Boxes[1]);
if (splitBox.ParentBox != null)
splitBox.SetBeforeBox(rightBox);
}
else
{
rightBox = parentBox.Boxes[2];
}
rightBox.SetAllBoxes(badBox);
}
else if (splitBox.ParentBox != null && parentBox.Boxes.Count > 1)
{
splitBox.SetBeforeBox(parentBox.Boxes[1]);
if (splitBox.HtmlTag != null && splitBox.HtmlTag.Name == "br" && (leftbox != null || leftBlock.Boxes.Count > 1))
splitBox.Display = CssConstants.Inline;
}
}
/// <summary>
/// Makes block boxes be among only block boxes and all inline boxes have block parent box.<br/>
/// Inline boxes should live in a pool of Inline boxes only so they will define a single block.<br/>
/// At the end of this process a block box will have only block siblings and inline box will have
/// only inline siblings.
/// </summary>
/// <param name="box">the current box to correct its sub-tree</param>
private static void CorrectInlineBoxesParent(CssBox box)
{
if (ContainsVariantBoxes(box))
{
for (int i = 0; i < box.Boxes.Count; i++)
{
if (box.Boxes[i].IsInline)
{
var newbox = CssBox.CreateBlock(box, null, box.Boxes[i++]);
while (i < box.Boxes.Count && box.Boxes[i].IsInline)
{
box.Boxes[i].ParentBox = newbox;
}
}
}
}
if (!DomUtils.ContainsInlinesOnly(box))
{
foreach (var childBox in box.Boxes)
{
CorrectInlineBoxesParent(childBox);
}
}
}
/// <summary>
/// Check if the given box contains only inline child boxes in all subtree.
/// </summary>
/// <param name="box">the box to check</param>
/// <returns>true - only inline child boxes, false - otherwise</returns>
private static bool ContainsInlinesOnlyDeep(CssBox box)
{
foreach (var childBox in box.Boxes)
{
if (!childBox.IsInline || !ContainsInlinesOnlyDeep(childBox))
{
return false;
}
}
return true;
}
/// <summary>
/// Check if the given box contains inline and block child boxes.
/// </summary>
/// <param name="box">the box to check</param>
/// <returns>true - has variant child boxes, false - otherwise</returns>
private static bool ContainsVariantBoxes(CssBox box)
{
bool hasBlock = false;
bool hasInline = false;
for (int i = 0; i < box.Boxes.Count && (!hasBlock || !hasInline); i++)
{
var isBlock = !box.Boxes[i].IsInline;
hasBlock = hasBlock || isBlock;
hasInline = hasInline || !isBlock;
}
return hasBlock && hasInline;
}
#endregion
}
}
| |
//*********************************************************
//
// Copyright (c) Microsoft. All rights reserved.
// This code is licensed under the MIT License (MIT).
// THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
// ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
// IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
// PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
//
//*********************************************************
using SDKTemplate;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Windows.Globalization;
using Windows.Media.SpeechRecognition;
using Windows.UI.Core;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Documents;
using Windows.UI.Xaml.Navigation;
using Windows.Foundation;
using Windows.ApplicationModel.Resources.Core;
namespace SpeechAndTTS
{
public sealed partial class PredefinedWebSearchGrammarScenario : Page
{
/// <summary>
/// This HResult represents the scenario where a user is prompted to allow in-app speech, but
/// declines. This should only happen on a Phone device, where speech is enabled for the entire device,
/// not per-app.
/// </summary>
private static uint HResultPrivacyStatementDeclined = 0x80045509;
private SpeechRecognizer speechRecognizer;
private CoreDispatcher dispatcher;
private IAsyncOperation<SpeechRecognitionResult> recognitionOperation;
private ResourceContext speechContext;
private ResourceMap speechResourceMap;
public PredefinedWebSearchGrammarScenario()
{
InitializeComponent();
}
/// <summary>
/// When activating the scenario, ensure we have permission from the user to access their microphone, and
/// provide an appropriate path for the user to enable access to the microphone if they haven't
/// given explicit permission for it.
/// </summary>
/// <param name="e">The navigation event details</param>
protected async override void OnNavigatedTo(NavigationEventArgs e)
{
// Save the UI thread dispatcher to allow speech status messages to be shown on the UI.
dispatcher = CoreWindow.GetForCurrentThread().Dispatcher;
bool permissionGained = await AudioCapturePermissions.RequestMicrophonePermission();
if (permissionGained)
{
// Enable the recognition buttons.
btnRecognizeWithUI.IsEnabled = true;
btnRecognizeWithoutUI.IsEnabled = true;
}
else
{
resultTextBlock.Visibility = Visibility.Visible;
resultTextBlock.Text = "Permission to access capture resources was not given by the user; please set the application setting in Settings->Privacy->Microphone.";
}
Language speechLanguage = SpeechRecognizer.SystemSpeechLanguage;
speechContext = ResourceContext.GetForCurrentView();
speechContext.Languages = new string[] { speechLanguage.LanguageTag};
speechResourceMap = ResourceManager.Current.MainResourceMap.GetSubtree("LocalizationSpeechResources");
PopulateLanguageDropDown();
await InitializeRecognizer(SpeechRecognizer.SystemSpeechLanguage);
}
/// <summary>
/// Look up the supported languages for this speech recognition scenario,
/// that are installed on this machine, and populate a dropdown with a list.
/// </summary>
private void PopulateLanguageDropDown()
{
Language defaultLanguage = SpeechRecognizer.SystemSpeechLanguage;
IEnumerable<Language> supportedLanguages = SpeechRecognizer.SupportedTopicLanguages;
foreach (Language lang in supportedLanguages)
{
ComboBoxItem item = new ComboBoxItem();
item.Tag = lang;
item.Content = lang.DisplayName;
cbLanguageSelection.Items.Add(item);
if (lang.LanguageTag == defaultLanguage.LanguageTag)
{
item.IsSelected = true;
cbLanguageSelection.SelectedItem = item;
}
}
}
/// <summary>
/// Ensure that we clean up any state tracking event handlers created in OnNavigatedTo to prevent leaks.
/// </summary>
/// <param name="e">Details about the navigation event</param>
protected override void OnNavigatedFrom(NavigationEventArgs e)
{
base.OnNavigatedFrom(e);
if (speechRecognizer != null)
{
if (speechRecognizer.State != SpeechRecognizerState.Idle)
{
if (recognitionOperation != null)
{
recognitionOperation.Cancel();
recognitionOperation = null;
}
}
speechRecognizer.StateChanged -= SpeechRecognizer_StateChanged;
this.speechRecognizer.Dispose();
this.speechRecognizer = null;
}
}
/// <summary>
/// Initialize Speech Recognizer and compile constraints.
/// </summary>
/// <param name="recognizerLanguage">Language to use for the speech recognizer</param>
/// <returns>Awaitable task.</returns>
private async Task InitializeRecognizer(Language recognizerLanguage)
{
if (speechRecognizer != null)
{
// cleanup prior to re-initializing this scenario.
speechRecognizer.StateChanged -= SpeechRecognizer_StateChanged;
this.speechRecognizer.Dispose();
this.speechRecognizer = null;
}
// Create an instance of SpeechRecognizer.
speechRecognizer = new SpeechRecognizer(recognizerLanguage);
// Provide feedback to the user about the state of the recognizer.
speechRecognizer.StateChanged += SpeechRecognizer_StateChanged;
// Add a web search topic constraint to the recognizer.
var webSearchGrammar = new SpeechRecognitionTopicConstraint(SpeechRecognitionScenario.WebSearch, "webSearch");
speechRecognizer.Constraints.Add(webSearchGrammar);
// RecognizeWithUIAsync allows developers to customize the prompts.
speechRecognizer.UIOptions.AudiblePrompt = "Say what you want to search for...";
speechRecognizer.UIOptions.ExampleText = speechResourceMap.GetValue("WebSearchUIOptionsExampleText", speechContext).ValueAsString;
// Compile the constraint.
SpeechRecognitionCompilationResult compilationResult = await speechRecognizer.CompileConstraintsAsync();
// Check to make sure that the constraints were in a proper format and the recognizer was able to compile it.
if (compilationResult.Status != SpeechRecognitionResultStatus.Success)
{
// Disable the recognition buttons.
btnRecognizeWithUI.IsEnabled = false;
btnRecognizeWithoutUI.IsEnabled = false;
// Let the user know that the grammar didn't compile properly.
resultTextBlock.Visibility = Visibility.Visible;
resultTextBlock.Text = "Unable to compile grammar.";
}
}
/// <summary>
/// Handle SpeechRecognizer state changed events by updating a UI component.
/// </summary>
/// <param name="sender">Speech recognizer that generated this status event</param>
/// <param name="args">The recognizer's status</param>
private async void SpeechRecognizer_StateChanged(SpeechRecognizer sender, SpeechRecognizerStateChangedEventArgs args)
{
await dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
{
MainPage.Current.NotifyUser("Speech recognizer state: " + args.State.ToString(), NotifyType.StatusMessage);
});
}
/// <summary>
/// Uses the recognizer constructed earlier to listen for speech from the user before displaying
/// it back on the screen. Uses the built-in speech recognition UI.
/// </summary>
/// <param name="sender">Button that triggered this event</param>
/// <param name="e">State information about the routed event</param>
private async void RecognizeWithUIWebSearchGrammar_Click(object sender, RoutedEventArgs e)
{
heardYouSayTextBlock.Visibility = resultTextBlock.Visibility = Visibility.Collapsed;
hlOpenPrivacySettings.Visibility = Visibility.Collapsed;
// Start recognition.
try
{
recognitionOperation = speechRecognizer.RecognizeWithUIAsync();
SpeechRecognitionResult speechRecognitionResult = await recognitionOperation;
// If successful, display the recognition result.
if (speechRecognitionResult.Status == SpeechRecognitionResultStatus.Success)
{
heardYouSayTextBlock.Visibility = resultTextBlock.Visibility = Visibility.Visible;
resultTextBlock.Text = speechRecognitionResult.Text;
}
else
{
resultTextBlock.Visibility = Visibility.Visible;
resultTextBlock.Text = string.Format("Speech Recognition Failed, Status: {0}", speechRecognitionResult.Status.ToString());
}
}
catch (TaskCanceledException exception)
{
// TaskCanceledException will be thrown if you exit the scenario while the recognizer is actively
// processing speech. Since this happens here when we navigate out of the scenario, don't try to
// show a message dialog for this exception.
System.Diagnostics.Debug.WriteLine("TaskCanceledException caught while recognition in progress (can be ignored):");
System.Diagnostics.Debug.WriteLine(exception.ToString());
}
catch (Exception exception)
{
// Handle the speech privacy policy error.
if ((uint)exception.HResult == HResultPrivacyStatementDeclined)
{
hlOpenPrivacySettings.Visibility = Visibility.Visible;
}
else
{
var messageDialog = new Windows.UI.Popups.MessageDialog(exception.Message, "Exception");
await messageDialog.ShowAsync();
}
}
}
/// <summary>
/// Uses the recognizer constructed earlier to listen for speech from the user before displaying
/// it back on the screen. Uses developer-provided UI for user feedback.
/// </summary>
/// <param name="sender">Button that triggered this event</param>
/// <param name="e">State information about the routed event</param>
private async void RecognizeWithoutUIWebSearchGrammar_Click(object sender, RoutedEventArgs e)
{
heardYouSayTextBlock.Visibility = resultTextBlock.Visibility = Visibility.Collapsed;
// Disable the UI while recognition is occurring, and provide feedback to the user about current state.
btnRecognizeWithUI.IsEnabled = false;
btnRecognizeWithoutUI.IsEnabled = false;
cbLanguageSelection.IsEnabled = false;
hlOpenPrivacySettings.Visibility = Visibility.Collapsed;
listenWithoutUIButtonText.Text = " listening for speech...";
// Start recognition.
try
{
recognitionOperation = speechRecognizer.RecognizeAsync();
SpeechRecognitionResult speechRecognitionResult = await recognitionOperation;
// If successful, display the recognition result.
if (speechRecognitionResult.Status == SpeechRecognitionResultStatus.Success)
{
heardYouSayTextBlock.Visibility = resultTextBlock.Visibility = Visibility.Visible;
resultTextBlock.Text = speechRecognitionResult.Text;
}
else
{
resultTextBlock.Visibility = Visibility.Visible;
resultTextBlock.Text = string.Format("Speech Recognition Failed, Status: {0}", speechRecognitionResult.Status.ToString());
}
}
catch (TaskCanceledException exception)
{
// TaskCanceledException will be thrown if you exit the scenario while the recognizer is actively
// processing speech. Since this happens here when we navigate out of the scenario, don't try to
// show a message dialog for this exception.
System.Diagnostics.Debug.WriteLine("TaskCanceledException caught while recognition in progress (can be ignored):");
System.Diagnostics.Debug.WriteLine(exception.ToString());
}
catch (Exception exception)
{
// Handle the speech privacy policy error.
if ((uint)exception.HResult == HResultPrivacyStatementDeclined)
{
hlOpenPrivacySettings.Visibility = Visibility.Visible;
}
else
{
var messageDialog = new Windows.UI.Popups.MessageDialog(exception.Message, "Exception");
await messageDialog.ShowAsync();
}
}
// Reset UI state.
listenWithoutUIButtonText.Text = " without UI";
btnRecognizeWithUI.IsEnabled = true;
cbLanguageSelection.IsEnabled = true;
btnRecognizeWithoutUI.IsEnabled = true;
}
/// <summary>
/// When a user changes the speech recognition language, trigger re-initialization of the
/// speech engine with that language, and change any speech-specific UI assets.
/// </summary>
/// <param name="sender">Ignored</param>
/// <param name="e">Ignored</param>
private async void cbLanguageSelection_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
if (speechRecognizer != null)
{
ComboBoxItem item = (ComboBoxItem)(cbLanguageSelection.SelectedItem);
Language newLanguage = (Language)item.Tag;
if (speechRecognizer.CurrentLanguage != newLanguage)
{
// trigger cleanup and re-initialization of speech.
try
{
speechContext.Languages = new string[] { newLanguage.LanguageTag };
await InitializeRecognizer(newLanguage);
}
catch (Exception exception)
{
var messageDialog = new Windows.UI.Popups.MessageDialog(exception.Message, "Exception");
await messageDialog.ShowAsync();
}
}
}
}
/// <summary>
/// Open the Speech, Inking and Typing page under Settings -> Privacy, enabling a user to accept the
/// Microsoft Privacy Policy, and enable personalization.
/// </summary>
/// <param name="sender">Ignored</param>
/// <param name="args">Ignored</param>
private async void openPrivacySettings_Click(Hyperlink sender, HyperlinkClickEventArgs args)
{
await Windows.System.Launcher.LaunchUriAsync(new Uri("ms-settings:privacy-speechtyping"));
}
}
}
| |
namespace MovieFanatic.Data.Migrations
{
using System;
using System.Collections.Generic;
using System.Data.Entity.Infrastructure.Annotations;
using System.Data.Entity.Migrations;
public partial class AddingGlobalFilter : DbMigration
{
public override void Up()
{
AlterTableAnnotations(
"dbo.Actors",
c => new
{
Id = c.Int(nullable: false, identity: true),
Name = c.String(nullable: false, maxLength: 100),
IsDeleted = c.Boolean(nullable: false),
UpdatedDate = c.DateTime(nullable: false),
AddedDate = c.DateTime(nullable: false),
UpdatedBy = c.String(nullable: false, maxLength: 50),
AddedBy = c.String(nullable: false, maxLength: 50),
},
annotations: new Dictionary<string, AnnotationValues>
{
{
"globalFilter_SoftDelete",
new AnnotationValues(oldValue: "EntityFramework.Filters.FilterDefinition", newValue: null)
},
});
AlterTableAnnotations(
"dbo.Characters",
c => new
{
Id = c.Int(nullable: false, identity: true),
Name = c.String(nullable: false, maxLength: 400),
IsDeleted = c.Boolean(nullable: false),
UpdatedDate = c.DateTime(nullable: false),
AddedDate = c.DateTime(nullable: false),
UpdatedBy = c.String(nullable: false, maxLength: 50),
AddedBy = c.String(nullable: false, maxLength: 50),
Actor_Id = c.Int(nullable: false),
Movie_Id = c.Int(nullable: false),
},
annotations: new Dictionary<string, AnnotationValues>
{
{
"globalFilter_SoftDelete",
new AnnotationValues(oldValue: "EntityFramework.Filters.FilterDefinition", newValue: null)
},
});
AlterTableAnnotations(
"dbo.Movies",
c => new
{
Id = c.Int(nullable: false, identity: true),
Title = c.String(nullable: false, maxLength: 100),
ApiId = c.Int(nullable: false),
ReleaseDate = c.DateTime(nullable: false),
Overview = c.String(),
AverageRating = c.Decimal(precision: 4, scale: 2),
HaveWatched = c.Boolean(nullable: false),
WatchedOn = c.DateTime(),
Review = c.String(),
IsDeleted = c.Boolean(nullable: false),
UpdatedDate = c.DateTime(nullable: false),
AddedDate = c.DateTime(nullable: false),
UpdatedBy = c.String(nullable: false, maxLength: 50),
AddedBy = c.String(nullable: false, maxLength: 50),
Status_Id = c.Int(nullable: false),
},
annotations: new Dictionary<string, AnnotationValues>
{
{
"globalFilter_SoftDelete",
new AnnotationValues(oldValue: "EntityFramework.Filters.FilterDefinition", newValue: null)
},
});
AlterTableAnnotations(
"dbo.MovieGenres",
c => new
{
Id = c.Int(nullable: false, identity: true),
IsDeleted = c.Boolean(nullable: false),
UpdatedDate = c.DateTime(nullable: false),
AddedDate = c.DateTime(nullable: false),
UpdatedBy = c.String(nullable: false, maxLength: 50),
AddedBy = c.String(nullable: false, maxLength: 50),
Genre_Id = c.Int(nullable: false),
Movie_Id = c.Int(nullable: false),
},
annotations: new Dictionary<string, AnnotationValues>
{
{
"globalFilter_SoftDelete",
new AnnotationValues(oldValue: "EntityFramework.Filters.FilterDefinition", newValue: null)
},
});
AlterTableAnnotations(
"dbo.Genres",
c => new
{
Id = c.Int(nullable: false, identity: true),
Name = c.String(nullable: false, maxLength: 50),
IsDeleted = c.Boolean(nullable: false),
UpdatedDate = c.DateTime(nullable: false),
AddedDate = c.DateTime(nullable: false),
UpdatedBy = c.String(nullable: false, maxLength: 50),
AddedBy = c.String(nullable: false, maxLength: 50),
},
annotations: new Dictionary<string, AnnotationValues>
{
{
"globalFilter_SoftDelete",
new AnnotationValues(oldValue: "EntityFramework.Filters.FilterDefinition", newValue: null)
},
});
AlterTableAnnotations(
"dbo.ProductionCompanyMovies",
c => new
{
Id = c.Int(nullable: false, identity: true),
IsDeleted = c.Boolean(nullable: false),
UpdatedDate = c.DateTime(nullable: false),
AddedDate = c.DateTime(nullable: false),
UpdatedBy = c.String(nullable: false, maxLength: 50),
AddedBy = c.String(nullable: false, maxLength: 50),
Movie_Id = c.Int(nullable: false),
ProductionCompany_Id = c.Int(nullable: false),
},
annotations: new Dictionary<string, AnnotationValues>
{
{
"globalFilter_SoftDelete",
new AnnotationValues(oldValue: "EntityFramework.Filters.FilterDefinition", newValue: null)
},
});
AlterTableAnnotations(
"dbo.ProductionCompanies",
c => new
{
Id = c.Int(nullable: false, identity: true),
Name = c.String(nullable: false, maxLength: 100),
IsDeleted = c.Boolean(nullable: false),
UpdatedDate = c.DateTime(nullable: false),
AddedDate = c.DateTime(nullable: false),
UpdatedBy = c.String(nullable: false, maxLength: 50),
AddedBy = c.String(nullable: false, maxLength: 50),
},
annotations: new Dictionary<string, AnnotationValues>
{
{
"globalFilter_SoftDelete",
new AnnotationValues(oldValue: "EntityFramework.Filters.FilterDefinition", newValue: null)
},
});
AlterTableAnnotations(
"dbo.MovieStatus",
c => new
{
Id = c.Int(nullable: false, identity: true),
Status = c.String(nullable: false, maxLength: 50),
IsDeleted = c.Boolean(nullable: false),
UpdatedDate = c.DateTime(nullable: false),
AddedDate = c.DateTime(nullable: false),
UpdatedBy = c.String(nullable: false, maxLength: 50),
AddedBy = c.String(nullable: false, maxLength: 50),
},
annotations: new Dictionary<string, AnnotationValues>
{
{
"globalFilter_SoftDelete",
new AnnotationValues(oldValue: "EntityFramework.Filters.FilterDefinition", newValue: null)
},
});
}
public override void Down()
{
AlterTableAnnotations(
"dbo.MovieStatus",
c => new
{
Id = c.Int(nullable: false, identity: true),
Status = c.String(nullable: false, maxLength: 50),
IsDeleted = c.Boolean(nullable: false),
UpdatedDate = c.DateTime(nullable: false),
AddedDate = c.DateTime(nullable: false),
UpdatedBy = c.String(nullable: false, maxLength: 50),
AddedBy = c.String(nullable: false, maxLength: 50),
},
annotations: new Dictionary<string, AnnotationValues>
{
{
"globalFilter_SoftDelete",
new AnnotationValues(oldValue: null, newValue: "EntityFramework.Filters.FilterDefinition")
},
});
AlterTableAnnotations(
"dbo.ProductionCompanies",
c => new
{
Id = c.Int(nullable: false, identity: true),
Name = c.String(nullable: false, maxLength: 100),
IsDeleted = c.Boolean(nullable: false),
UpdatedDate = c.DateTime(nullable: false),
AddedDate = c.DateTime(nullable: false),
UpdatedBy = c.String(nullable: false, maxLength: 50),
AddedBy = c.String(nullable: false, maxLength: 50),
},
annotations: new Dictionary<string, AnnotationValues>
{
{
"globalFilter_SoftDelete",
new AnnotationValues(oldValue: null, newValue: "EntityFramework.Filters.FilterDefinition")
},
});
AlterTableAnnotations(
"dbo.ProductionCompanyMovies",
c => new
{
Id = c.Int(nullable: false, identity: true),
IsDeleted = c.Boolean(nullable: false),
UpdatedDate = c.DateTime(nullable: false),
AddedDate = c.DateTime(nullable: false),
UpdatedBy = c.String(nullable: false, maxLength: 50),
AddedBy = c.String(nullable: false, maxLength: 50),
Movie_Id = c.Int(nullable: false),
ProductionCompany_Id = c.Int(nullable: false),
},
annotations: new Dictionary<string, AnnotationValues>
{
{
"globalFilter_SoftDelete",
new AnnotationValues(oldValue: null, newValue: "EntityFramework.Filters.FilterDefinition")
},
});
AlterTableAnnotations(
"dbo.Genres",
c => new
{
Id = c.Int(nullable: false, identity: true),
Name = c.String(nullable: false, maxLength: 50),
IsDeleted = c.Boolean(nullable: false),
UpdatedDate = c.DateTime(nullable: false),
AddedDate = c.DateTime(nullable: false),
UpdatedBy = c.String(nullable: false, maxLength: 50),
AddedBy = c.String(nullable: false, maxLength: 50),
},
annotations: new Dictionary<string, AnnotationValues>
{
{
"globalFilter_SoftDelete",
new AnnotationValues(oldValue: null, newValue: "EntityFramework.Filters.FilterDefinition")
},
});
AlterTableAnnotations(
"dbo.MovieGenres",
c => new
{
Id = c.Int(nullable: false, identity: true),
IsDeleted = c.Boolean(nullable: false),
UpdatedDate = c.DateTime(nullable: false),
AddedDate = c.DateTime(nullable: false),
UpdatedBy = c.String(nullable: false, maxLength: 50),
AddedBy = c.String(nullable: false, maxLength: 50),
Genre_Id = c.Int(nullable: false),
Movie_Id = c.Int(nullable: false),
},
annotations: new Dictionary<string, AnnotationValues>
{
{
"globalFilter_SoftDelete",
new AnnotationValues(oldValue: null, newValue: "EntityFramework.Filters.FilterDefinition")
},
});
AlterTableAnnotations(
"dbo.Movies",
c => new
{
Id = c.Int(nullable: false, identity: true),
Title = c.String(nullable: false, maxLength: 100),
ApiId = c.Int(nullable: false),
ReleaseDate = c.DateTime(nullable: false),
Overview = c.String(),
AverageRating = c.Decimal(precision: 4, scale: 2),
HaveWatched = c.Boolean(nullable: false),
WatchedOn = c.DateTime(),
Review = c.String(),
IsDeleted = c.Boolean(nullable: false),
UpdatedDate = c.DateTime(nullable: false),
AddedDate = c.DateTime(nullable: false),
UpdatedBy = c.String(nullable: false, maxLength: 50),
AddedBy = c.String(nullable: false, maxLength: 50),
Status_Id = c.Int(nullable: false),
},
annotations: new Dictionary<string, AnnotationValues>
{
{
"globalFilter_SoftDelete",
new AnnotationValues(oldValue: null, newValue: "EntityFramework.Filters.FilterDefinition")
},
});
AlterTableAnnotations(
"dbo.Characters",
c => new
{
Id = c.Int(nullable: false, identity: true),
Name = c.String(nullable: false, maxLength: 400),
IsDeleted = c.Boolean(nullable: false),
UpdatedDate = c.DateTime(nullable: false),
AddedDate = c.DateTime(nullable: false),
UpdatedBy = c.String(nullable: false, maxLength: 50),
AddedBy = c.String(nullable: false, maxLength: 50),
Actor_Id = c.Int(nullable: false),
Movie_Id = c.Int(nullable: false),
},
annotations: new Dictionary<string, AnnotationValues>
{
{
"globalFilter_SoftDelete",
new AnnotationValues(oldValue: null, newValue: "EntityFramework.Filters.FilterDefinition")
},
});
AlterTableAnnotations(
"dbo.Actors",
c => new
{
Id = c.Int(nullable: false, identity: true),
Name = c.String(nullable: false, maxLength: 100),
IsDeleted = c.Boolean(nullable: false),
UpdatedDate = c.DateTime(nullable: false),
AddedDate = c.DateTime(nullable: false),
UpdatedBy = c.String(nullable: false, maxLength: 50),
AddedBy = c.String(nullable: false, maxLength: 50),
},
annotations: new Dictionary<string, AnnotationValues>
{
{
"globalFilter_SoftDelete",
new AnnotationValues(oldValue: null, newValue: "EntityFramework.Filters.FilterDefinition")
},
});
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Runtime.CompilerServices;
using System.Reflection;
namespace System.Linq.Expressions.Interpreter
{
public partial class LightLambda
{
#if NO_FEATURE_STATIC_DELEGATE
internal const int MaxParameters = 16;
[EnableInvokeTesting]
internal TRet Run0<TRet>()
{
var frame = MakeFrame();
var current = frame.Enter();
try { _interpreter.Run(frame); } finally { frame.Leave(current); }
return (TRet)frame.Pop();
}
[EnableInvokeTesting]
internal void RunVoid0()
{
var frame = MakeFrame();
var current = frame.Enter();
try { _interpreter.Run(frame); } finally { frame.Leave(current); }
}
#if FEATURE_MAKE_RUN_METHODS
internal static Delegate MakeRun0<TRet>(LightLambda lambda)
{
return new Func<TRet>(lambda.Run0<TRet>);
}
internal static Delegate MakeRunVoid0(LightLambda lambda)
{
return new Action(lambda.RunVoid0);
}
#endif
[EnableInvokeTesting]
internal TRet Run1<T0, TRet>(T0 arg0)
{
/*Console.WriteLine("Running method: {0}", arg0);
var dv = new InstructionArray.DebugView(_interpreter.Instructions);
foreach(var view in dv.A0) {
Console.WriteLine("{0} {1} {2}", view.GetValue(), view.GetName(), view.GetDisplayType());
}*/
var frame = MakeFrame();
frame.Data[0] = arg0;
var current = frame.Enter();
try { _interpreter.Run(frame); } finally { frame.Leave(current); }
return (TRet)frame.Pop();
}
[EnableInvokeTesting]
internal void RunVoid1<T0>(T0 arg0)
{
var frame = MakeFrame();
frame.Data[0] = arg0;
var current = frame.Enter();
try { _interpreter.Run(frame); } finally { frame.Leave(current); }
}
#if FEATURE_MAKE_RUN_METHODS
internal static Delegate MakeRun1<T0, TRet>(LightLambda lambda)
{
return new Func<T0, TRet>(lambda.Run1<T0, TRet>);
}
internal static Delegate MakeRunVoid1<T0>(LightLambda lambda)
{
return new Action<T0>(lambda.RunVoid1<T0>);
}
#endif
[EnableInvokeTesting]
internal TRet Run2<T0, T1, TRet>(T0 arg0, T1 arg1)
{
var frame = MakeFrame();
frame.Data[0] = arg0;
frame.Data[1] = arg1;
var current = frame.Enter();
try { _interpreter.Run(frame); } finally { frame.Leave(current); }
return (TRet)frame.Pop();
}
[EnableInvokeTesting]
internal void RunVoid2<T0, T1>(T0 arg0, T1 arg1)
{
var frame = MakeFrame();
frame.Data[0] = arg0;
frame.Data[1] = arg1;
var current = frame.Enter();
try { _interpreter.Run(frame); } finally { frame.Leave(current); }
}
#if FEATURE_MAKE_RUN_METHODS
internal static Delegate MakeRun2<T0, T1, TRet>(LightLambda lambda)
{
return new Func<T0, T1, TRet>(lambda.Run2<T0, T1, TRet>);
}
internal static Delegate MakeRunVoid2<T0, T1>(LightLambda lambda)
{
return new Action<T0, T1>(lambda.RunVoid2<T0, T1>);
}
#endif
[EnableInvokeTesting]
internal TRet Run3<T0, T1, T2, TRet>(T0 arg0, T1 arg1, T2 arg2)
{
var frame = MakeFrame();
frame.Data[0] = arg0;
frame.Data[1] = arg1;
frame.Data[2] = arg2;
var current = frame.Enter();
try { _interpreter.Run(frame); } finally { frame.Leave(current); }
return (TRet)frame.Pop();
}
[EnableInvokeTesting]
internal void RunVoid3<T0, T1, T2>(T0 arg0, T1 arg1, T2 arg2)
{
var frame = MakeFrame();
frame.Data[0] = arg0;
frame.Data[1] = arg1;
frame.Data[2] = arg2;
var current = frame.Enter();
try { _interpreter.Run(frame); } finally { frame.Leave(current); }
}
#if FEATURE_MAKE_RUN_METHODS
internal static Delegate MakeRun3<T0, T1, T2, TRet>(LightLambda lambda)
{
return new Func<T0, T1, T2, TRet>(lambda.Run3<T0, T1, T2, TRet>);
}
internal static Delegate MakeRunVoid3<T0, T1, T2>(LightLambda lambda)
{
return new Action<T0, T1, T2>(lambda.RunVoid3<T0, T1, T2>);
}
#endif
[EnableInvokeTesting]
internal TRet Run4<T0, T1, T2, T3, TRet>(T0 arg0, T1 arg1, T2 arg2, T3 arg3)
{
var frame = MakeFrame();
frame.Data[0] = arg0;
frame.Data[1] = arg1;
frame.Data[2] = arg2;
frame.Data[3] = arg3;
var current = frame.Enter();
try { _interpreter.Run(frame); } finally { frame.Leave(current); }
return (TRet)frame.Pop();
}
[EnableInvokeTesting]
internal void RunVoid4<T0, T1, T2, T3>(T0 arg0, T1 arg1, T2 arg2, T3 arg3)
{
var frame = MakeFrame();
frame.Data[0] = arg0;
frame.Data[1] = arg1;
frame.Data[2] = arg2;
frame.Data[3] = arg3;
var current = frame.Enter();
try { _interpreter.Run(frame); } finally { frame.Leave(current); }
}
#if FEATURE_MAKE_RUN_METHODS
internal static Delegate MakeRun4<T0, T1, T2, T3, TRet>(LightLambda lambda)
{
return new Func<T0, T1, T2, T3, TRet>(lambda.Run4<T0, T1, T2, T3, TRet>);
}
internal static Delegate MakeRunVoid4<T0, T1, T2, T3>(LightLambda lambda)
{
return new Action<T0, T1, T2, T3>(lambda.RunVoid4<T0, T1, T2, T3>);
}
#endif
[EnableInvokeTesting]
internal TRet Run5<T0, T1, T2, T3, T4, TRet>(T0 arg0, T1 arg1, T2 arg2, T3 arg3, T4 arg4)
{
var frame = MakeFrame();
frame.Data[0] = arg0;
frame.Data[1] = arg1;
frame.Data[2] = arg2;
frame.Data[3] = arg3;
frame.Data[4] = arg4;
var current = frame.Enter();
try { _interpreter.Run(frame); } finally { frame.Leave(current); }
return (TRet)frame.Pop();
}
[EnableInvokeTesting]
internal void RunVoid5<T0, T1, T2, T3, T4>(T0 arg0, T1 arg1, T2 arg2, T3 arg3, T4 arg4)
{
var frame = MakeFrame();
frame.Data[0] = arg0;
frame.Data[1] = arg1;
frame.Data[2] = arg2;
frame.Data[3] = arg3;
frame.Data[4] = arg4;
var current = frame.Enter();
try { _interpreter.Run(frame); } finally { frame.Leave(current); }
}
#if FEATURE_MAKE_RUN_METHODS
internal static Delegate MakeRun5<T0, T1, T2, T3, T4, TRet>(LightLambda lambda)
{
return new Func<T0, T1, T2, T3, T4, TRet>(lambda.Run5<T0, T1, T2, T3, T4, TRet>);
}
internal static Delegate MakeRunVoid5<T0, T1, T2, T3, T4>(LightLambda lambda)
{
return new Action<T0, T1, T2, T3, T4>(lambda.RunVoid5<T0, T1, T2, T3, T4>);
}
#endif
[EnableInvokeTesting]
internal TRet Run6<T0, T1, T2, T3, T4, T5, TRet>(T0 arg0, T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5)
{
var frame = MakeFrame();
frame.Data[0] = arg0;
frame.Data[1] = arg1;
frame.Data[2] = arg2;
frame.Data[3] = arg3;
frame.Data[4] = arg4;
frame.Data[5] = arg5;
var current = frame.Enter();
try { _interpreter.Run(frame); } finally { frame.Leave(current); }
return (TRet)frame.Pop();
}
[EnableInvokeTesting]
internal void RunVoid6<T0, T1, T2, T3, T4, T5>(T0 arg0, T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5)
{
var frame = MakeFrame();
frame.Data[0] = arg0;
frame.Data[1] = arg1;
frame.Data[2] = arg2;
frame.Data[3] = arg3;
frame.Data[4] = arg4;
frame.Data[5] = arg5;
var current = frame.Enter();
try { _interpreter.Run(frame); } finally { frame.Leave(current); }
}
#if FEATURE_MAKE_RUN_METHODS
internal static Delegate MakeRun6<T0, T1, T2, T3, T4, T5, TRet>(LightLambda lambda)
{
return new Func<T0, T1, T2, T3, T4, T5, TRet>(lambda.Run6<T0, T1, T2, T3, T4, T5, TRet>);
}
internal static Delegate MakeRunVoid6<T0, T1, T2, T3, T4, T5>(LightLambda lambda)
{
return new Action<T0, T1, T2, T3, T4, T5>(lambda.RunVoid6<T0, T1, T2, T3, T4, T5>);
}
#endif
[EnableInvokeTesting]
internal TRet Run7<T0, T1, T2, T3, T4, T5, T6, TRet>(T0 arg0, T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6)
{
var frame = MakeFrame();
frame.Data[0] = arg0;
frame.Data[1] = arg1;
frame.Data[2] = arg2;
frame.Data[3] = arg3;
frame.Data[4] = arg4;
frame.Data[5] = arg5;
frame.Data[6] = arg6;
var current = frame.Enter();
try { _interpreter.Run(frame); } finally { frame.Leave(current); }
return (TRet)frame.Pop();
}
[EnableInvokeTesting]
internal void RunVoid7<T0, T1, T2, T3, T4, T5, T6>(T0 arg0, T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6)
{
var frame = MakeFrame();
frame.Data[0] = arg0;
frame.Data[1] = arg1;
frame.Data[2] = arg2;
frame.Data[3] = arg3;
frame.Data[4] = arg4;
frame.Data[5] = arg5;
frame.Data[6] = arg6;
var current = frame.Enter();
try { _interpreter.Run(frame); } finally { frame.Leave(current); }
}
#if FEATURE_MAKE_RUN_METHODS
internal static Delegate MakeRun7<T0, T1, T2, T3, T4, T5, T6, TRet>(LightLambda lambda)
{
return new Func<T0, T1, T2, T3, T4, T5, T6, TRet>(lambda.Run7<T0, T1, T2, T3, T4, T5, T6, TRet>);
}
internal static Delegate MakeRunVoid7<T0, T1, T2, T3, T4, T5, T6>(LightLambda lambda)
{
return new Action<T0, T1, T2, T3, T4, T5, T6>(lambda.RunVoid7<T0, T1, T2, T3, T4, T5, T6>);
}
#endif
[EnableInvokeTesting]
internal TRet Run8<T0, T1, T2, T3, T4, T5, T6, T7, TRet>(T0 arg0, T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6, T7 arg7)
{
var frame = MakeFrame();
frame.Data[0] = arg0;
frame.Data[1] = arg1;
frame.Data[2] = arg2;
frame.Data[3] = arg3;
frame.Data[4] = arg4;
frame.Data[5] = arg5;
frame.Data[6] = arg6;
frame.Data[7] = arg7;
var current = frame.Enter();
try { _interpreter.Run(frame); } finally { frame.Leave(current); }
return (TRet)frame.Pop();
}
[EnableInvokeTesting]
internal void RunVoid8<T0, T1, T2, T3, T4, T5, T6, T7>(T0 arg0, T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6, T7 arg7)
{
var frame = MakeFrame();
frame.Data[0] = arg0;
frame.Data[1] = arg1;
frame.Data[2] = arg2;
frame.Data[3] = arg3;
frame.Data[4] = arg4;
frame.Data[5] = arg5;
frame.Data[6] = arg6;
frame.Data[7] = arg7;
var current = frame.Enter();
try { _interpreter.Run(frame); } finally { frame.Leave(current); }
}
#if FEATURE_MAKE_RUN_METHODS
internal static Delegate MakeRun8<T0, T1, T2, T3, T4, T5, T6, T7, TRet>(LightLambda lambda)
{
return new Func<T0, T1, T2, T3, T4, T5, T6, T7, TRet>(lambda.Run8<T0, T1, T2, T3, T4, T5, T6, T7, TRet>);
}
internal static Delegate MakeRunVoid8<T0, T1, T2, T3, T4, T5, T6, T7>(LightLambda lambda)
{
return new Action<T0, T1, T2, T3, T4, T5, T6, T7>(lambda.RunVoid8<T0, T1, T2, T3, T4, T5, T6, T7>);
}
#endif
[EnableInvokeTesting]
internal TRet Run9<T0, T1, T2, T3, T4, T5, T6, T7, T8, TRet>(T0 arg0, T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6, T7 arg7, T8 arg8)
{
var frame = MakeFrame();
frame.Data[0] = arg0;
frame.Data[1] = arg1;
frame.Data[2] = arg2;
frame.Data[3] = arg3;
frame.Data[4] = arg4;
frame.Data[5] = arg5;
frame.Data[6] = arg6;
frame.Data[7] = arg7;
frame.Data[8] = arg8;
var current = frame.Enter();
try { _interpreter.Run(frame); } finally { frame.Leave(current); }
return (TRet)frame.Pop();
}
[EnableInvokeTesting]
internal void RunVoid9<T0, T1, T2, T3, T4, T5, T6, T7, T8>(T0 arg0, T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6, T7 arg7, T8 arg8)
{
var frame = MakeFrame();
frame.Data[0] = arg0;
frame.Data[1] = arg1;
frame.Data[2] = arg2;
frame.Data[3] = arg3;
frame.Data[4] = arg4;
frame.Data[5] = arg5;
frame.Data[6] = arg6;
frame.Data[7] = arg7;
frame.Data[8] = arg8;
var current = frame.Enter();
try { _interpreter.Run(frame); } finally { frame.Leave(current); }
}
#if FEATURE_MAKE_RUN_METHODS
internal static Delegate MakeRun9<T0, T1, T2, T3, T4, T5, T6, T7, T8, TRet>(LightLambda lambda)
{
return new Func<T0, T1, T2, T3, T4, T5, T6, T7, T8, TRet>(lambda.Run9<T0, T1, T2, T3, T4, T5, T6, T7, T8, TRet>);
}
internal static Delegate MakeRunVoid9<T0, T1, T2, T3, T4, T5, T6, T7, T8>(LightLambda lambda)
{
return new Action<T0, T1, T2, T3, T4, T5, T6, T7, T8>(lambda.RunVoid9<T0, T1, T2, T3, T4, T5, T6, T7, T8>);
}
#endif
[EnableInvokeTesting]
internal TRet Run10<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, TRet>(T0 arg0, T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6, T7 arg7, T8 arg8, T9 arg9)
{
var frame = MakeFrame();
frame.Data[0] = arg0;
frame.Data[1] = arg1;
frame.Data[2] = arg2;
frame.Data[3] = arg3;
frame.Data[4] = arg4;
frame.Data[5] = arg5;
frame.Data[6] = arg6;
frame.Data[7] = arg7;
frame.Data[8] = arg8;
frame.Data[9] = arg9;
var current = frame.Enter();
try { _interpreter.Run(frame); } finally { frame.Leave(current); }
return (TRet)frame.Pop();
}
[EnableInvokeTesting]
internal void RunVoid10<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9>(T0 arg0, T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6, T7 arg7, T8 arg8, T9 arg9)
{
var frame = MakeFrame();
frame.Data[0] = arg0;
frame.Data[1] = arg1;
frame.Data[2] = arg2;
frame.Data[3] = arg3;
frame.Data[4] = arg4;
frame.Data[5] = arg5;
frame.Data[6] = arg6;
frame.Data[7] = arg7;
frame.Data[8] = arg8;
frame.Data[9] = arg9;
var current = frame.Enter();
try { _interpreter.Run(frame); } finally { frame.Leave(current); }
}
#if FEATURE_MAKE_RUN_METHODS
internal static Delegate MakeRun10<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, TRet>(LightLambda lambda)
{
return new Func<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, TRet>(lambda.Run10<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, TRet>);
}
internal static Delegate MakeRunVoid10<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9>(LightLambda lambda)
{
return new Action<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9>(lambda.RunVoid10<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9>);
}
#endif
[EnableInvokeTesting]
internal TRet Run11<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, TRet>(T0 arg0, T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6, T7 arg7, T8 arg8, T9 arg9, T10 arg10)
{
var frame = MakeFrame();
frame.Data[0] = arg0;
frame.Data[1] = arg1;
frame.Data[2] = arg2;
frame.Data[3] = arg3;
frame.Data[4] = arg4;
frame.Data[5] = arg5;
frame.Data[6] = arg6;
frame.Data[7] = arg7;
frame.Data[8] = arg8;
frame.Data[9] = arg9;
frame.Data[10] = arg10;
var current = frame.Enter();
try { _interpreter.Run(frame); } finally { frame.Leave(current); }
return (TRet)frame.Pop();
}
[EnableInvokeTesting]
internal void RunVoid11<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10>(T0 arg0, T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6, T7 arg7, T8 arg8, T9 arg9, T10 arg10)
{
var frame = MakeFrame();
frame.Data[0] = arg0;
frame.Data[1] = arg1;
frame.Data[2] = arg2;
frame.Data[3] = arg3;
frame.Data[4] = arg4;
frame.Data[5] = arg5;
frame.Data[6] = arg6;
frame.Data[7] = arg7;
frame.Data[8] = arg8;
frame.Data[9] = arg9;
frame.Data[10] = arg10;
var current = frame.Enter();
try { _interpreter.Run(frame); } finally { frame.Leave(current); }
}
#if FEATURE_MAKE_RUN_METHODS
internal static Delegate MakeRun11<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, TRet>(LightLambda lambda)
{
return new Func<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, TRet>(lambda.Run11<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, TRet>);
}
internal static Delegate MakeRunVoid11<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10>(LightLambda lambda)
{
return new Action<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10>(lambda.RunVoid11<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10>);
}
#endif
[EnableInvokeTesting]
internal TRet Run12<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, TRet>(T0 arg0, T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6, T7 arg7, T8 arg8, T9 arg9, T10 arg10, T11 arg11)
{
var frame = MakeFrame();
frame.Data[0] = arg0;
frame.Data[1] = arg1;
frame.Data[2] = arg2;
frame.Data[3] = arg3;
frame.Data[4] = arg4;
frame.Data[5] = arg5;
frame.Data[6] = arg6;
frame.Data[7] = arg7;
frame.Data[8] = arg8;
frame.Data[9] = arg9;
frame.Data[10] = arg10;
frame.Data[11] = arg11;
var current = frame.Enter();
try { _interpreter.Run(frame); } finally { frame.Leave(current); }
return (TRet)frame.Pop();
}
[EnableInvokeTesting]
internal void RunVoid12<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11>(T0 arg0, T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6, T7 arg7, T8 arg8, T9 arg9, T10 arg10, T11 arg11)
{
var frame = MakeFrame();
frame.Data[0] = arg0;
frame.Data[1] = arg1;
frame.Data[2] = arg2;
frame.Data[3] = arg3;
frame.Data[4] = arg4;
frame.Data[5] = arg5;
frame.Data[6] = arg6;
frame.Data[7] = arg7;
frame.Data[8] = arg8;
frame.Data[9] = arg9;
frame.Data[10] = arg10;
frame.Data[11] = arg11;
var current = frame.Enter();
try { _interpreter.Run(frame); } finally { frame.Leave(current); }
}
#if FEATURE_MAKE_RUN_METHODS
internal static Delegate MakeRun12<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, TRet>(LightLambda lambda)
{
return new Func<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, TRet>(lambda.Run12<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, TRet>);
}
internal static Delegate MakeRunVoid12<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11>(LightLambda lambda)
{
return new Action<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11>(lambda.RunVoid12<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11>);
}
#endif
[EnableInvokeTesting]
internal TRet Run13<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, TRet>(T0 arg0, T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6, T7 arg7, T8 arg8, T9 arg9, T10 arg10, T11 arg11, T12 arg12)
{
var frame = MakeFrame();
frame.Data[0] = arg0;
frame.Data[1] = arg1;
frame.Data[2] = arg2;
frame.Data[3] = arg3;
frame.Data[4] = arg4;
frame.Data[5] = arg5;
frame.Data[6] = arg6;
frame.Data[7] = arg7;
frame.Data[8] = arg8;
frame.Data[9] = arg9;
frame.Data[10] = arg10;
frame.Data[11] = arg11;
frame.Data[12] = arg12;
var current = frame.Enter();
try { _interpreter.Run(frame); } finally { frame.Leave(current); }
return (TRet)frame.Pop();
}
[EnableInvokeTesting]
internal void RunVoid13<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12>(T0 arg0, T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6, T7 arg7, T8 arg8, T9 arg9, T10 arg10, T11 arg11, T12 arg12)
{
var frame = MakeFrame();
frame.Data[0] = arg0;
frame.Data[1] = arg1;
frame.Data[2] = arg2;
frame.Data[3] = arg3;
frame.Data[4] = arg4;
frame.Data[5] = arg5;
frame.Data[6] = arg6;
frame.Data[7] = arg7;
frame.Data[8] = arg8;
frame.Data[9] = arg9;
frame.Data[10] = arg10;
frame.Data[11] = arg11;
frame.Data[12] = arg12;
var current = frame.Enter();
try { _interpreter.Run(frame); } finally { frame.Leave(current); }
}
#if FEATURE_MAKE_RUN_METHODS
internal static Delegate MakeRun13<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, TRet>(LightLambda lambda)
{
return new Func<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, TRet>(lambda.Run13<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, TRet>);
}
internal static Delegate MakeRunVoid13<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12>(LightLambda lambda)
{
return new Action<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12>(lambda.RunVoid13<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12>);
}
#endif
[EnableInvokeTesting]
internal TRet Run14<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, TRet>(T0 arg0, T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6, T7 arg7, T8 arg8, T9 arg9, T10 arg10, T11 arg11, T12 arg12, T13 arg13)
{
var frame = MakeFrame();
frame.Data[0] = arg0;
frame.Data[1] = arg1;
frame.Data[2] = arg2;
frame.Data[3] = arg3;
frame.Data[4] = arg4;
frame.Data[5] = arg5;
frame.Data[6] = arg6;
frame.Data[7] = arg7;
frame.Data[8] = arg8;
frame.Data[9] = arg9;
frame.Data[10] = arg10;
frame.Data[11] = arg11;
frame.Data[12] = arg12;
frame.Data[13] = arg13;
var current = frame.Enter();
try { _interpreter.Run(frame); } finally { frame.Leave(current); }
return (TRet)frame.Pop();
}
[EnableInvokeTesting]
internal void RunVoid14<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13>(T0 arg0, T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6, T7 arg7, T8 arg8, T9 arg9, T10 arg10, T11 arg11, T12 arg12, T13 arg13)
{
var frame = MakeFrame();
frame.Data[0] = arg0;
frame.Data[1] = arg1;
frame.Data[2] = arg2;
frame.Data[3] = arg3;
frame.Data[4] = arg4;
frame.Data[5] = arg5;
frame.Data[6] = arg6;
frame.Data[7] = arg7;
frame.Data[8] = arg8;
frame.Data[9] = arg9;
frame.Data[10] = arg10;
frame.Data[11] = arg11;
frame.Data[12] = arg12;
frame.Data[13] = arg13;
var current = frame.Enter();
try { _interpreter.Run(frame); } finally { frame.Leave(current); }
}
#if FEATURE_MAKE_RUN_METHODS
internal static Delegate MakeRun14<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, TRet>(LightLambda lambda)
{
return new Func<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, TRet>(lambda.Run14<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, TRet>);
}
internal static Delegate MakeRunVoid14<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13>(LightLambda lambda)
{
return new Action<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13>(lambda.RunVoid14<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13>);
}
#endif
[EnableInvokeTesting]
internal TRet Run15<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, TRet>(T0 arg0, T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6, T7 arg7, T8 arg8, T9 arg9, T10 arg10, T11 arg11, T12 arg12, T13 arg13, T14 arg14)
{
var frame = MakeFrame();
frame.Data[0] = arg0;
frame.Data[1] = arg1;
frame.Data[2] = arg2;
frame.Data[3] = arg3;
frame.Data[4] = arg4;
frame.Data[5] = arg5;
frame.Data[6] = arg6;
frame.Data[7] = arg7;
frame.Data[8] = arg8;
frame.Data[9] = arg9;
frame.Data[10] = arg10;
frame.Data[11] = arg11;
frame.Data[12] = arg12;
frame.Data[13] = arg13;
frame.Data[14] = arg14;
var current = frame.Enter();
try { _interpreter.Run(frame); } finally { frame.Leave(current); }
return (TRet)frame.Pop();
}
[EnableInvokeTesting]
internal void RunVoid15<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14>(T0 arg0, T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6, T7 arg7, T8 arg8, T9 arg9, T10 arg10, T11 arg11, T12 arg12, T13 arg13, T14 arg14)
{
var frame = MakeFrame();
frame.Data[0] = arg0;
frame.Data[1] = arg1;
frame.Data[2] = arg2;
frame.Data[3] = arg3;
frame.Data[4] = arg4;
frame.Data[5] = arg5;
frame.Data[6] = arg6;
frame.Data[7] = arg7;
frame.Data[8] = arg8;
frame.Data[9] = arg9;
frame.Data[10] = arg10;
frame.Data[11] = arg11;
frame.Data[12] = arg12;
frame.Data[13] = arg13;
frame.Data[14] = arg14;
var current = frame.Enter();
try { _interpreter.Run(frame); } finally { frame.Leave(current); }
}
#if FEATURE_MAKE_RUN_METHODS
internal static Delegate MakeRun15<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, TRet>(LightLambda lambda)
{
return new Func<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, TRet>(lambda.Run15<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, TRet>);
}
internal static Delegate MakeRunVoid15<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14>(LightLambda lambda)
{
return new Action<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14>(lambda.RunVoid15<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14>);
}
#endif
#endif
}
}
| |
// Copyright 2022 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
using gax = Google.Api.Gax;
using gcdcv = Google.Cloud.Dialogflow.Cx.V3;
using sys = System;
namespace Google.Cloud.Dialogflow.Cx.V3
{
/// <summary>Resource name for the <c>TestCase</c> resource.</summary>
public sealed partial class TestCaseName : gax::IResourceName, sys::IEquatable<TestCaseName>
{
/// <summary>The possible contents of <see cref="TestCaseName"/>.</summary>
public enum ResourceNameType
{
/// <summary>An unparsed resource name.</summary>
Unparsed = 0,
/// <summary>
/// A resource name with pattern
/// <c>projects/{project}/locations/{location}/agents/{agent}/testCases/{test_case}</c>.
/// </summary>
ProjectLocationAgentTestCase = 1,
}
private static gax::PathTemplate s_projectLocationAgentTestCase = new gax::PathTemplate("projects/{project}/locations/{location}/agents/{agent}/testCases/{test_case}");
/// <summary>Creates a <see cref="TestCaseName"/> containing an unparsed resource name.</summary>
/// <param name="unparsedResourceName">The unparsed resource name. Must not be <c>null</c>.</param>
/// <returns>
/// A new instance of <see cref="TestCaseName"/> containing the provided <paramref name="unparsedResourceName"/>
/// .
/// </returns>
public static TestCaseName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) =>
new TestCaseName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName)));
/// <summary>
/// Creates a <see cref="TestCaseName"/> with the pattern
/// <c>projects/{project}/locations/{location}/agents/{agent}/testCases/{test_case}</c>.
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="agentId">The <c>Agent</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="testCaseId">The <c>TestCase</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>A new instance of <see cref="TestCaseName"/> constructed from the provided ids.</returns>
public static TestCaseName FromProjectLocationAgentTestCase(string projectId, string locationId, string agentId, string testCaseId) =>
new TestCaseName(ResourceNameType.ProjectLocationAgentTestCase, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), locationId: gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), agentId: gax::GaxPreconditions.CheckNotNullOrEmpty(agentId, nameof(agentId)), testCaseId: gax::GaxPreconditions.CheckNotNullOrEmpty(testCaseId, nameof(testCaseId)));
/// <summary>
/// Formats the IDs into the string representation of this <see cref="TestCaseName"/> with pattern
/// <c>projects/{project}/locations/{location}/agents/{agent}/testCases/{test_case}</c>.
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="agentId">The <c>Agent</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="testCaseId">The <c>TestCase</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="TestCaseName"/> with pattern
/// <c>projects/{project}/locations/{location}/agents/{agent}/testCases/{test_case}</c>.
/// </returns>
public static string Format(string projectId, string locationId, string agentId, string testCaseId) =>
FormatProjectLocationAgentTestCase(projectId, locationId, agentId, testCaseId);
/// <summary>
/// Formats the IDs into the string representation of this <see cref="TestCaseName"/> with pattern
/// <c>projects/{project}/locations/{location}/agents/{agent}/testCases/{test_case}</c>.
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="agentId">The <c>Agent</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="testCaseId">The <c>TestCase</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="TestCaseName"/> with pattern
/// <c>projects/{project}/locations/{location}/agents/{agent}/testCases/{test_case}</c>.
/// </returns>
public static string FormatProjectLocationAgentTestCase(string projectId, string locationId, string agentId, string testCaseId) =>
s_projectLocationAgentTestCase.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), gax::GaxPreconditions.CheckNotNullOrEmpty(agentId, nameof(agentId)), gax::GaxPreconditions.CheckNotNullOrEmpty(testCaseId, nameof(testCaseId)));
/// <summary>Parses the given resource name string into a new <see cref="TestCaseName"/> instance.</summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item>
/// <description>
/// <c>projects/{project}/locations/{location}/agents/{agent}/testCases/{test_case}</c>
/// </description>
/// </item>
/// </list>
/// </remarks>
/// <param name="testCaseName">The resource name in string form. Must not be <c>null</c>.</param>
/// <returns>The parsed <see cref="TestCaseName"/> if successful.</returns>
public static TestCaseName Parse(string testCaseName) => Parse(testCaseName, false);
/// <summary>
/// Parses the given resource name string into a new <see cref="TestCaseName"/> instance; optionally allowing an
/// unparseable resource name.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item>
/// <description>
/// <c>projects/{project}/locations/{location}/agents/{agent}/testCases/{test_case}</c>
/// </description>
/// </item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="testCaseName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="allowUnparsed">
/// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/>
/// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is
/// specified.
/// </param>
/// <returns>The parsed <see cref="TestCaseName"/> if successful.</returns>
public static TestCaseName Parse(string testCaseName, bool allowUnparsed) =>
TryParse(testCaseName, allowUnparsed, out TestCaseName result) ? result : throw new sys::ArgumentException("The given resource-name matches no pattern.");
/// <summary>
/// Tries to parse the given resource name string into a new <see cref="TestCaseName"/> instance.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item>
/// <description>
/// <c>projects/{project}/locations/{location}/agents/{agent}/testCases/{test_case}</c>
/// </description>
/// </item>
/// </list>
/// </remarks>
/// <param name="testCaseName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="result">
/// When this method returns, the parsed <see cref="TestCaseName"/>, or <c>null</c> if parsing failed.
/// </param>
/// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns>
public static bool TryParse(string testCaseName, out TestCaseName result) => TryParse(testCaseName, false, out result);
/// <summary>
/// Tries to parse the given resource name string into a new <see cref="TestCaseName"/> instance; optionally
/// allowing an unparseable resource name.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item>
/// <description>
/// <c>projects/{project}/locations/{location}/agents/{agent}/testCases/{test_case}</c>
/// </description>
/// </item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="testCaseName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="allowUnparsed">
/// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/>
/// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is
/// specified.
/// </param>
/// <param name="result">
/// When this method returns, the parsed <see cref="TestCaseName"/>, or <c>null</c> if parsing failed.
/// </param>
/// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns>
public static bool TryParse(string testCaseName, bool allowUnparsed, out TestCaseName result)
{
gax::GaxPreconditions.CheckNotNull(testCaseName, nameof(testCaseName));
gax::TemplatedResourceName resourceName;
if (s_projectLocationAgentTestCase.TryParseName(testCaseName, out resourceName))
{
result = FromProjectLocationAgentTestCase(resourceName[0], resourceName[1], resourceName[2], resourceName[3]);
return true;
}
if (allowUnparsed)
{
if (gax::UnparsedResourceName.TryParse(testCaseName, out gax::UnparsedResourceName unparsedResourceName))
{
result = FromUnparsed(unparsedResourceName);
return true;
}
}
result = null;
return false;
}
private TestCaseName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string agentId = null, string locationId = null, string projectId = null, string testCaseId = null)
{
Type = type;
UnparsedResource = unparsedResourceName;
AgentId = agentId;
LocationId = locationId;
ProjectId = projectId;
TestCaseId = testCaseId;
}
/// <summary>
/// Constructs a new instance of a <see cref="TestCaseName"/> class from the component parts of pattern
/// <c>projects/{project}/locations/{location}/agents/{agent}/testCases/{test_case}</c>
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="agentId">The <c>Agent</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="testCaseId">The <c>TestCase</c> ID. Must not be <c>null</c> or empty.</param>
public TestCaseName(string projectId, string locationId, string agentId, string testCaseId) : this(ResourceNameType.ProjectLocationAgentTestCase, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), locationId: gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), agentId: gax::GaxPreconditions.CheckNotNullOrEmpty(agentId, nameof(agentId)), testCaseId: gax::GaxPreconditions.CheckNotNullOrEmpty(testCaseId, nameof(testCaseId)))
{
}
/// <summary>The <see cref="ResourceNameType"/> of the contained resource name.</summary>
public ResourceNameType Type { get; }
/// <summary>
/// The contained <see cref="gax::UnparsedResourceName"/>. Only non-<c>null</c> if this instance contains an
/// unparsed resource name.
/// </summary>
public gax::UnparsedResourceName UnparsedResource { get; }
/// <summary>
/// The <c>Agent</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string AgentId { get; }
/// <summary>
/// The <c>Location</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string LocationId { get; }
/// <summary>
/// The <c>Project</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string ProjectId { get; }
/// <summary>
/// The <c>TestCase</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string TestCaseId { get; }
/// <summary>Whether this instance contains a resource name with a known pattern.</summary>
public bool IsKnownPattern => Type != ResourceNameType.Unparsed;
/// <summary>The string representation of the resource name.</summary>
/// <returns>The string representation of the resource name.</returns>
public override string ToString()
{
switch (Type)
{
case ResourceNameType.Unparsed: return UnparsedResource.ToString();
case ResourceNameType.ProjectLocationAgentTestCase: return s_projectLocationAgentTestCase.Expand(ProjectId, LocationId, AgentId, TestCaseId);
default: throw new sys::InvalidOperationException("Unrecognized resource-type.");
}
}
/// <summary>Returns a hash code for this resource name.</summary>
public override int GetHashCode() => ToString().GetHashCode();
/// <inheritdoc/>
public override bool Equals(object obj) => Equals(obj as TestCaseName);
/// <inheritdoc/>
public bool Equals(TestCaseName other) => ToString() == other?.ToString();
/// <inheritdoc/>
public static bool operator ==(TestCaseName a, TestCaseName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false);
/// <inheritdoc/>
public static bool operator !=(TestCaseName a, TestCaseName b) => !(a == b);
}
/// <summary>Resource name for the <c>TestCaseResult</c> resource.</summary>
public sealed partial class TestCaseResultName : gax::IResourceName, sys::IEquatable<TestCaseResultName>
{
/// <summary>The possible contents of <see cref="TestCaseResultName"/>.</summary>
public enum ResourceNameType
{
/// <summary>An unparsed resource name.</summary>
Unparsed = 0,
/// <summary>
/// A resource name with pattern
/// <c>projects/{project}/locations/{location}/agents/{agent}/testCases/{test_case}/results/{result}</c>.
/// </summary>
ProjectLocationAgentTestCaseResult = 1,
}
private static gax::PathTemplate s_projectLocationAgentTestCaseResult = new gax::PathTemplate("projects/{project}/locations/{location}/agents/{agent}/testCases/{test_case}/results/{result}");
/// <summary>Creates a <see cref="TestCaseResultName"/> containing an unparsed resource name.</summary>
/// <param name="unparsedResourceName">The unparsed resource name. Must not be <c>null</c>.</param>
/// <returns>
/// A new instance of <see cref="TestCaseResultName"/> containing the provided
/// <paramref name="unparsedResourceName"/>.
/// </returns>
public static TestCaseResultName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) =>
new TestCaseResultName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName)));
/// <summary>
/// Creates a <see cref="TestCaseResultName"/> with the pattern
/// <c>projects/{project}/locations/{location}/agents/{agent}/testCases/{test_case}/results/{result}</c>.
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="agentId">The <c>Agent</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="testCaseId">The <c>TestCase</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="resultId">The <c>Result</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>A new instance of <see cref="TestCaseResultName"/> constructed from the provided ids.</returns>
public static TestCaseResultName FromProjectLocationAgentTestCaseResult(string projectId, string locationId, string agentId, string testCaseId, string resultId) =>
new TestCaseResultName(ResourceNameType.ProjectLocationAgentTestCaseResult, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), locationId: gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), agentId: gax::GaxPreconditions.CheckNotNullOrEmpty(agentId, nameof(agentId)), testCaseId: gax::GaxPreconditions.CheckNotNullOrEmpty(testCaseId, nameof(testCaseId)), resultId: gax::GaxPreconditions.CheckNotNullOrEmpty(resultId, nameof(resultId)));
/// <summary>
/// Formats the IDs into the string representation of this <see cref="TestCaseResultName"/> with pattern
/// <c>projects/{project}/locations/{location}/agents/{agent}/testCases/{test_case}/results/{result}</c>.
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="agentId">The <c>Agent</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="testCaseId">The <c>TestCase</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="resultId">The <c>Result</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="TestCaseResultName"/> with pattern
/// <c>projects/{project}/locations/{location}/agents/{agent}/testCases/{test_case}/results/{result}</c>.
/// </returns>
public static string Format(string projectId, string locationId, string agentId, string testCaseId, string resultId) =>
FormatProjectLocationAgentTestCaseResult(projectId, locationId, agentId, testCaseId, resultId);
/// <summary>
/// Formats the IDs into the string representation of this <see cref="TestCaseResultName"/> with pattern
/// <c>projects/{project}/locations/{location}/agents/{agent}/testCases/{test_case}/results/{result}</c>.
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="agentId">The <c>Agent</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="testCaseId">The <c>TestCase</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="resultId">The <c>Result</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="TestCaseResultName"/> with pattern
/// <c>projects/{project}/locations/{location}/agents/{agent}/testCases/{test_case}/results/{result}</c>.
/// </returns>
public static string FormatProjectLocationAgentTestCaseResult(string projectId, string locationId, string agentId, string testCaseId, string resultId) =>
s_projectLocationAgentTestCaseResult.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), gax::GaxPreconditions.CheckNotNullOrEmpty(agentId, nameof(agentId)), gax::GaxPreconditions.CheckNotNullOrEmpty(testCaseId, nameof(testCaseId)), gax::GaxPreconditions.CheckNotNullOrEmpty(resultId, nameof(resultId)));
/// <summary>
/// Parses the given resource name string into a new <see cref="TestCaseResultName"/> instance.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item>
/// <description>
/// <c>projects/{project}/locations/{location}/agents/{agent}/testCases/{test_case}/results/{result}</c>
/// </description>
/// </item>
/// </list>
/// </remarks>
/// <param name="testCaseResultName">The resource name in string form. Must not be <c>null</c>.</param>
/// <returns>The parsed <see cref="TestCaseResultName"/> if successful.</returns>
public static TestCaseResultName Parse(string testCaseResultName) => Parse(testCaseResultName, false);
/// <summary>
/// Parses the given resource name string into a new <see cref="TestCaseResultName"/> instance; optionally
/// allowing an unparseable resource name.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item>
/// <description>
/// <c>projects/{project}/locations/{location}/agents/{agent}/testCases/{test_case}/results/{result}</c>
/// </description>
/// </item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="testCaseResultName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="allowUnparsed">
/// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/>
/// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is
/// specified.
/// </param>
/// <returns>The parsed <see cref="TestCaseResultName"/> if successful.</returns>
public static TestCaseResultName Parse(string testCaseResultName, bool allowUnparsed) =>
TryParse(testCaseResultName, allowUnparsed, out TestCaseResultName result) ? result : throw new sys::ArgumentException("The given resource-name matches no pattern.");
/// <summary>
/// Tries to parse the given resource name string into a new <see cref="TestCaseResultName"/> instance.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item>
/// <description>
/// <c>projects/{project}/locations/{location}/agents/{agent}/testCases/{test_case}/results/{result}</c>
/// </description>
/// </item>
/// </list>
/// </remarks>
/// <param name="testCaseResultName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="result">
/// When this method returns, the parsed <see cref="TestCaseResultName"/>, or <c>null</c> if parsing failed.
/// </param>
/// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns>
public static bool TryParse(string testCaseResultName, out TestCaseResultName result) =>
TryParse(testCaseResultName, false, out result);
/// <summary>
/// Tries to parse the given resource name string into a new <see cref="TestCaseResultName"/> instance;
/// optionally allowing an unparseable resource name.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item>
/// <description>
/// <c>projects/{project}/locations/{location}/agents/{agent}/testCases/{test_case}/results/{result}</c>
/// </description>
/// </item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="testCaseResultName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="allowUnparsed">
/// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/>
/// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is
/// specified.
/// </param>
/// <param name="result">
/// When this method returns, the parsed <see cref="TestCaseResultName"/>, or <c>null</c> if parsing failed.
/// </param>
/// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns>
public static bool TryParse(string testCaseResultName, bool allowUnparsed, out TestCaseResultName result)
{
gax::GaxPreconditions.CheckNotNull(testCaseResultName, nameof(testCaseResultName));
gax::TemplatedResourceName resourceName;
if (s_projectLocationAgentTestCaseResult.TryParseName(testCaseResultName, out resourceName))
{
result = FromProjectLocationAgentTestCaseResult(resourceName[0], resourceName[1], resourceName[2], resourceName[3], resourceName[4]);
return true;
}
if (allowUnparsed)
{
if (gax::UnparsedResourceName.TryParse(testCaseResultName, out gax::UnparsedResourceName unparsedResourceName))
{
result = FromUnparsed(unparsedResourceName);
return true;
}
}
result = null;
return false;
}
private TestCaseResultName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string agentId = null, string locationId = null, string projectId = null, string resultId = null, string testCaseId = null)
{
Type = type;
UnparsedResource = unparsedResourceName;
AgentId = agentId;
LocationId = locationId;
ProjectId = projectId;
ResultId = resultId;
TestCaseId = testCaseId;
}
/// <summary>
/// Constructs a new instance of a <see cref="TestCaseResultName"/> class from the component parts of pattern
/// <c>projects/{project}/locations/{location}/agents/{agent}/testCases/{test_case}/results/{result}</c>
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="agentId">The <c>Agent</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="testCaseId">The <c>TestCase</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="resultId">The <c>Result</c> ID. Must not be <c>null</c> or empty.</param>
public TestCaseResultName(string projectId, string locationId, string agentId, string testCaseId, string resultId) : this(ResourceNameType.ProjectLocationAgentTestCaseResult, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), locationId: gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), agentId: gax::GaxPreconditions.CheckNotNullOrEmpty(agentId, nameof(agentId)), testCaseId: gax::GaxPreconditions.CheckNotNullOrEmpty(testCaseId, nameof(testCaseId)), resultId: gax::GaxPreconditions.CheckNotNullOrEmpty(resultId, nameof(resultId)))
{
}
/// <summary>The <see cref="ResourceNameType"/> of the contained resource name.</summary>
public ResourceNameType Type { get; }
/// <summary>
/// The contained <see cref="gax::UnparsedResourceName"/>. Only non-<c>null</c> if this instance contains an
/// unparsed resource name.
/// </summary>
public gax::UnparsedResourceName UnparsedResource { get; }
/// <summary>
/// The <c>Agent</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string AgentId { get; }
/// <summary>
/// The <c>Location</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string LocationId { get; }
/// <summary>
/// The <c>Project</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string ProjectId { get; }
/// <summary>
/// The <c>Result</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string ResultId { get; }
/// <summary>
/// The <c>TestCase</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string TestCaseId { get; }
/// <summary>Whether this instance contains a resource name with a known pattern.</summary>
public bool IsKnownPattern => Type != ResourceNameType.Unparsed;
/// <summary>The string representation of the resource name.</summary>
/// <returns>The string representation of the resource name.</returns>
public override string ToString()
{
switch (Type)
{
case ResourceNameType.Unparsed: return UnparsedResource.ToString();
case ResourceNameType.ProjectLocationAgentTestCaseResult: return s_projectLocationAgentTestCaseResult.Expand(ProjectId, LocationId, AgentId, TestCaseId, ResultId);
default: throw new sys::InvalidOperationException("Unrecognized resource-type.");
}
}
/// <summary>Returns a hash code for this resource name.</summary>
public override int GetHashCode() => ToString().GetHashCode();
/// <inheritdoc/>
public override bool Equals(object obj) => Equals(obj as TestCaseResultName);
/// <inheritdoc/>
public bool Equals(TestCaseResultName other) => ToString() == other?.ToString();
/// <inheritdoc/>
public static bool operator ==(TestCaseResultName a, TestCaseResultName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false);
/// <inheritdoc/>
public static bool operator !=(TestCaseResultName a, TestCaseResultName b) => !(a == b);
}
public partial class TestCase
{
/// <summary>
/// <see cref="gcdcv::TestCaseName"/>-typed view over the <see cref="Name"/> resource name property.
/// </summary>
public gcdcv::TestCaseName TestCaseName
{
get => string.IsNullOrEmpty(Name) ? null : gcdcv::TestCaseName.Parse(Name, allowUnparsed: true);
set => Name = value?.ToString() ?? "";
}
}
public partial class TestCaseResult
{
/// <summary>
/// <see cref="gcdcv::TestCaseResultName"/>-typed view over the <see cref="Name"/> resource name property.
/// </summary>
public gcdcv::TestCaseResultName TestCaseResultName
{
get => string.IsNullOrEmpty(Name) ? null : gcdcv::TestCaseResultName.Parse(Name, allowUnparsed: true);
set => Name = value?.ToString() ?? "";
}
/// <summary>
/// <see cref="EnvironmentName"/>-typed view over the <see cref="Environment"/> resource name property.
/// </summary>
public EnvironmentName EnvironmentAsEnvironmentName
{
get => string.IsNullOrEmpty(Environment) ? null : EnvironmentName.Parse(Environment, allowUnparsed: true);
set => Environment = value?.ToString() ?? "";
}
}
public partial class TestConfig
{
/// <summary><see cref="FlowName"/>-typed view over the <see cref="Flow"/> resource name property.</summary>
public FlowName FlowAsFlowName
{
get => string.IsNullOrEmpty(Flow) ? null : FlowName.Parse(Flow, allowUnparsed: true);
set => Flow = value?.ToString() ?? "";
}
/// <summary><see cref="PageName"/>-typed view over the <see cref="Page"/> resource name property.</summary>
public PageName PageAsPageName
{
get => string.IsNullOrEmpty(Page) ? null : PageName.Parse(Page, allowUnparsed: true);
set => Page = value?.ToString() ?? "";
}
}
public partial class CalculateCoverageRequest
{
/// <summary><see cref="AgentName"/>-typed view over the <see cref="Agent"/> resource name property.</summary>
public AgentName AgentAsAgentName
{
get => string.IsNullOrEmpty(Agent) ? null : AgentName.Parse(Agent, allowUnparsed: true);
set => Agent = value?.ToString() ?? "";
}
}
public partial class CalculateCoverageResponse
{
/// <summary><see cref="AgentName"/>-typed view over the <see cref="Agent"/> resource name property.</summary>
public AgentName AgentAsAgentName
{
get => string.IsNullOrEmpty(Agent) ? null : AgentName.Parse(Agent, allowUnparsed: true);
set => Agent = value?.ToString() ?? "";
}
}
public partial class ListTestCasesRequest
{
/// <summary><see cref="AgentName"/>-typed view over the <see cref="Parent"/> resource name property.</summary>
public AgentName ParentAsAgentName
{
get => string.IsNullOrEmpty(Parent) ? null : AgentName.Parse(Parent, allowUnparsed: true);
set => Parent = value?.ToString() ?? "";
}
}
public partial class BatchDeleteTestCasesRequest
{
/// <summary><see cref="AgentName"/>-typed view over the <see cref="Parent"/> resource name property.</summary>
public AgentName ParentAsAgentName
{
get => string.IsNullOrEmpty(Parent) ? null : AgentName.Parse(Parent, allowUnparsed: true);
set => Parent = value?.ToString() ?? "";
}
/// <summary>
/// <see cref="TestCaseName"/>-typed view over the <see cref="Names"/> resource name property.
/// </summary>
public gax::ResourceNameList<TestCaseName> TestCaseNames
{
get => new gax::ResourceNameList<TestCaseName>(Names, s => string.IsNullOrEmpty(s) ? null : TestCaseName.Parse(s, allowUnparsed: true));
}
}
public partial class CreateTestCaseRequest
{
/// <summary><see cref="AgentName"/>-typed view over the <see cref="Parent"/> resource name property.</summary>
public AgentName ParentAsAgentName
{
get => string.IsNullOrEmpty(Parent) ? null : AgentName.Parse(Parent, allowUnparsed: true);
set => Parent = value?.ToString() ?? "";
}
}
public partial class GetTestCaseRequest
{
/// <summary>
/// <see cref="gcdcv::TestCaseName"/>-typed view over the <see cref="Name"/> resource name property.
/// </summary>
public gcdcv::TestCaseName TestCaseName
{
get => string.IsNullOrEmpty(Name) ? null : gcdcv::TestCaseName.Parse(Name, allowUnparsed: true);
set => Name = value?.ToString() ?? "";
}
}
public partial class RunTestCaseRequest
{
/// <summary>
/// <see cref="gcdcv::TestCaseName"/>-typed view over the <see cref="Name"/> resource name property.
/// </summary>
public gcdcv::TestCaseName TestCaseName
{
get => string.IsNullOrEmpty(Name) ? null : gcdcv::TestCaseName.Parse(Name, allowUnparsed: true);
set => Name = value?.ToString() ?? "";
}
/// <summary>
/// <see cref="EnvironmentName"/>-typed view over the <see cref="Environment"/> resource name property.
/// </summary>
public EnvironmentName EnvironmentAsEnvironmentName
{
get => string.IsNullOrEmpty(Environment) ? null : EnvironmentName.Parse(Environment, allowUnparsed: true);
set => Environment = value?.ToString() ?? "";
}
}
public partial class BatchRunTestCasesRequest
{
/// <summary><see cref="AgentName"/>-typed view over the <see cref="Parent"/> resource name property.</summary>
public AgentName ParentAsAgentName
{
get => string.IsNullOrEmpty(Parent) ? null : AgentName.Parse(Parent, allowUnparsed: true);
set => Parent = value?.ToString() ?? "";
}
/// <summary>
/// <see cref="EnvironmentName"/>-typed view over the <see cref="Environment"/> resource name property.
/// </summary>
public EnvironmentName EnvironmentAsEnvironmentName
{
get => string.IsNullOrEmpty(Environment) ? null : EnvironmentName.Parse(Environment, allowUnparsed: true);
set => Environment = value?.ToString() ?? "";
}
/// <summary>
/// <see cref="TestCaseName"/>-typed view over the <see cref="TestCases"/> resource name property.
/// </summary>
public gax::ResourceNameList<TestCaseName> TestCasesAsTestCaseNames
{
get => new gax::ResourceNameList<TestCaseName>(TestCases, s => string.IsNullOrEmpty(s) ? null : TestCaseName.Parse(s, allowUnparsed: true));
}
}
public partial class TestError
{
/// <summary>
/// <see cref="TestCaseName"/>-typed view over the <see cref="TestCase"/> resource name property.
/// </summary>
public TestCaseName TestCaseAsTestCaseName
{
get => string.IsNullOrEmpty(TestCase) ? null : TestCaseName.Parse(TestCase, allowUnparsed: true);
set => TestCase = value?.ToString() ?? "";
}
}
public partial class ImportTestCasesRequest
{
/// <summary><see cref="AgentName"/>-typed view over the <see cref="Parent"/> resource name property.</summary>
public AgentName ParentAsAgentName
{
get => string.IsNullOrEmpty(Parent) ? null : AgentName.Parse(Parent, allowUnparsed: true);
set => Parent = value?.ToString() ?? "";
}
}
public partial class ImportTestCasesResponse
{
/// <summary>
/// <see cref="TestCaseName"/>-typed view over the <see cref="Names"/> resource name property.
/// </summary>
public gax::ResourceNameList<TestCaseName> TestCaseNames
{
get => new gax::ResourceNameList<TestCaseName>(Names, s => string.IsNullOrEmpty(s) ? null : TestCaseName.Parse(s, allowUnparsed: true));
}
}
public partial class ExportTestCasesRequest
{
/// <summary><see cref="AgentName"/>-typed view over the <see cref="Parent"/> resource name property.</summary>
public AgentName ParentAsAgentName
{
get => string.IsNullOrEmpty(Parent) ? null : AgentName.Parse(Parent, allowUnparsed: true);
set => Parent = value?.ToString() ?? "";
}
}
public partial class ListTestCaseResultsRequest
{
/// <summary>
/// <see cref="TestCaseName"/>-typed view over the <see cref="Parent"/> resource name property.
/// </summary>
public TestCaseName ParentAsTestCaseName
{
get => string.IsNullOrEmpty(Parent) ? null : TestCaseName.Parse(Parent, allowUnparsed: true);
set => Parent = value?.ToString() ?? "";
}
}
public partial class GetTestCaseResultRequest
{
/// <summary>
/// <see cref="gcdcv::TestCaseResultName"/>-typed view over the <see cref="Name"/> resource name property.
/// </summary>
public gcdcv::TestCaseResultName TestCaseResultName
{
get => string.IsNullOrEmpty(Name) ? null : gcdcv::TestCaseResultName.Parse(Name, allowUnparsed: true);
set => Name = value?.ToString() ?? "";
}
}
}
| |
//------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//------------------------------------------------------------
namespace System.ServiceModel.Channels
{
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Net;
using System.Runtime;
using System.ServiceModel;
using System.ServiceModel.Description;
using System.ServiceModel.Diagnostics;
using System.ServiceModel.Dispatcher;
// What the connector interface needs to looks like
interface IPeerConnectorContract
{
void Connect(IPeerNeighbor neighbor, ConnectInfo connectInfo);
void Disconnect(IPeerNeighbor neighbor, DisconnectInfo disconnectInfo);
void Refuse(IPeerNeighbor neighbor, RefuseInfo refuseInfo);
void Welcome(IPeerNeighbor neighbor, WelcomeInfo welcomeInfo);
}
// Implemented by flooder / service uses this to delegate service invocations
interface IPeerFlooderContract<TFloodContract, TLinkContract>
{
//invoked by the peerservice
IAsyncResult OnFloodedMessage(IPeerNeighbor neighbor, TFloodContract floodedInfo, AsyncCallback callback, object state);
void EndFloodMessage(IAsyncResult result);
void ProcessLinkUtility(IPeerNeighbor neighbor, TLinkContract utilityInfo);
}
// Class that implements IPeerService contract for incoming neighbor sessions and messages.
// WARNING: This class is not synchronized. Expects the using class to synchronize access
[ServiceBehavior(
ConcurrencyMode = ConcurrencyMode.Multiple,
InstanceContextMode = InstanceContextMode.Single,
UseSynchronizationContext = false)]
class PeerService : IPeerService, IServiceBehavior, IChannelInitializer
{
public delegate bool ChannelCallback(IClientChannel channel);
public delegate IPeerNeighbor GetNeighborCallback(IPeerProxy channel);
Binding binding;
PeerNodeConfig config;
ChannelCallback newChannelCallback;
GetNeighborCallback getNeighborCallback;
ServiceHost serviceHost; // To listen for incoming neighbor sessions
IPeerConnectorContract connector;
IPeerFlooderContract<Message, UtilityInfo> flooder;
IPeerNodeMessageHandling messageHandler;
public PeerService(PeerNodeConfig config,
ChannelCallback channelCallback,
GetNeighborCallback getNeighborCallback,
Dictionary<Type, object> services)
: this(config, channelCallback, getNeighborCallback, services, null) { }
public PeerService(PeerNodeConfig config,
ChannelCallback channelCallback,
GetNeighborCallback getNeighborCallback,
Dictionary<Type, object> services,
IPeerNodeMessageHandling messageHandler)
{
this.config = config;
this.newChannelCallback = channelCallback;
Fx.Assert(getNeighborCallback != null, "getNeighborCallback must be passed to PeerService constructor");
this.getNeighborCallback = getNeighborCallback;
this.messageHandler = messageHandler;
if (services != null)
{
object reply = null;
services.TryGetValue(typeof(IPeerConnectorContract), out reply);
connector = reply as IPeerConnectorContract;
Fx.Assert(connector != null, "PeerService must be created with a connector implementation");
reply = null;
services.TryGetValue(typeof(IPeerFlooderContract<Message, UtilityInfo>), out reply);
flooder = reply as IPeerFlooderContract<Message, UtilityInfo>;
Fx.Assert(flooder != null, "PeerService must be created with a flooder implementation");
}
this.serviceHost = new ServiceHost(this);
// Add throttling
ServiceThrottlingBehavior throttle = new ServiceThrottlingBehavior();
throttle.MaxConcurrentCalls = this.config.MaxPendingIncomingCalls;
throttle.MaxConcurrentSessions = this.config.MaxConcurrentSessions;
this.serviceHost.Description.Behaviors.Add(throttle);
}
public void Abort()
{
this.serviceHost.Abort();
}
public Binding Binding
{
get { return this.binding; }
}
// Create the binding using user specified config. The stacking is
// BinaryMessageEncoder/TCP
void CreateBinding()
{
Collection<BindingElement> bindingElements = new Collection<BindingElement>();
BindingElement security = this.config.SecurityManager.GetSecurityBindingElement();
if (security != null)
{
bindingElements.Add(security);
}
TcpTransportBindingElement transport = new TcpTransportBindingElement();
transport.MaxReceivedMessageSize = this.config.MaxReceivedMessageSize;
transport.MaxBufferPoolSize = this.config.MaxBufferPoolSize;
transport.TeredoEnabled = true;
MessageEncodingBindingElement encoder = null;
if (messageHandler != null)
encoder = messageHandler.EncodingBindingElement;
if (encoder == null)
{
BinaryMessageEncodingBindingElement bencoder = new BinaryMessageEncodingBindingElement();
this.config.ReaderQuotas.CopyTo(bencoder.ReaderQuotas);
bindingElements.Add(bencoder);
}
else
{
bindingElements.Add(encoder);
}
bindingElements.Add(transport);
this.binding = new CustomBinding(bindingElements);
this.binding.ReceiveTimeout = TimeSpan.MaxValue;
}
// Returns the address that the serviceHost is listening on.
public EndpointAddress GetListenAddress()
{
IChannelListener listener = this.serviceHost.ChannelDispatchers[0].Listener;
return new EndpointAddress(listener.Uri, listener.GetProperty<EndpointIdentity>());
}
IPeerNeighbor GetNeighbor()
{
IPeerNeighbor neighbor = (IPeerNeighbor)getNeighborCallback(OperationContext.Current.GetCallbackChannel<IPeerProxy>());
if (neighbor == null || neighbor.State == PeerNeighborState.Closed)
{
if (DiagnosticUtility.ShouldTraceWarning)
{
TraceUtility.TraceEvent(TraceEventType.Warning, TraceCode.PeerNeighborNotFound,
SR.GetString(SR.TraceCodePeerNeighborNotFound),
new PeerNodeTraceRecord(config.NodeId),
OperationContext.Current.IncomingMessage);
}
return null;
}
if (DiagnosticUtility.ShouldTraceVerbose)
{
PeerNeighborState state = neighbor.State;
PeerNodeAddress listenAddr = null;
IPAddress connectIPAddr = null;
if (state >= PeerNeighborState.Opened && state <= PeerNeighborState.Connected)
{
listenAddr = config.GetListenAddress(true);
connectIPAddr = config.ListenIPAddress;
}
PeerNeighborTraceRecord record = new PeerNeighborTraceRecord(neighbor.NodeId,
this.config.NodeId, listenAddr, connectIPAddr, neighbor.GetHashCode(),
neighbor.IsInitiator, state.ToString(), null, null,
OperationContext.Current.IncomingMessage.Headers.Action);
TraceUtility.TraceEvent(TraceEventType.Verbose, TraceCode.PeerNeighborMessageReceived, SR.GetString(SR.TraceCodePeerNeighborMessageReceived), record, this, null);
}
return neighbor;
}
public void Open(TimeSpan timeout)
{
// Create the neighbor binding
CreateBinding();
this.serviceHost.Description.Endpoints.Clear();
ServiceEndpoint endPoint = this.serviceHost.AddServiceEndpoint(typeof(IPeerService), this.binding, config.GetMeshUri());
endPoint.ListenUri = config.GetSelfUri();
endPoint.ListenUriMode = (this.config.Port > 0) ? ListenUriMode.Explicit : ListenUriMode.Unique;
/*
Uncomment this to allow the retrieval of metadata
using the command:
\binaries.x86chk\svcutil http://localhost /t:metadata
ServiceMetadataBehavior mex = new ServiceMetadataBehavior();
mex.HttpGetEnabled = true;
mex.HttpGetUrl = new Uri("http://localhost");
mex.HttpsGetEnabled = true;
mex.HttpsGetUrl = new Uri("https://localhost");
this.serviceHost.Description.Behaviors.Add(mex);
*/
this.config.SecurityManager.ApplyServiceSecurity(this.serviceHost.Description);
this.serviceHost.Open(timeout);
if (DiagnosticUtility.ShouldTraceInformation)
{
TraceUtility.TraceEvent(TraceEventType.Information, TraceCode.PeerServiceOpened,
SR.GetString(SR.TraceCodePeerServiceOpened, this.GetListenAddress()), this);
}
}
//
// IContractBehavior and IChannelInitializer implementation.
// Used to register for incoming channel notification.
//
void IServiceBehavior.Validate(ServiceDescription description, ServiceHostBase serviceHost)
{
}
void IServiceBehavior.AddBindingParameters(ServiceDescription description, ServiceHostBase serviceHost, Collection<ServiceEndpoint> endpoints, BindingParameterCollection parameters)
{
}
void IServiceBehavior.ApplyDispatchBehavior(ServiceDescription description, ServiceHostBase serviceHost)
{
for (int i = 0; i < serviceHost.ChannelDispatchers.Count; i++)
{
ChannelDispatcher channelDispatcher = serviceHost.ChannelDispatchers[i] as ChannelDispatcher;
if (channelDispatcher != null)
{
bool addedChannelInitializer = false;
foreach (EndpointDispatcher endpointDispatcher in channelDispatcher.Endpoints)
{
if (!endpointDispatcher.IsSystemEndpoint)
{
if (!addedChannelInitializer)
{
channelDispatcher.ChannelInitializers.Add(this);
addedChannelInitializer = true;
}
endpointDispatcher.DispatchRuntime.OperationSelector = new OperationSelector(this.messageHandler);
}
}
}
}
}
void IChannelInitializer.Initialize(IClientChannel channel)
{
newChannelCallback(channel);
}
void IPeerServiceContract.Connect(ConnectInfo connectInfo)
{
IPeerNeighbor neighbor = GetNeighbor();
if (neighbor != null)
{
connector.Connect(neighbor, connectInfo);
}
}
void IPeerServiceContract.Disconnect(DisconnectInfo disconnectInfo)
{
IPeerNeighbor neighbor = GetNeighbor();
if (neighbor != null)
{
connector.Disconnect(neighbor, disconnectInfo);
}
}
void IPeerServiceContract.Refuse(RefuseInfo refuseInfo)
{
IPeerNeighbor neighbor = GetNeighbor();
if (neighbor != null)
{
connector.Refuse(neighbor, refuseInfo);
}
}
void IPeerServiceContract.Welcome(WelcomeInfo welcomeInfo)
{
IPeerNeighbor neighbor = GetNeighbor();
if (neighbor != null)
{
connector.Welcome(neighbor, welcomeInfo);
}
}
IAsyncResult IPeerServiceContract.BeginFloodMessage(Message floodedInfo, AsyncCallback callback, object state)
{
IPeerNeighbor neighbor = GetNeighbor();
if (neighbor != null)
{
return flooder.OnFloodedMessage(neighbor, floodedInfo, callback, state);
}
else
return new CompletedAsyncResult(callback, state);
}
void IPeerServiceContract.EndFloodMessage(IAsyncResult result)
{
flooder.EndFloodMessage(result);
}
void IPeerServiceContract.LinkUtility(UtilityInfo utilityInfo)
{
IPeerNeighbor neighbor = GetNeighbor();
if (neighbor != null)
{
flooder.ProcessLinkUtility(neighbor, utilityInfo);
}
}
Message IPeerServiceContract.ProcessRequestSecurityToken(Message message)
{
IPeerNeighbor neighbor = GetNeighbor();
if (neighbor == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ObjectDisposedException(typeof(IPeerNeighbor).ToString()));
Message reply = this.config.SecurityManager.ProcessRequest(neighbor, message);
if (reply == null)
{
OperationContext current = OperationContext.Current;
current.RequestContext.Close();
current.RequestContext = null;
}
return reply;
}
void IPeerServiceContract.Fault(Message message)
{
IPeerNeighbor neighbor = GetNeighbor();
if (neighbor == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ObjectDisposedException(typeof(IPeerNeighbor).ToString()));
neighbor.Abort(PeerCloseReason.Faulted, PeerCloseInitiator.RemoteNode);
}
void IPeerServiceContract.Ping(Message message)
{
}
}
}
| |
using System;
using System.Collections;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Text.RegularExpressions;
public static class dbg_extensions
{
static public T dump<T>(this T @object, params object[] args)
{
dbg.print(@object, args);
return @object;
}
static public T print<T>(this T @object, params object[] args)
{
dbg.print(@object, args);
return @object;
}
}
public class dbg
{
public static bool publicOnly = true;
public static bool propsOnly = false;
public static int max_items = 25;
public static int depth = 1;
public static void printf(string format, params object[] args)
{
try
{
print(string.Format(format, args));
}
catch { }
}
public static void print(object @object, params object[] args)
{
try
{
if (args.Length == 0)
{
new dbg().WriteObject(@object);
}
else
{
var sb = new StringBuilder();
foreach (var o in new[] { @object }.Concat(args))
{
if (sb.Length > 0)
sb.Append(" ");
sb.Append((o ?? "{null}").ToString());
}
new dbg().writeLine(sb.ToString());
}
}
catch { }
}
//===============================
int level = 0;
string indent = " ";
void write(object @object = null)
{
if (@object != null)
Console.Out.Write(@object.ToString().ReplaceClrAliaces());
}
void writeLine(object @object = null)
{
write(@object);
Console.Out.WriteLine();
}
string Indent
{
get { return new string('0', level).Replace("0", indent); }
}
string DisplayName(IEnumerable obj)
{
if (obj is Array)
{
var arr = obj as Array;
return "{" + obj + "} - Length: " + arr.Length + " item" + (arr.Length == 1 ? "" : "s");
}
else if (obj is IDictionary)
{
var arr = obj as IDictionary;
return "{IDictionary} - Count: " + arr.Count;
}
else if (obj is IList)
{
var arr = obj as IList;
return "{IList} - Count: " + arr.Count;
}
else
{
var count = obj.Cast<object>().Count();
return "{IEnumerable} - " + count + " item" + (count == 1 ? "" : "s");
}
}
static public string CustomPrimitiveTypes = "Newtonsoft.Json.Linq.JValue;";
static bool isPrimitive(object obj)
{
if (obj == null || obj.GetType().IsPrimitive || obj is decimal || obj is string)
return true;
else if (CustomPrimitiveTypes != null)
return CustomPrimitiveTypes.Split(new char[] { ';' }).Contains(obj.GetType().ToString());
return false;
}
void WriteObject(object obj)
{
level++;
if (isPrimitive(obj))
{
writeLine(obj);
}
// else if (obj is IDictionary dictionaryElement)
// {
// }
else if (obj is IEnumerable enumerableElement)
{
writeLine(DisplayName(enumerableElement));
int index = 0;
foreach (object item in enumerableElement)
{
write(Indent);
if (index > max_items) //need to have some limit
{
writeLine("... truncated ...");
break;
}
if (obj is IDictionary)
write($"{index++} - ");
else
write("[" + (index++) + "]: ");
if (level < (depth + 1))
{
level++;
WriteValue(item);
// WriteObject(item);
level--;
}
writeLine("");
}
}
else
{
writeLine("{" + obj + "}");
foreach (MemberInfo m in GetMembers(obj))
{
write(Indent);
write("." + m.Name);
write(" = ");
object value = GetMemberValue(obj, m);
if (isPrimitive(value) || (level >= depth))
{
WriteValue(value);
writeLine("");
}
else
WriteObject(value);
}
}
level--;
}
object GetMemberValue(object element, MemberInfo m)
{
FieldInfo f = m as FieldInfo;
PropertyInfo p = m as PropertyInfo;
if (f != null || p != null)
{
try
{
Type t = f != null ? f.FieldType : p.PropertyType;
return f != null ? f.GetValue(element) : p.GetValue(element, null);
}
catch
{
return "{???}";
}
}
return null;
}
void WriteValue(object o)
{
if (o == null)
write("{null}");
else if (o is DateTime)
write("{" + o + "}");
else if (o is DictionaryEntry entry)
{
// write($"[{entry.Key}]: {entry.Value}");
write($"[{entry.Key}]: ");
WriteValue(entry.Value);
}
else if (o is ValueType)
write(o);
else if (o is string)
write("\"" + o + "\"");
else
write("{" + o.ToString().TrimStart('{').TrimEnd('}') + "}");
}
MemberInfo[] GetMembers(object obj)
{
Func<MemberInfo, bool> relevant_types = x => x.MemberType == MemberTypes.Field || x.MemberType == MemberTypes.Property;
if (propsOnly)
relevant_types = x => x.MemberType == MemberTypes.Property;
MemberInfo[] members = obj.GetType()
.GetMembers(BindingFlags.Public | BindingFlags.Instance)
.Where(relevant_types)
.OrderBy(x => x.Name)
.ToArray();
var private_members = new MemberInfo[0];
if (!publicOnly)
private_members = obj.GetType()
.GetMembers(BindingFlags.NonPublic | BindingFlags.Instance)
.Where(relevant_types)
.OrderBy(x => x.Name)
.OrderBy(x => char.IsLower(x.Name[0]))
.OrderBy(x => x.Name.StartsWith("_"))
.ToArray();
var items = members.Concat(private_members);
return items.ToArray();
}
}
internal static class Extension
{
static public string ReplaceWholeWord(this string text, string pattern, string replacement)
{
return Regex.Replace(text, @"\b(" + pattern + @")\b", replacement);
}
static public string ReplaceClrAliaces(this string text, bool hideSystemNamespace = false)
{
if (string.IsNullOrEmpty(text))
return text;
else
{
var retval = text.ReplaceWholeWord("System.Object", "object")
.ReplaceWholeWord("System.Boolean", "bool")
.ReplaceWholeWord("System.Byte", "byte")
.ReplaceWholeWord("System.SByte", "sbyte")
.ReplaceWholeWord("System.Char", "char")
.ReplaceWholeWord("System.Decimal", "decimal")
.ReplaceWholeWord("System.Double", "double")
.ReplaceWholeWord("System.Single", "float")
.ReplaceWholeWord("System.Int32", "int")
.ReplaceWholeWord("System.UInt32", "uint")
.ReplaceWholeWord("System.Int64", "long")
.ReplaceWholeWord("System.UInt64", "ulong")
.ReplaceWholeWord("System.Object", "object")
.ReplaceWholeWord("System.Int16", "short")
.ReplaceWholeWord("System.UInt16", "ushort")
.ReplaceWholeWord("System.String", "string")
.ReplaceWholeWord("System.Void", "void")
.ReplaceWholeWord("Void", "void");
if (hideSystemNamespace && retval.StartsWith("System."))
{
string typeName = retval.Substring("System.".Length);
if (!typeName.Contains('.')) // it is not a complex namespace
retval = typeName;
}
return retval.Replace("`1", "<T>")
.Replace("`2", "<T, T1>")
.Replace("`3", "<T, T1, T2>")
.Replace("`4", "<T, T1, T2, T3>");
}
}
// for reflecting dynamic objects look at dbg.dynamic.cs
}
| |
// Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
using gaxgrpc = Google.Api.Gax.Grpc;
using proto = Google.Protobuf;
using wkt = Google.Protobuf.WellKnownTypes;
using grpccore = Grpc.Core;
using moq = Moq;
using st = System.Threading;
using stt = System.Threading.Tasks;
using xunit = Xunit;
namespace Google.Cloud.Iam.Credentials.V1.Tests
{
/// <summary>Generated unit tests.</summary>
public sealed class GeneratedIAMCredentialsClientTest
{
[xunit::FactAttribute]
public void GenerateAccessTokenRequestObject()
{
moq::Mock<IAMCredentials.IAMCredentialsClient> mockGrpcClient = new moq::Mock<IAMCredentials.IAMCredentialsClient>(moq::MockBehavior.Strict);
GenerateAccessTokenRequest request = new GenerateAccessTokenRequest
{
ServiceAccountName = ServiceAccountName.FromProjectServiceAccount("[PROJECT]", "[SERVICE_ACCOUNT]"),
Delegates =
{
"delegates331d18f6",
},
Scope = { "scope14fda131", },
Lifetime = new wkt::Duration(),
};
GenerateAccessTokenResponse expectedResponse = new GenerateAccessTokenResponse
{
AccessToken = "access_token85826cd8",
ExpireTime = new wkt::Timestamp(),
};
mockGrpcClient.Setup(x => x.GenerateAccessToken(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
IAMCredentialsClient client = new IAMCredentialsClientImpl(mockGrpcClient.Object, null);
GenerateAccessTokenResponse response = client.GenerateAccessToken(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GenerateAccessTokenRequestObjectAsync()
{
moq::Mock<IAMCredentials.IAMCredentialsClient> mockGrpcClient = new moq::Mock<IAMCredentials.IAMCredentialsClient>(moq::MockBehavior.Strict);
GenerateAccessTokenRequest request = new GenerateAccessTokenRequest
{
ServiceAccountName = ServiceAccountName.FromProjectServiceAccount("[PROJECT]", "[SERVICE_ACCOUNT]"),
Delegates =
{
"delegates331d18f6",
},
Scope = { "scope14fda131", },
Lifetime = new wkt::Duration(),
};
GenerateAccessTokenResponse expectedResponse = new GenerateAccessTokenResponse
{
AccessToken = "access_token85826cd8",
ExpireTime = new wkt::Timestamp(),
};
mockGrpcClient.Setup(x => x.GenerateAccessTokenAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<GenerateAccessTokenResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null));
IAMCredentialsClient client = new IAMCredentialsClientImpl(mockGrpcClient.Object, null);
GenerateAccessTokenResponse responseCallSettings = await client.GenerateAccessTokenAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
GenerateAccessTokenResponse responseCancellationToken = await client.GenerateAccessTokenAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GenerateAccessToken()
{
moq::Mock<IAMCredentials.IAMCredentialsClient> mockGrpcClient = new moq::Mock<IAMCredentials.IAMCredentialsClient>(moq::MockBehavior.Strict);
GenerateAccessTokenRequest request = new GenerateAccessTokenRequest
{
ServiceAccountName = ServiceAccountName.FromProjectServiceAccount("[PROJECT]", "[SERVICE_ACCOUNT]"),
Delegates =
{
"delegates331d18f6",
},
Scope = { "scope14fda131", },
Lifetime = new wkt::Duration(),
};
GenerateAccessTokenResponse expectedResponse = new GenerateAccessTokenResponse
{
AccessToken = "access_token85826cd8",
ExpireTime = new wkt::Timestamp(),
};
mockGrpcClient.Setup(x => x.GenerateAccessToken(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
IAMCredentialsClient client = new IAMCredentialsClientImpl(mockGrpcClient.Object, null);
GenerateAccessTokenResponse response = client.GenerateAccessToken(request.Name, request.Delegates, request.Scope, request.Lifetime);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GenerateAccessTokenAsync()
{
moq::Mock<IAMCredentials.IAMCredentialsClient> mockGrpcClient = new moq::Mock<IAMCredentials.IAMCredentialsClient>(moq::MockBehavior.Strict);
GenerateAccessTokenRequest request = new GenerateAccessTokenRequest
{
ServiceAccountName = ServiceAccountName.FromProjectServiceAccount("[PROJECT]", "[SERVICE_ACCOUNT]"),
Delegates =
{
"delegates331d18f6",
},
Scope = { "scope14fda131", },
Lifetime = new wkt::Duration(),
};
GenerateAccessTokenResponse expectedResponse = new GenerateAccessTokenResponse
{
AccessToken = "access_token85826cd8",
ExpireTime = new wkt::Timestamp(),
};
mockGrpcClient.Setup(x => x.GenerateAccessTokenAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<GenerateAccessTokenResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null));
IAMCredentialsClient client = new IAMCredentialsClientImpl(mockGrpcClient.Object, null);
GenerateAccessTokenResponse responseCallSettings = await client.GenerateAccessTokenAsync(request.Name, request.Delegates, request.Scope, request.Lifetime, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
GenerateAccessTokenResponse responseCancellationToken = await client.GenerateAccessTokenAsync(request.Name, request.Delegates, request.Scope, request.Lifetime, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GenerateAccessTokenResourceNames()
{
moq::Mock<IAMCredentials.IAMCredentialsClient> mockGrpcClient = new moq::Mock<IAMCredentials.IAMCredentialsClient>(moq::MockBehavior.Strict);
GenerateAccessTokenRequest request = new GenerateAccessTokenRequest
{
ServiceAccountName = ServiceAccountName.FromProjectServiceAccount("[PROJECT]", "[SERVICE_ACCOUNT]"),
Delegates =
{
"delegates331d18f6",
},
Scope = { "scope14fda131", },
Lifetime = new wkt::Duration(),
};
GenerateAccessTokenResponse expectedResponse = new GenerateAccessTokenResponse
{
AccessToken = "access_token85826cd8",
ExpireTime = new wkt::Timestamp(),
};
mockGrpcClient.Setup(x => x.GenerateAccessToken(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
IAMCredentialsClient client = new IAMCredentialsClientImpl(mockGrpcClient.Object, null);
GenerateAccessTokenResponse response = client.GenerateAccessToken(request.ServiceAccountName, request.Delegates, request.Scope, request.Lifetime);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GenerateAccessTokenResourceNamesAsync()
{
moq::Mock<IAMCredentials.IAMCredentialsClient> mockGrpcClient = new moq::Mock<IAMCredentials.IAMCredentialsClient>(moq::MockBehavior.Strict);
GenerateAccessTokenRequest request = new GenerateAccessTokenRequest
{
ServiceAccountName = ServiceAccountName.FromProjectServiceAccount("[PROJECT]", "[SERVICE_ACCOUNT]"),
Delegates =
{
"delegates331d18f6",
},
Scope = { "scope14fda131", },
Lifetime = new wkt::Duration(),
};
GenerateAccessTokenResponse expectedResponse = new GenerateAccessTokenResponse
{
AccessToken = "access_token85826cd8",
ExpireTime = new wkt::Timestamp(),
};
mockGrpcClient.Setup(x => x.GenerateAccessTokenAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<GenerateAccessTokenResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null));
IAMCredentialsClient client = new IAMCredentialsClientImpl(mockGrpcClient.Object, null);
GenerateAccessTokenResponse responseCallSettings = await client.GenerateAccessTokenAsync(request.ServiceAccountName, request.Delegates, request.Scope, request.Lifetime, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
GenerateAccessTokenResponse responseCancellationToken = await client.GenerateAccessTokenAsync(request.ServiceAccountName, request.Delegates, request.Scope, request.Lifetime, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GenerateIdTokenRequestObject()
{
moq::Mock<IAMCredentials.IAMCredentialsClient> mockGrpcClient = new moq::Mock<IAMCredentials.IAMCredentialsClient>(moq::MockBehavior.Strict);
GenerateIdTokenRequest request = new GenerateIdTokenRequest
{
ServiceAccountName = ServiceAccountName.FromProjectServiceAccount("[PROJECT]", "[SERVICE_ACCOUNT]"),
Delegates =
{
"delegates331d18f6",
},
Audience = "audience986f1fe3",
IncludeEmail = false,
};
GenerateIdTokenResponse expectedResponse = new GenerateIdTokenResponse
{
Token = "tokena18da094",
};
mockGrpcClient.Setup(x => x.GenerateIdToken(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
IAMCredentialsClient client = new IAMCredentialsClientImpl(mockGrpcClient.Object, null);
GenerateIdTokenResponse response = client.GenerateIdToken(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GenerateIdTokenRequestObjectAsync()
{
moq::Mock<IAMCredentials.IAMCredentialsClient> mockGrpcClient = new moq::Mock<IAMCredentials.IAMCredentialsClient>(moq::MockBehavior.Strict);
GenerateIdTokenRequest request = new GenerateIdTokenRequest
{
ServiceAccountName = ServiceAccountName.FromProjectServiceAccount("[PROJECT]", "[SERVICE_ACCOUNT]"),
Delegates =
{
"delegates331d18f6",
},
Audience = "audience986f1fe3",
IncludeEmail = false,
};
GenerateIdTokenResponse expectedResponse = new GenerateIdTokenResponse
{
Token = "tokena18da094",
};
mockGrpcClient.Setup(x => x.GenerateIdTokenAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<GenerateIdTokenResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null));
IAMCredentialsClient client = new IAMCredentialsClientImpl(mockGrpcClient.Object, null);
GenerateIdTokenResponse responseCallSettings = await client.GenerateIdTokenAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
GenerateIdTokenResponse responseCancellationToken = await client.GenerateIdTokenAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GenerateIdToken()
{
moq::Mock<IAMCredentials.IAMCredentialsClient> mockGrpcClient = new moq::Mock<IAMCredentials.IAMCredentialsClient>(moq::MockBehavior.Strict);
GenerateIdTokenRequest request = new GenerateIdTokenRequest
{
ServiceAccountName = ServiceAccountName.FromProjectServiceAccount("[PROJECT]", "[SERVICE_ACCOUNT]"),
Delegates =
{
"delegates331d18f6",
},
Audience = "audience986f1fe3",
IncludeEmail = false,
};
GenerateIdTokenResponse expectedResponse = new GenerateIdTokenResponse
{
Token = "tokena18da094",
};
mockGrpcClient.Setup(x => x.GenerateIdToken(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
IAMCredentialsClient client = new IAMCredentialsClientImpl(mockGrpcClient.Object, null);
GenerateIdTokenResponse response = client.GenerateIdToken(request.Name, request.Delegates, request.Audience, request.IncludeEmail);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GenerateIdTokenAsync()
{
moq::Mock<IAMCredentials.IAMCredentialsClient> mockGrpcClient = new moq::Mock<IAMCredentials.IAMCredentialsClient>(moq::MockBehavior.Strict);
GenerateIdTokenRequest request = new GenerateIdTokenRequest
{
ServiceAccountName = ServiceAccountName.FromProjectServiceAccount("[PROJECT]", "[SERVICE_ACCOUNT]"),
Delegates =
{
"delegates331d18f6",
},
Audience = "audience986f1fe3",
IncludeEmail = false,
};
GenerateIdTokenResponse expectedResponse = new GenerateIdTokenResponse
{
Token = "tokena18da094",
};
mockGrpcClient.Setup(x => x.GenerateIdTokenAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<GenerateIdTokenResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null));
IAMCredentialsClient client = new IAMCredentialsClientImpl(mockGrpcClient.Object, null);
GenerateIdTokenResponse responseCallSettings = await client.GenerateIdTokenAsync(request.Name, request.Delegates, request.Audience, request.IncludeEmail, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
GenerateIdTokenResponse responseCancellationToken = await client.GenerateIdTokenAsync(request.Name, request.Delegates, request.Audience, request.IncludeEmail, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GenerateIdTokenResourceNames()
{
moq::Mock<IAMCredentials.IAMCredentialsClient> mockGrpcClient = new moq::Mock<IAMCredentials.IAMCredentialsClient>(moq::MockBehavior.Strict);
GenerateIdTokenRequest request = new GenerateIdTokenRequest
{
ServiceAccountName = ServiceAccountName.FromProjectServiceAccount("[PROJECT]", "[SERVICE_ACCOUNT]"),
Delegates =
{
"delegates331d18f6",
},
Audience = "audience986f1fe3",
IncludeEmail = false,
};
GenerateIdTokenResponse expectedResponse = new GenerateIdTokenResponse
{
Token = "tokena18da094",
};
mockGrpcClient.Setup(x => x.GenerateIdToken(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
IAMCredentialsClient client = new IAMCredentialsClientImpl(mockGrpcClient.Object, null);
GenerateIdTokenResponse response = client.GenerateIdToken(request.ServiceAccountName, request.Delegates, request.Audience, request.IncludeEmail);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GenerateIdTokenResourceNamesAsync()
{
moq::Mock<IAMCredentials.IAMCredentialsClient> mockGrpcClient = new moq::Mock<IAMCredentials.IAMCredentialsClient>(moq::MockBehavior.Strict);
GenerateIdTokenRequest request = new GenerateIdTokenRequest
{
ServiceAccountName = ServiceAccountName.FromProjectServiceAccount("[PROJECT]", "[SERVICE_ACCOUNT]"),
Delegates =
{
"delegates331d18f6",
},
Audience = "audience986f1fe3",
IncludeEmail = false,
};
GenerateIdTokenResponse expectedResponse = new GenerateIdTokenResponse
{
Token = "tokena18da094",
};
mockGrpcClient.Setup(x => x.GenerateIdTokenAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<GenerateIdTokenResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null));
IAMCredentialsClient client = new IAMCredentialsClientImpl(mockGrpcClient.Object, null);
GenerateIdTokenResponse responseCallSettings = await client.GenerateIdTokenAsync(request.ServiceAccountName, request.Delegates, request.Audience, request.IncludeEmail, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
GenerateIdTokenResponse responseCancellationToken = await client.GenerateIdTokenAsync(request.ServiceAccountName, request.Delegates, request.Audience, request.IncludeEmail, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void SignBlobRequestObject()
{
moq::Mock<IAMCredentials.IAMCredentialsClient> mockGrpcClient = new moq::Mock<IAMCredentials.IAMCredentialsClient>(moq::MockBehavior.Strict);
SignBlobRequest request = new SignBlobRequest
{
ServiceAccountName = ServiceAccountName.FromProjectServiceAccount("[PROJECT]", "[SERVICE_ACCOUNT]"),
Delegates =
{
"delegates331d18f6",
},
Payload = proto::ByteString.CopyFromUtf8("payloadf43c1c32"),
};
SignBlobResponse expectedResponse = new SignBlobResponse
{
KeyId = "key_id2691f630",
SignedBlob = proto::ByteString.CopyFromUtf8("signed_blob0afddec9"),
};
mockGrpcClient.Setup(x => x.SignBlob(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
IAMCredentialsClient client = new IAMCredentialsClientImpl(mockGrpcClient.Object, null);
SignBlobResponse response = client.SignBlob(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task SignBlobRequestObjectAsync()
{
moq::Mock<IAMCredentials.IAMCredentialsClient> mockGrpcClient = new moq::Mock<IAMCredentials.IAMCredentialsClient>(moq::MockBehavior.Strict);
SignBlobRequest request = new SignBlobRequest
{
ServiceAccountName = ServiceAccountName.FromProjectServiceAccount("[PROJECT]", "[SERVICE_ACCOUNT]"),
Delegates =
{
"delegates331d18f6",
},
Payload = proto::ByteString.CopyFromUtf8("payloadf43c1c32"),
};
SignBlobResponse expectedResponse = new SignBlobResponse
{
KeyId = "key_id2691f630",
SignedBlob = proto::ByteString.CopyFromUtf8("signed_blob0afddec9"),
};
mockGrpcClient.Setup(x => x.SignBlobAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<SignBlobResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null));
IAMCredentialsClient client = new IAMCredentialsClientImpl(mockGrpcClient.Object, null);
SignBlobResponse responseCallSettings = await client.SignBlobAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
SignBlobResponse responseCancellationToken = await client.SignBlobAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void SignBlob()
{
moq::Mock<IAMCredentials.IAMCredentialsClient> mockGrpcClient = new moq::Mock<IAMCredentials.IAMCredentialsClient>(moq::MockBehavior.Strict);
SignBlobRequest request = new SignBlobRequest
{
ServiceAccountName = ServiceAccountName.FromProjectServiceAccount("[PROJECT]", "[SERVICE_ACCOUNT]"),
Delegates =
{
"delegates331d18f6",
},
Payload = proto::ByteString.CopyFromUtf8("payloadf43c1c32"),
};
SignBlobResponse expectedResponse = new SignBlobResponse
{
KeyId = "key_id2691f630",
SignedBlob = proto::ByteString.CopyFromUtf8("signed_blob0afddec9"),
};
mockGrpcClient.Setup(x => x.SignBlob(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
IAMCredentialsClient client = new IAMCredentialsClientImpl(mockGrpcClient.Object, null);
SignBlobResponse response = client.SignBlob(request.Name, request.Delegates, request.Payload);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task SignBlobAsync()
{
moq::Mock<IAMCredentials.IAMCredentialsClient> mockGrpcClient = new moq::Mock<IAMCredentials.IAMCredentialsClient>(moq::MockBehavior.Strict);
SignBlobRequest request = new SignBlobRequest
{
ServiceAccountName = ServiceAccountName.FromProjectServiceAccount("[PROJECT]", "[SERVICE_ACCOUNT]"),
Delegates =
{
"delegates331d18f6",
},
Payload = proto::ByteString.CopyFromUtf8("payloadf43c1c32"),
};
SignBlobResponse expectedResponse = new SignBlobResponse
{
KeyId = "key_id2691f630",
SignedBlob = proto::ByteString.CopyFromUtf8("signed_blob0afddec9"),
};
mockGrpcClient.Setup(x => x.SignBlobAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<SignBlobResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null));
IAMCredentialsClient client = new IAMCredentialsClientImpl(mockGrpcClient.Object, null);
SignBlobResponse responseCallSettings = await client.SignBlobAsync(request.Name, request.Delegates, request.Payload, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
SignBlobResponse responseCancellationToken = await client.SignBlobAsync(request.Name, request.Delegates, request.Payload, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void SignBlobResourceNames()
{
moq::Mock<IAMCredentials.IAMCredentialsClient> mockGrpcClient = new moq::Mock<IAMCredentials.IAMCredentialsClient>(moq::MockBehavior.Strict);
SignBlobRequest request = new SignBlobRequest
{
ServiceAccountName = ServiceAccountName.FromProjectServiceAccount("[PROJECT]", "[SERVICE_ACCOUNT]"),
Delegates =
{
"delegates331d18f6",
},
Payload = proto::ByteString.CopyFromUtf8("payloadf43c1c32"),
};
SignBlobResponse expectedResponse = new SignBlobResponse
{
KeyId = "key_id2691f630",
SignedBlob = proto::ByteString.CopyFromUtf8("signed_blob0afddec9"),
};
mockGrpcClient.Setup(x => x.SignBlob(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
IAMCredentialsClient client = new IAMCredentialsClientImpl(mockGrpcClient.Object, null);
SignBlobResponse response = client.SignBlob(request.ServiceAccountName, request.Delegates, request.Payload);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task SignBlobResourceNamesAsync()
{
moq::Mock<IAMCredentials.IAMCredentialsClient> mockGrpcClient = new moq::Mock<IAMCredentials.IAMCredentialsClient>(moq::MockBehavior.Strict);
SignBlobRequest request = new SignBlobRequest
{
ServiceAccountName = ServiceAccountName.FromProjectServiceAccount("[PROJECT]", "[SERVICE_ACCOUNT]"),
Delegates =
{
"delegates331d18f6",
},
Payload = proto::ByteString.CopyFromUtf8("payloadf43c1c32"),
};
SignBlobResponse expectedResponse = new SignBlobResponse
{
KeyId = "key_id2691f630",
SignedBlob = proto::ByteString.CopyFromUtf8("signed_blob0afddec9"),
};
mockGrpcClient.Setup(x => x.SignBlobAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<SignBlobResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null));
IAMCredentialsClient client = new IAMCredentialsClientImpl(mockGrpcClient.Object, null);
SignBlobResponse responseCallSettings = await client.SignBlobAsync(request.ServiceAccountName, request.Delegates, request.Payload, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
SignBlobResponse responseCancellationToken = await client.SignBlobAsync(request.ServiceAccountName, request.Delegates, request.Payload, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void SignJwtRequestObject()
{
moq::Mock<IAMCredentials.IAMCredentialsClient> mockGrpcClient = new moq::Mock<IAMCredentials.IAMCredentialsClient>(moq::MockBehavior.Strict);
SignJwtRequest request = new SignJwtRequest
{
ServiceAccountName = ServiceAccountName.FromProjectServiceAccount("[PROJECT]", "[SERVICE_ACCOUNT]"),
Delegates =
{
"delegates331d18f6",
},
Payload = "payloadf43c1c32",
};
SignJwtResponse expectedResponse = new SignJwtResponse
{
KeyId = "key_id2691f630",
SignedJwt = "signed_jwt09d786db",
};
mockGrpcClient.Setup(x => x.SignJwt(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
IAMCredentialsClient client = new IAMCredentialsClientImpl(mockGrpcClient.Object, null);
SignJwtResponse response = client.SignJwt(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task SignJwtRequestObjectAsync()
{
moq::Mock<IAMCredentials.IAMCredentialsClient> mockGrpcClient = new moq::Mock<IAMCredentials.IAMCredentialsClient>(moq::MockBehavior.Strict);
SignJwtRequest request = new SignJwtRequest
{
ServiceAccountName = ServiceAccountName.FromProjectServiceAccount("[PROJECT]", "[SERVICE_ACCOUNT]"),
Delegates =
{
"delegates331d18f6",
},
Payload = "payloadf43c1c32",
};
SignJwtResponse expectedResponse = new SignJwtResponse
{
KeyId = "key_id2691f630",
SignedJwt = "signed_jwt09d786db",
};
mockGrpcClient.Setup(x => x.SignJwtAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<SignJwtResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null));
IAMCredentialsClient client = new IAMCredentialsClientImpl(mockGrpcClient.Object, null);
SignJwtResponse responseCallSettings = await client.SignJwtAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
SignJwtResponse responseCancellationToken = await client.SignJwtAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void SignJwt()
{
moq::Mock<IAMCredentials.IAMCredentialsClient> mockGrpcClient = new moq::Mock<IAMCredentials.IAMCredentialsClient>(moq::MockBehavior.Strict);
SignJwtRequest request = new SignJwtRequest
{
ServiceAccountName = ServiceAccountName.FromProjectServiceAccount("[PROJECT]", "[SERVICE_ACCOUNT]"),
Delegates =
{
"delegates331d18f6",
},
Payload = "payloadf43c1c32",
};
SignJwtResponse expectedResponse = new SignJwtResponse
{
KeyId = "key_id2691f630",
SignedJwt = "signed_jwt09d786db",
};
mockGrpcClient.Setup(x => x.SignJwt(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
IAMCredentialsClient client = new IAMCredentialsClientImpl(mockGrpcClient.Object, null);
SignJwtResponse response = client.SignJwt(request.Name, request.Delegates, request.Payload);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task SignJwtAsync()
{
moq::Mock<IAMCredentials.IAMCredentialsClient> mockGrpcClient = new moq::Mock<IAMCredentials.IAMCredentialsClient>(moq::MockBehavior.Strict);
SignJwtRequest request = new SignJwtRequest
{
ServiceAccountName = ServiceAccountName.FromProjectServiceAccount("[PROJECT]", "[SERVICE_ACCOUNT]"),
Delegates =
{
"delegates331d18f6",
},
Payload = "payloadf43c1c32",
};
SignJwtResponse expectedResponse = new SignJwtResponse
{
KeyId = "key_id2691f630",
SignedJwt = "signed_jwt09d786db",
};
mockGrpcClient.Setup(x => x.SignJwtAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<SignJwtResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null));
IAMCredentialsClient client = new IAMCredentialsClientImpl(mockGrpcClient.Object, null);
SignJwtResponse responseCallSettings = await client.SignJwtAsync(request.Name, request.Delegates, request.Payload, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
SignJwtResponse responseCancellationToken = await client.SignJwtAsync(request.Name, request.Delegates, request.Payload, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void SignJwtResourceNames()
{
moq::Mock<IAMCredentials.IAMCredentialsClient> mockGrpcClient = new moq::Mock<IAMCredentials.IAMCredentialsClient>(moq::MockBehavior.Strict);
SignJwtRequest request = new SignJwtRequest
{
ServiceAccountName = ServiceAccountName.FromProjectServiceAccount("[PROJECT]", "[SERVICE_ACCOUNT]"),
Delegates =
{
"delegates331d18f6",
},
Payload = "payloadf43c1c32",
};
SignJwtResponse expectedResponse = new SignJwtResponse
{
KeyId = "key_id2691f630",
SignedJwt = "signed_jwt09d786db",
};
mockGrpcClient.Setup(x => x.SignJwt(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
IAMCredentialsClient client = new IAMCredentialsClientImpl(mockGrpcClient.Object, null);
SignJwtResponse response = client.SignJwt(request.ServiceAccountName, request.Delegates, request.Payload);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task SignJwtResourceNamesAsync()
{
moq::Mock<IAMCredentials.IAMCredentialsClient> mockGrpcClient = new moq::Mock<IAMCredentials.IAMCredentialsClient>(moq::MockBehavior.Strict);
SignJwtRequest request = new SignJwtRequest
{
ServiceAccountName = ServiceAccountName.FromProjectServiceAccount("[PROJECT]", "[SERVICE_ACCOUNT]"),
Delegates =
{
"delegates331d18f6",
},
Payload = "payloadf43c1c32",
};
SignJwtResponse expectedResponse = new SignJwtResponse
{
KeyId = "key_id2691f630",
SignedJwt = "signed_jwt09d786db",
};
mockGrpcClient.Setup(x => x.SignJwtAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<SignJwtResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null));
IAMCredentialsClient client = new IAMCredentialsClientImpl(mockGrpcClient.Object, null);
SignJwtResponse responseCallSettings = await client.SignJwtAsync(request.ServiceAccountName, request.Delegates, request.Payload, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
SignJwtResponse responseCancellationToken = await client.SignJwtAsync(request.ServiceAccountName, request.Delegates, request.Payload, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
}
}
| |
namespace android.graphics
{
[global::MonoJavaBridge.JavaClass()]
public partial class Path : java.lang.Object
{
internal new static global::MonoJavaBridge.JniGlobalHandle staticClass;
static Path()
{
InitJNI();
}
protected Path(global::MonoJavaBridge.JNIEnv @__env) : base(@__env)
{
}
[global::MonoJavaBridge.JavaClass()]
public sealed partial class Direction : java.lang.Enum
{
internal new static global::MonoJavaBridge.JniGlobalHandle staticClass;
static Direction()
{
InitJNI();
}
internal Direction(global::MonoJavaBridge.JNIEnv @__env) : base(@__env)
{
}
internal static global::MonoJavaBridge.MethodId _values3535;
public static global::android.graphics.Path.Direction[] values()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
return global::MonoJavaBridge.JavaBridge.WrapJavaArrayObject<android.graphics.Path.Direction>(@__env.CallStaticObjectMethod(android.graphics.Path.Direction.staticClass, global::android.graphics.Path.Direction._values3535)) as android.graphics.Path.Direction[];
}
internal static global::MonoJavaBridge.MethodId _valueOf3536;
public static global::android.graphics.Path.Direction valueOf(java.lang.String arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallStaticObjectMethod(android.graphics.Path.Direction.staticClass, global::android.graphics.Path.Direction._valueOf3536, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as android.graphics.Path.Direction;
}
internal static global::MonoJavaBridge.FieldId _CCW3537;
public static global::android.graphics.Path.Direction CCW
{
get
{
return default(global::android.graphics.Path.Direction);
}
}
internal static global::MonoJavaBridge.FieldId _CW3538;
public static global::android.graphics.Path.Direction CW
{
get
{
return default(global::android.graphics.Path.Direction);
}
}
private static void InitJNI()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::android.graphics.Path.Direction.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/graphics/Path$Direction"));
global::android.graphics.Path.Direction._values3535 = @__env.GetStaticMethodIDNoThrow(global::android.graphics.Path.Direction.staticClass, "values", "()[Landroid/graphics/Path/Direction;");
global::android.graphics.Path.Direction._valueOf3536 = @__env.GetStaticMethodIDNoThrow(global::android.graphics.Path.Direction.staticClass, "valueOf", "(Ljava/lang/String;)Landroid/graphics/Path$Direction;");
}
}
[global::MonoJavaBridge.JavaClass()]
public sealed partial class FillType : java.lang.Enum
{
internal new static global::MonoJavaBridge.JniGlobalHandle staticClass;
static FillType()
{
InitJNI();
}
internal FillType(global::MonoJavaBridge.JNIEnv @__env) : base(@__env)
{
}
internal static global::MonoJavaBridge.MethodId _values3539;
public static global::android.graphics.Path.FillType[] values()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
return global::MonoJavaBridge.JavaBridge.WrapJavaArrayObject<android.graphics.Path.FillType>(@__env.CallStaticObjectMethod(android.graphics.Path.FillType.staticClass, global::android.graphics.Path.FillType._values3539)) as android.graphics.Path.FillType[];
}
internal static global::MonoJavaBridge.MethodId _valueOf3540;
public static global::android.graphics.Path.FillType valueOf(java.lang.String arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallStaticObjectMethod(android.graphics.Path.FillType.staticClass, global::android.graphics.Path.FillType._valueOf3540, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as android.graphics.Path.FillType;
}
internal static global::MonoJavaBridge.FieldId _EVEN_ODD3541;
public static global::android.graphics.Path.FillType EVEN_ODD
{
get
{
return default(global::android.graphics.Path.FillType);
}
}
internal static global::MonoJavaBridge.FieldId _INVERSE_EVEN_ODD3542;
public static global::android.graphics.Path.FillType INVERSE_EVEN_ODD
{
get
{
return default(global::android.graphics.Path.FillType);
}
}
internal static global::MonoJavaBridge.FieldId _INVERSE_WINDING3543;
public static global::android.graphics.Path.FillType INVERSE_WINDING
{
get
{
return default(global::android.graphics.Path.FillType);
}
}
internal static global::MonoJavaBridge.FieldId _WINDING3544;
public static global::android.graphics.Path.FillType WINDING
{
get
{
return default(global::android.graphics.Path.FillType);
}
}
private static void InitJNI()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::android.graphics.Path.FillType.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/graphics/Path$FillType"));
global::android.graphics.Path.FillType._values3539 = @__env.GetStaticMethodIDNoThrow(global::android.graphics.Path.FillType.staticClass, "values", "()[Landroid/graphics/Path/FillType;");
global::android.graphics.Path.FillType._valueOf3540 = @__env.GetStaticMethodIDNoThrow(global::android.graphics.Path.FillType.staticClass, "valueOf", "(Ljava/lang/String;)Landroid/graphics/Path$FillType;");
}
}
internal static global::MonoJavaBridge.MethodId _finalize3545;
protected override void finalize()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.graphics.Path._finalize3545);
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.graphics.Path.staticClass, global::android.graphics.Path._finalize3545);
}
internal static global::MonoJavaBridge.MethodId _offset3546;
public virtual void offset(float arg0, float arg1, android.graphics.Path arg2)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.graphics.Path._offset3546, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.graphics.Path.staticClass, global::android.graphics.Path._offset3546, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2));
}
internal static global::MonoJavaBridge.MethodId _offset3547;
public virtual void offset(float arg0, float arg1)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.graphics.Path._offset3547, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.graphics.Path.staticClass, global::android.graphics.Path._offset3547, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
internal static global::MonoJavaBridge.MethodId _isEmpty3548;
public virtual bool isEmpty()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallBooleanMethod(this.JvmHandle, global::android.graphics.Path._isEmpty3548);
else
return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.graphics.Path.staticClass, global::android.graphics.Path._isEmpty3548);
}
internal static global::MonoJavaBridge.MethodId _transform3549;
public virtual void transform(android.graphics.Matrix arg0, android.graphics.Path arg1)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.graphics.Path._transform3549, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.graphics.Path.staticClass, global::android.graphics.Path._transform3549, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
internal static global::MonoJavaBridge.MethodId _transform3550;
public virtual void transform(android.graphics.Matrix arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.graphics.Path._transform3550, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.graphics.Path.staticClass, global::android.graphics.Path._transform3550, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _close3551;
public virtual void close()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.graphics.Path._close3551);
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.graphics.Path.staticClass, global::android.graphics.Path._close3551);
}
internal static global::MonoJavaBridge.MethodId _set3552;
public virtual void set(android.graphics.Path arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.graphics.Path._set3552, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.graphics.Path.staticClass, global::android.graphics.Path._set3552, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _reset3553;
public virtual void reset()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.graphics.Path._reset3553);
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.graphics.Path.staticClass, global::android.graphics.Path._reset3553);
}
internal static global::MonoJavaBridge.MethodId _rewind3554;
public virtual void rewind()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.graphics.Path._rewind3554);
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.graphics.Path.staticClass, global::android.graphics.Path._rewind3554);
}
internal static global::MonoJavaBridge.MethodId _isRect3555;
public virtual bool isRect(android.graphics.RectF arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallBooleanMethod(this.JvmHandle, global::android.graphics.Path._isRect3555, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.graphics.Path.staticClass, global::android.graphics.Path._isRect3555, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _getFillType3556;
public virtual global::android.graphics.Path.FillType getFillType()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::android.graphics.Path._getFillType3556)) as android.graphics.Path.FillType;
else
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.graphics.Path.staticClass, global::android.graphics.Path._getFillType3556)) as android.graphics.Path.FillType;
}
internal static global::MonoJavaBridge.MethodId _setFillType3557;
public virtual void setFillType(android.graphics.Path.FillType arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.graphics.Path._setFillType3557, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.graphics.Path.staticClass, global::android.graphics.Path._setFillType3557, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _isInverseFillType3558;
public virtual bool isInverseFillType()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallBooleanMethod(this.JvmHandle, global::android.graphics.Path._isInverseFillType3558);
else
return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.graphics.Path.staticClass, global::android.graphics.Path._isInverseFillType3558);
}
internal static global::MonoJavaBridge.MethodId _toggleInverseFillType3559;
public virtual void toggleInverseFillType()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.graphics.Path._toggleInverseFillType3559);
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.graphics.Path.staticClass, global::android.graphics.Path._toggleInverseFillType3559);
}
internal static global::MonoJavaBridge.MethodId _computeBounds3560;
public virtual void computeBounds(android.graphics.RectF arg0, bool arg1)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.graphics.Path._computeBounds3560, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.graphics.Path.staticClass, global::android.graphics.Path._computeBounds3560, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
internal static global::MonoJavaBridge.MethodId _incReserve3561;
public virtual void incReserve(int arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.graphics.Path._incReserve3561, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.graphics.Path.staticClass, global::android.graphics.Path._incReserve3561, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _moveTo3562;
public virtual void moveTo(float arg0, float arg1)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.graphics.Path._moveTo3562, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.graphics.Path.staticClass, global::android.graphics.Path._moveTo3562, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
internal static global::MonoJavaBridge.MethodId _rMoveTo3563;
public virtual void rMoveTo(float arg0, float arg1)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.graphics.Path._rMoveTo3563, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.graphics.Path.staticClass, global::android.graphics.Path._rMoveTo3563, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
internal static global::MonoJavaBridge.MethodId _lineTo3564;
public virtual void lineTo(float arg0, float arg1)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.graphics.Path._lineTo3564, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.graphics.Path.staticClass, global::android.graphics.Path._lineTo3564, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
internal static global::MonoJavaBridge.MethodId _rLineTo3565;
public virtual void rLineTo(float arg0, float arg1)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.graphics.Path._rLineTo3565, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.graphics.Path.staticClass, global::android.graphics.Path._rLineTo3565, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
internal static global::MonoJavaBridge.MethodId _quadTo3566;
public virtual void quadTo(float arg0, float arg1, float arg2, float arg3)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.graphics.Path._quadTo3566, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.graphics.Path.staticClass, global::android.graphics.Path._quadTo3566, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3));
}
internal static global::MonoJavaBridge.MethodId _rQuadTo3567;
public virtual void rQuadTo(float arg0, float arg1, float arg2, float arg3)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.graphics.Path._rQuadTo3567, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.graphics.Path.staticClass, global::android.graphics.Path._rQuadTo3567, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3));
}
internal static global::MonoJavaBridge.MethodId _cubicTo3568;
public virtual void cubicTo(float arg0, float arg1, float arg2, float arg3, float arg4, float arg5)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.graphics.Path._cubicTo3568, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg4), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg5));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.graphics.Path.staticClass, global::android.graphics.Path._cubicTo3568, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg4), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg5));
}
internal static global::MonoJavaBridge.MethodId _rCubicTo3569;
public virtual void rCubicTo(float arg0, float arg1, float arg2, float arg3, float arg4, float arg5)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.graphics.Path._rCubicTo3569, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg4), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg5));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.graphics.Path.staticClass, global::android.graphics.Path._rCubicTo3569, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg4), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg5));
}
internal static global::MonoJavaBridge.MethodId _arcTo3570;
public virtual void arcTo(android.graphics.RectF arg0, float arg1, float arg2, bool arg3)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.graphics.Path._arcTo3570, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.graphics.Path.staticClass, global::android.graphics.Path._arcTo3570, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3));
}
internal static global::MonoJavaBridge.MethodId _arcTo3571;
public virtual void arcTo(android.graphics.RectF arg0, float arg1, float arg2)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.graphics.Path._arcTo3571, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.graphics.Path.staticClass, global::android.graphics.Path._arcTo3571, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2));
}
internal static global::MonoJavaBridge.MethodId _addRect3572;
public virtual void addRect(float arg0, float arg1, float arg2, float arg3, android.graphics.Path.Direction arg4)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.graphics.Path._addRect3572, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg4));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.graphics.Path.staticClass, global::android.graphics.Path._addRect3572, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg4));
}
internal static global::MonoJavaBridge.MethodId _addRect3573;
public virtual void addRect(android.graphics.RectF arg0, android.graphics.Path.Direction arg1)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.graphics.Path._addRect3573, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.graphics.Path.staticClass, global::android.graphics.Path._addRect3573, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
internal static global::MonoJavaBridge.MethodId _addOval3574;
public virtual void addOval(android.graphics.RectF arg0, android.graphics.Path.Direction arg1)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.graphics.Path._addOval3574, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.graphics.Path.staticClass, global::android.graphics.Path._addOval3574, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
internal static global::MonoJavaBridge.MethodId _addCircle3575;
public virtual void addCircle(float arg0, float arg1, float arg2, android.graphics.Path.Direction arg3)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.graphics.Path._addCircle3575, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.graphics.Path.staticClass, global::android.graphics.Path._addCircle3575, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3));
}
internal static global::MonoJavaBridge.MethodId _addArc3576;
public virtual void addArc(android.graphics.RectF arg0, float arg1, float arg2)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.graphics.Path._addArc3576, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.graphics.Path.staticClass, global::android.graphics.Path._addArc3576, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2));
}
internal static global::MonoJavaBridge.MethodId _addRoundRect3577;
public virtual void addRoundRect(android.graphics.RectF arg0, float arg1, float arg2, android.graphics.Path.Direction arg3)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.graphics.Path._addRoundRect3577, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.graphics.Path.staticClass, global::android.graphics.Path._addRoundRect3577, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3));
}
internal static global::MonoJavaBridge.MethodId _addRoundRect3578;
public virtual void addRoundRect(android.graphics.RectF arg0, float[] arg1, android.graphics.Path.Direction arg2)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.graphics.Path._addRoundRect3578, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.graphics.Path.staticClass, global::android.graphics.Path._addRoundRect3578, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2));
}
internal static global::MonoJavaBridge.MethodId _addPath3579;
public virtual void addPath(android.graphics.Path arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.graphics.Path._addPath3579, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.graphics.Path.staticClass, global::android.graphics.Path._addPath3579, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _addPath3580;
public virtual void addPath(android.graphics.Path arg0, android.graphics.Matrix arg1)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.graphics.Path._addPath3580, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.graphics.Path.staticClass, global::android.graphics.Path._addPath3580, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
internal static global::MonoJavaBridge.MethodId _addPath3581;
public virtual void addPath(android.graphics.Path arg0, float arg1, float arg2)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.graphics.Path._addPath3581, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.graphics.Path.staticClass, global::android.graphics.Path._addPath3581, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2));
}
internal static global::MonoJavaBridge.MethodId _setLastPoint3582;
public virtual void setLastPoint(float arg0, float arg1)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.graphics.Path._setLastPoint3582, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.graphics.Path.staticClass, global::android.graphics.Path._setLastPoint3582, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
internal static global::MonoJavaBridge.MethodId _Path3583;
public Path() : base(global::MonoJavaBridge.JNIEnv.ThreadEnv)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.graphics.Path.staticClass, global::android.graphics.Path._Path3583);
Init(@__env, handle);
}
internal static global::MonoJavaBridge.MethodId _Path3584;
public Path(android.graphics.Path arg0) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.graphics.Path.staticClass, global::android.graphics.Path._Path3584, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
Init(@__env, handle);
}
private static void InitJNI()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::android.graphics.Path.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/graphics/Path"));
global::android.graphics.Path._finalize3545 = @__env.GetMethodIDNoThrow(global::android.graphics.Path.staticClass, "finalize", "()V");
global::android.graphics.Path._offset3546 = @__env.GetMethodIDNoThrow(global::android.graphics.Path.staticClass, "offset", "(FFLandroid/graphics/Path;)V");
global::android.graphics.Path._offset3547 = @__env.GetMethodIDNoThrow(global::android.graphics.Path.staticClass, "offset", "(FF)V");
global::android.graphics.Path._isEmpty3548 = @__env.GetMethodIDNoThrow(global::android.graphics.Path.staticClass, "isEmpty", "()Z");
global::android.graphics.Path._transform3549 = @__env.GetMethodIDNoThrow(global::android.graphics.Path.staticClass, "transform", "(Landroid/graphics/Matrix;Landroid/graphics/Path;)V");
global::android.graphics.Path._transform3550 = @__env.GetMethodIDNoThrow(global::android.graphics.Path.staticClass, "transform", "(Landroid/graphics/Matrix;)V");
global::android.graphics.Path._close3551 = @__env.GetMethodIDNoThrow(global::android.graphics.Path.staticClass, "close", "()V");
global::android.graphics.Path._set3552 = @__env.GetMethodIDNoThrow(global::android.graphics.Path.staticClass, "set", "(Landroid/graphics/Path;)V");
global::android.graphics.Path._reset3553 = @__env.GetMethodIDNoThrow(global::android.graphics.Path.staticClass, "reset", "()V");
global::android.graphics.Path._rewind3554 = @__env.GetMethodIDNoThrow(global::android.graphics.Path.staticClass, "rewind", "()V");
global::android.graphics.Path._isRect3555 = @__env.GetMethodIDNoThrow(global::android.graphics.Path.staticClass, "isRect", "(Landroid/graphics/RectF;)Z");
global::android.graphics.Path._getFillType3556 = @__env.GetMethodIDNoThrow(global::android.graphics.Path.staticClass, "getFillType", "()Landroid/graphics/Path$FillType;");
global::android.graphics.Path._setFillType3557 = @__env.GetMethodIDNoThrow(global::android.graphics.Path.staticClass, "setFillType", "(Landroid/graphics/Path$FillType;)V");
global::android.graphics.Path._isInverseFillType3558 = @__env.GetMethodIDNoThrow(global::android.graphics.Path.staticClass, "isInverseFillType", "()Z");
global::android.graphics.Path._toggleInverseFillType3559 = @__env.GetMethodIDNoThrow(global::android.graphics.Path.staticClass, "toggleInverseFillType", "()V");
global::android.graphics.Path._computeBounds3560 = @__env.GetMethodIDNoThrow(global::android.graphics.Path.staticClass, "computeBounds", "(Landroid/graphics/RectF;Z)V");
global::android.graphics.Path._incReserve3561 = @__env.GetMethodIDNoThrow(global::android.graphics.Path.staticClass, "incReserve", "(I)V");
global::android.graphics.Path._moveTo3562 = @__env.GetMethodIDNoThrow(global::android.graphics.Path.staticClass, "moveTo", "(FF)V");
global::android.graphics.Path._rMoveTo3563 = @__env.GetMethodIDNoThrow(global::android.graphics.Path.staticClass, "rMoveTo", "(FF)V");
global::android.graphics.Path._lineTo3564 = @__env.GetMethodIDNoThrow(global::android.graphics.Path.staticClass, "lineTo", "(FF)V");
global::android.graphics.Path._rLineTo3565 = @__env.GetMethodIDNoThrow(global::android.graphics.Path.staticClass, "rLineTo", "(FF)V");
global::android.graphics.Path._quadTo3566 = @__env.GetMethodIDNoThrow(global::android.graphics.Path.staticClass, "quadTo", "(FFFF)V");
global::android.graphics.Path._rQuadTo3567 = @__env.GetMethodIDNoThrow(global::android.graphics.Path.staticClass, "rQuadTo", "(FFFF)V");
global::android.graphics.Path._cubicTo3568 = @__env.GetMethodIDNoThrow(global::android.graphics.Path.staticClass, "cubicTo", "(FFFFFF)V");
global::android.graphics.Path._rCubicTo3569 = @__env.GetMethodIDNoThrow(global::android.graphics.Path.staticClass, "rCubicTo", "(FFFFFF)V");
global::android.graphics.Path._arcTo3570 = @__env.GetMethodIDNoThrow(global::android.graphics.Path.staticClass, "arcTo", "(Landroid/graphics/RectF;FFZ)V");
global::android.graphics.Path._arcTo3571 = @__env.GetMethodIDNoThrow(global::android.graphics.Path.staticClass, "arcTo", "(Landroid/graphics/RectF;FF)V");
global::android.graphics.Path._addRect3572 = @__env.GetMethodIDNoThrow(global::android.graphics.Path.staticClass, "addRect", "(FFFFLandroid/graphics/Path$Direction;)V");
global::android.graphics.Path._addRect3573 = @__env.GetMethodIDNoThrow(global::android.graphics.Path.staticClass, "addRect", "(Landroid/graphics/RectF;Landroid/graphics/Path$Direction;)V");
global::android.graphics.Path._addOval3574 = @__env.GetMethodIDNoThrow(global::android.graphics.Path.staticClass, "addOval", "(Landroid/graphics/RectF;Landroid/graphics/Path$Direction;)V");
global::android.graphics.Path._addCircle3575 = @__env.GetMethodIDNoThrow(global::android.graphics.Path.staticClass, "addCircle", "(FFFLandroid/graphics/Path$Direction;)V");
global::android.graphics.Path._addArc3576 = @__env.GetMethodIDNoThrow(global::android.graphics.Path.staticClass, "addArc", "(Landroid/graphics/RectF;FF)V");
global::android.graphics.Path._addRoundRect3577 = @__env.GetMethodIDNoThrow(global::android.graphics.Path.staticClass, "addRoundRect", "(Landroid/graphics/RectF;FFLandroid/graphics/Path$Direction;)V");
global::android.graphics.Path._addRoundRect3578 = @__env.GetMethodIDNoThrow(global::android.graphics.Path.staticClass, "addRoundRect", "(Landroid/graphics/RectF;[FLandroid/graphics/Path$Direction;)V");
global::android.graphics.Path._addPath3579 = @__env.GetMethodIDNoThrow(global::android.graphics.Path.staticClass, "addPath", "(Landroid/graphics/Path;)V");
global::android.graphics.Path._addPath3580 = @__env.GetMethodIDNoThrow(global::android.graphics.Path.staticClass, "addPath", "(Landroid/graphics/Path;Landroid/graphics/Matrix;)V");
global::android.graphics.Path._addPath3581 = @__env.GetMethodIDNoThrow(global::android.graphics.Path.staticClass, "addPath", "(Landroid/graphics/Path;FF)V");
global::android.graphics.Path._setLastPoint3582 = @__env.GetMethodIDNoThrow(global::android.graphics.Path.staticClass, "setLastPoint", "(FF)V");
global::android.graphics.Path._Path3583 = @__env.GetMethodIDNoThrow(global::android.graphics.Path.staticClass, "<init>", "()V");
global::android.graphics.Path._Path3584 = @__env.GetMethodIDNoThrow(global::android.graphics.Path.staticClass, "<init>", "(Landroid/graphics/Path;)V");
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.Net;
using System.Text;
namespace System.Web.Util
{
internal static class HttpEncoder
{
private static void AppendCharAsUnicodeJavaScript(StringBuilder builder, char c)
{
builder.Append("\\u");
builder.Append(((int)c).ToString("x4", CultureInfo.InvariantCulture));
}
private static bool CharRequiresJavaScriptEncoding(char c) =>
c < 0x20 // control chars always have to be encoded
|| c == '\"' // chars which must be encoded per JSON spec
|| c == '\\'
|| c == '\'' // HTML-sensitive chars encoded for safety
|| c == '<'
|| c == '>'
|| (c == '&')
|| c == '\u0085' // newline chars (see Unicode 6.2, Table 5-1 [http://www.unicode.org/versions/Unicode6.2.0/ch05.pdf]) have to be encoded
|| c == '\u2028'
|| c == '\u2029';
[return: NotNullIfNotNull("value")]
internal static string? HtmlAttributeEncode(string? value)
{
if (string.IsNullOrEmpty(value))
{
return value;
}
// Don't create string writer if we don't have nothing to encode
int pos = IndexOfHtmlAttributeEncodingChars(value, 0);
if (pos == -1)
{
return value;
}
StringWriter writer = new StringWriter(CultureInfo.InvariantCulture);
HtmlAttributeEncode(value, writer);
return writer.ToString();
}
internal static void HtmlAttributeEncode(string? value, TextWriter output)
{
if (value == null)
{
return;
}
if (output == null)
{
throw new ArgumentNullException(nameof(output));
}
HtmlAttributeEncodeInternal(value, output);
}
private static unsafe void HtmlAttributeEncodeInternal(string s, TextWriter output)
{
int index = IndexOfHtmlAttributeEncodingChars(s, 0);
if (index == -1)
{
output.Write(s);
}
else
{
int cch = s.Length - index;
fixed (char* str = s)
{
char* pch = str;
while (index-- > 0)
{
output.Write(*pch++);
}
while (cch-- > 0)
{
char ch = *pch++;
if (ch <= '<')
{
switch (ch)
{
case '<':
output.Write("<");
break;
case '"':
output.Write(""");
break;
case '\'':
output.Write("'");
break;
case '&':
output.Write("&");
break;
default:
output.Write(ch);
break;
}
}
else
{
output.Write(ch);
}
}
}
}
}
[return: NotNullIfNotNull("value")]
internal static string? HtmlDecode(string? value) => string.IsNullOrEmpty(value) ? value : WebUtility.HtmlDecode(value);
internal static void HtmlDecode(string? value, TextWriter output)
{
if (output == null)
{
throw new ArgumentNullException(nameof(output));
}
output.Write(WebUtility.HtmlDecode(value));
}
[return: NotNullIfNotNull("value")]
internal static string? HtmlEncode(string? value) => string.IsNullOrEmpty(value) ? value : WebUtility.HtmlEncode(value);
internal static void HtmlEncode(string? value, TextWriter output)
{
if (output == null)
{
throw new ArgumentNullException(nameof(output));
}
output.Write(WebUtility.HtmlEncode(value));
}
private static unsafe int IndexOfHtmlAttributeEncodingChars(string s, int startPos)
{
Debug.Assert(0 <= startPos && startPos <= s.Length, "0 <= startPos && startPos <= s.Length");
int cch = s.Length - startPos;
fixed (char* str = s)
{
for (char* pch = &str[startPos]; cch > 0; pch++, cch--)
{
char ch = *pch;
if (ch <= '<')
{
switch (ch)
{
case '<':
case '"':
case '\'':
case '&':
return s.Length - cch;
}
}
}
}
return -1;
}
private static bool IsNonAsciiByte(byte b) => b >= 0x7F || b < 0x20;
internal static string JavaScriptStringEncode(string? value)
{
if (string.IsNullOrEmpty(value))
{
return string.Empty;
}
StringBuilder? b = null;
int startIndex = 0;
int count = 0;
for (int i = 0; i < value.Length; i++)
{
char c = value[i];
// Append the unhandled characters (that do not require special treament)
// to the string builder when special characters are detected.
if (CharRequiresJavaScriptEncoding(c))
{
if (b == null)
{
b = new StringBuilder(value.Length + 5);
}
if (count > 0)
{
b.Append(value, startIndex, count);
}
startIndex = i + 1;
count = 0;
switch (c)
{
case '\r':
b.Append("\\r");
break;
case '\t':
b.Append("\\t");
break;
case '\"':
b.Append("\\\"");
break;
case '\\':
b.Append("\\\\");
break;
case '\n':
b.Append("\\n");
break;
case '\b':
b.Append("\\b");
break;
case '\f':
b.Append("\\f");
break;
default:
AppendCharAsUnicodeJavaScript(b, c);
break;
}
}
else
{
count++;
}
}
if (b == null)
{
return value;
}
if (count > 0)
{
b.Append(value, startIndex, count);
}
return b.ToString();
}
[return: NotNullIfNotNull("bytes")]
internal static byte[]? UrlDecode(byte[]? bytes, int offset, int count)
{
if (!ValidateUrlEncodingParameters(bytes, offset, count))
{
return null;
}
int decodedBytesCount = 0;
byte[] decodedBytes = new byte[count];
for (int i = 0; i < count; i++)
{
int pos = offset + i;
byte b = bytes[pos];
if (b == '+')
{
b = (byte)' ';
}
else if (b == '%' && i < count - 2)
{
int h1 = HttpEncoderUtility.HexToInt((char)bytes[pos + 1]);
int h2 = HttpEncoderUtility.HexToInt((char)bytes[pos + 2]);
if (h1 >= 0 && h2 >= 0)
{
// valid 2 hex chars
b = (byte)((h1 << 4) | h2);
i += 2;
}
}
decodedBytes[decodedBytesCount++] = b;
}
if (decodedBytesCount < decodedBytes.Length)
{
byte[] newDecodedBytes = new byte[decodedBytesCount];
Array.Copy(decodedBytes, 0, newDecodedBytes, 0, decodedBytesCount);
decodedBytes = newDecodedBytes;
}
return decodedBytes;
}
[return: NotNullIfNotNull("bytes")]
internal static string? UrlDecode(byte[]? bytes, int offset, int count, Encoding encoding)
{
if (!ValidateUrlEncodingParameters(bytes, offset, count))
{
return null;
}
UrlDecoder helper = new UrlDecoder(count, encoding);
// go through the bytes collapsing %XX and %uXXXX and appending
// each byte as byte, with exception of %uXXXX constructs that
// are appended as chars
for (int i = 0; i < count; i++)
{
int pos = offset + i;
byte b = bytes[pos];
// The code assumes that + and % cannot be in multibyte sequence
if (b == '+')
{
b = (byte)' ';
}
else if (b == '%' && i < count - 2)
{
if (bytes[pos + 1] == 'u' && i < count - 5)
{
int h1 = HttpEncoderUtility.HexToInt((char)bytes[pos + 2]);
int h2 = HttpEncoderUtility.HexToInt((char)bytes[pos + 3]);
int h3 = HttpEncoderUtility.HexToInt((char)bytes[pos + 4]);
int h4 = HttpEncoderUtility.HexToInt((char)bytes[pos + 5]);
if (h1 >= 0 && h2 >= 0 && h3 >= 0 && h4 >= 0)
{ // valid 4 hex chars
char ch = (char)((h1 << 12) | (h2 << 8) | (h3 << 4) | h4);
i += 5;
// don't add as byte
helper.AddChar(ch);
continue;
}
}
else
{
int h1 = HttpEncoderUtility.HexToInt((char)bytes[pos + 1]);
int h2 = HttpEncoderUtility.HexToInt((char)bytes[pos + 2]);
if (h1 >= 0 && h2 >= 0)
{ // valid 2 hex chars
b = (byte)((h1 << 4) | h2);
i += 2;
}
}
}
helper.AddByte(b);
}
return Utf16StringValidator.ValidateString(helper.GetString());
}
[return: NotNullIfNotNull("value")]
internal static string? UrlDecode(string? value, Encoding encoding)
{
if (value == null)
{
return null;
}
int count = value.Length;
UrlDecoder helper = new UrlDecoder(count, encoding);
// go through the string's chars collapsing %XX and %uXXXX and
// appending each char as char, with exception of %XX constructs
// that are appended as bytes
for (int pos = 0; pos < count; pos++)
{
char ch = value[pos];
if (ch == '+')
{
ch = ' ';
}
else if (ch == '%' && pos < count - 2)
{
if (value[pos + 1] == 'u' && pos < count - 5)
{
int h1 = HttpEncoderUtility.HexToInt(value[pos + 2]);
int h2 = HttpEncoderUtility.HexToInt(value[pos + 3]);
int h3 = HttpEncoderUtility.HexToInt(value[pos + 4]);
int h4 = HttpEncoderUtility.HexToInt(value[pos + 5]);
if (h1 >= 0 && h2 >= 0 && h3 >= 0 && h4 >= 0)
{ // valid 4 hex chars
ch = (char)((h1 << 12) | (h2 << 8) | (h3 << 4) | h4);
pos += 5;
// only add as char
helper.AddChar(ch);
continue;
}
}
else
{
int h1 = HttpEncoderUtility.HexToInt(value[pos + 1]);
int h2 = HttpEncoderUtility.HexToInt(value[pos + 2]);
if (h1 >= 0 && h2 >= 0)
{ // valid 2 hex chars
byte b = (byte)((h1 << 4) | h2);
pos += 2;
// don't add as char
helper.AddByte(b);
continue;
}
}
}
if ((ch & 0xFF80) == 0)
{
helper.AddByte((byte)ch); // 7 bit have to go as bytes because of Unicode
}
else
{
helper.AddChar(ch);
}
}
return Utf16StringValidator.ValidateString(helper.GetString());
}
[return: NotNullIfNotNull("bytes")]
internal static byte[]? UrlEncode(byte[]? bytes, int offset, int count, bool alwaysCreateNewReturnValue)
{
byte[]? encoded = UrlEncode(bytes, offset, count);
return (alwaysCreateNewReturnValue && (encoded != null) && (encoded == bytes))
? (byte[])encoded.Clone()
: encoded;
}
[return: NotNullIfNotNull("bytes")]
private static byte[]? UrlEncode(byte[]? bytes, int offset, int count)
{
if (!ValidateUrlEncodingParameters(bytes, offset, count))
{
return null;
}
int cSpaces = 0;
int cUnsafe = 0;
// count them first
for (int i = 0; i < count; i++)
{
char ch = (char)bytes[offset + i];
if (ch == ' ')
{
cSpaces++;
}
else if (!HttpEncoderUtility.IsUrlSafeChar(ch))
{
cUnsafe++;
}
}
// nothing to expand?
if (cSpaces == 0 && cUnsafe == 0)
{
// DevDiv 912606: respect "offset" and "count"
if (0 == offset && bytes.Length == count)
{
return bytes;
}
else
{
byte[] subarray = new byte[count];
Buffer.BlockCopy(bytes, offset, subarray, 0, count);
return subarray;
}
}
// expand not 'safe' characters into %XX, spaces to +s
byte[] expandedBytes = new byte[count + cUnsafe * 2];
int pos = 0;
for (int i = 0; i < count; i++)
{
byte b = bytes[offset + i];
char ch = (char)b;
if (HttpEncoderUtility.IsUrlSafeChar(ch))
{
expandedBytes[pos++] = b;
}
else if (ch == ' ')
{
expandedBytes[pos++] = (byte)'+';
}
else
{
expandedBytes[pos++] = (byte)'%';
expandedBytes[pos++] = (byte)HttpEncoderUtility.IntToHex((b >> 4) & 0xf);
expandedBytes[pos++] = (byte)HttpEncoderUtility.IntToHex(b & 0x0f);
}
}
return expandedBytes;
}
// Helper to encode the non-ASCII url characters only
private static string UrlEncodeNonAscii(string str, Encoding e)
{
Debug.Assert(!string.IsNullOrEmpty(str));
Debug.Assert(e != null);
byte[] bytes = e.GetBytes(str);
byte[] encodedBytes = UrlEncodeNonAscii(bytes, 0, bytes.Length);
return Encoding.ASCII.GetString(encodedBytes);
}
private static byte[] UrlEncodeNonAscii(byte[] bytes, int offset, int count)
{
int cNonAscii = 0;
// count them first
for (int i = 0; i < count; i++)
{
if (IsNonAsciiByte(bytes[offset + i]))
{
cNonAscii++;
}
}
// nothing to expand?
if (cNonAscii == 0)
{
return bytes;
}
// expand not 'safe' characters into %XX, spaces to +s
byte[] expandedBytes = new byte[count + cNonAscii * 2];
int pos = 0;
for (int i = 0; i < count; i++)
{
byte b = bytes[offset + i];
if (IsNonAsciiByte(b))
{
expandedBytes[pos++] = (byte)'%';
expandedBytes[pos++] = (byte)HttpEncoderUtility.IntToHex((b >> 4) & 0xf);
expandedBytes[pos++] = (byte)HttpEncoderUtility.IntToHex(b & 0x0f);
}
else
{
expandedBytes[pos++] = b;
}
}
return expandedBytes;
}
[Obsolete("This method produces non-standards-compliant output and has interoperability issues. The preferred alternative is UrlEncode(*).")]
[return: NotNullIfNotNull("value")]
internal static string? UrlEncodeUnicode(string? value)
{
if (value == null)
{
return null;
}
int l = value.Length;
StringBuilder sb = new StringBuilder(l);
for (int i = 0; i < l; i++)
{
char ch = value[i];
if ((ch & 0xff80) == 0)
{ // 7 bit?
if (HttpEncoderUtility.IsUrlSafeChar(ch))
{
sb.Append(ch);
}
else if (ch == ' ')
{
sb.Append('+');
}
else
{
sb.Append('%');
sb.Append(HttpEncoderUtility.IntToHex((ch >> 4) & 0xf));
sb.Append(HttpEncoderUtility.IntToHex((ch) & 0xf));
}
}
else
{ // arbitrary Unicode?
sb.Append("%u");
sb.Append(HttpEncoderUtility.IntToHex((ch >> 12) & 0xf));
sb.Append(HttpEncoderUtility.IntToHex((ch >> 8) & 0xf));
sb.Append(HttpEncoderUtility.IntToHex((ch >> 4) & 0xf));
sb.Append(HttpEncoderUtility.IntToHex((ch) & 0xf));
}
}
return sb.ToString();
}
[SuppressMessage("Microsoft.Design", "CA1055:UriReturnValuesShouldNotBeStrings",
Justification = "Does not represent an entire URL, just a portion.")]
[return: NotNullIfNotNull("value")]
internal static string? UrlPathEncode(string? value)
{
if (string.IsNullOrEmpty(value))
{
return value;
}
string? schemeAndAuthority;
string? path;
string? queryAndFragment;
if (!UriUtil.TrySplitUriForPathEncode(value, out schemeAndAuthority, out path, out queryAndFragment))
{
// If the value is not a valid url, we treat it as a relative url.
// We don't need to extract query string from the url since UrlPathEncode()
// does not encode query string.
schemeAndAuthority = null;
path = value;
queryAndFragment = null;
}
return schemeAndAuthority + UrlPathEncodeImpl(path) + queryAndFragment;
}
// This is the original UrlPathEncode(string)
[SuppressMessage("Microsoft.Design", "CA1055:UriReturnValuesShouldNotBeStrings",
Justification = "Does not represent an entire URL, just a portion.")]
private static string UrlPathEncodeImpl(string value)
{
if (string.IsNullOrEmpty(value))
{
return value;
}
// recurse in case there is a query string
int i = value.IndexOf('?');
if (i >= 0)
{
return string.Concat(UrlPathEncodeImpl(value.Substring(0, i)), value.AsSpan(i));
}
// encode DBCS characters and spaces only
return HttpEncoderUtility.UrlEncodeSpaces(UrlEncodeNonAscii(value, Encoding.UTF8));
}
private static bool ValidateUrlEncodingParameters([NotNullWhen(true)] byte[]? bytes, int offset, int count)
{
if (bytes == null && count == 0)
{
return false;
}
if (bytes == null)
{
throw new ArgumentNullException(nameof(bytes));
}
if (offset < 0 || offset > bytes.Length)
{
throw new ArgumentOutOfRangeException(nameof(offset));
}
if (count < 0 || offset + count > bytes.Length)
{
throw new ArgumentOutOfRangeException(nameof(count));
}
return true;
}
// Internal class to facilitate URL decoding -- keeps char buffer and byte buffer, allows appending of either chars or bytes
private class UrlDecoder
{
private readonly int _bufferSize;
// Accumulate characters in a special array
private int _numChars;
private readonly char[] _charBuffer;
// Accumulate bytes for decoding into characters in a special array
private int _numBytes;
private byte[]? _byteBuffer;
// Encoding to convert chars to bytes
private readonly Encoding _encoding;
private void FlushBytes()
{
if (_numBytes > 0)
{
Debug.Assert(_byteBuffer != null);
_numChars += _encoding.GetChars(_byteBuffer, 0, _numBytes, _charBuffer, _numChars);
_numBytes = 0;
}
}
internal UrlDecoder(int bufferSize, Encoding encoding)
{
_bufferSize = bufferSize;
_encoding = encoding;
_charBuffer = new char[bufferSize];
// byte buffer created on demand
}
internal void AddChar(char ch)
{
if (_numBytes > 0)
{
FlushBytes();
}
_charBuffer[_numChars++] = ch;
}
internal void AddByte(byte b)
{
// if there are no pending bytes treat 7 bit bytes as characters
// this optimization is temp disable as it doesn't work for some encodings
/*
if (_numBytes == 0 && ((b & 0x80) == 0)) {
AddChar((char)b);
}
else
*/
{
if (_byteBuffer == null)
{
_byteBuffer = new byte[_bufferSize];
}
_byteBuffer[_numBytes++] = b;
}
}
internal string GetString()
{
if (_numBytes > 0)
{
FlushBytes();
}
return _numChars > 0 ? new string(_charBuffer, 0, _numChars) : "";
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.ComponentModel;
using System.Data.Common;
using System.Data.ProviderBase;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Runtime.InteropServices;
using System.Text;
namespace System.Data.OleDb
{
using SysTx = Transactions;
// wraps the OLEDB IDBInitialize interface which represents a connection
// Notes about connection pooling
// 1. Connection pooling isn't supported on Win95
// 2. Only happens if we use the IDataInitialize or IDBPromptInitialize interfaces
// it won't happen if you directly create the provider and set its properties
// 3. First call on IDBInitialize must be Initialize, can't QI for any other interfaces before that
[DefaultEvent("InfoMessage")]
public sealed partial class OleDbConnection : DbConnection, ICloneable, IDbConnection
{
private static readonly object EventInfoMessage = new object();
public OleDbConnection(string connectionString) : this()
{
ConnectionString = connectionString;
}
private OleDbConnection(OleDbConnection connection) : this()
{ // Clone
CopyFrom(connection);
}
[
DefaultValue(""),
#pragma warning disable 618 // ignore obsolete warning about RecommendedAsConfigurable to use SettingsBindableAttribute
RecommendedAsConfigurable(true),
#pragma warning restore 618
SettingsBindable(true),
RefreshProperties(RefreshProperties.All),
]
public override string ConnectionString
{
get
{
return ConnectionString_Get();
}
set
{
ConnectionString_Set(value);
}
}
private OleDbConnectionString OleDbConnectionStringValue
{
get { return (OleDbConnectionString)ConnectionOptions; }
}
[
DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden),
]
public override int ConnectionTimeout
{
get
{
object value = null;
if (IsOpen)
{
value = GetDataSourceValue(OleDbPropertySetGuid.DBInit, ODB.DBPROP_INIT_TIMEOUT);
}
else
{
OleDbConnectionString constr = this.OleDbConnectionStringValue;
value = (null != constr) ? constr.ConnectTimeout : ADP.DefaultConnectionTimeout;
}
if (null != value)
{
return Convert.ToInt32(value, CultureInfo.InvariantCulture);
}
else
{
return ADP.DefaultConnectionTimeout;
}
}
}
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public override string Database
{
get
{
OleDbConnectionString constr = (OleDbConnectionString)UserConnectionOptions;
object value = (null != constr) ? constr.InitialCatalog : string.Empty;
if ((null != value) && !((string)value).StartsWith(DbConnectionOptions.DataDirectory, StringComparison.OrdinalIgnoreCase))
{
OleDbConnectionInternal connection = GetOpenConnection();
if (null != connection)
{
if (connection.HasSession)
{
value = GetDataSourceValue(OleDbPropertySetGuid.DataSource, ODB.DBPROP_CURRENTCATALOG);
}
else
{
value = GetDataSourceValue(OleDbPropertySetGuid.DBInit, ODB.DBPROP_INIT_CATALOG);
}
}
else
{
constr = this.OleDbConnectionStringValue;
value = (null != constr) ? constr.InitialCatalog : string.Empty;
}
}
return Convert.ToString(value, CultureInfo.InvariantCulture);
}
}
[
Browsable(true)
]
public override string DataSource
{
get
{
OleDbConnectionString constr = (OleDbConnectionString)UserConnectionOptions;
object value = (null != constr) ? constr.DataSource : string.Empty;
if ((null != value) && !((string)value).StartsWith(DbConnectionOptions.DataDirectory, StringComparison.OrdinalIgnoreCase))
{
if (IsOpen)
{
value = GetDataSourceValue(OleDbPropertySetGuid.DBInit, ODB.DBPROP_INIT_DATASOURCE);
if ((null == value) || ((value is string) && (0 == (value as string).Length)))
{
value = GetDataSourceValue(OleDbPropertySetGuid.DataSourceInfo, ODB.DBPROP_DATASOURCENAME);
}
}
else
{
constr = this.OleDbConnectionStringValue;
value = (null != constr) ? constr.DataSource : string.Empty;
}
}
return Convert.ToString(value, CultureInfo.InvariantCulture);
}
}
internal bool IsOpen
{
get { return (null != GetOpenConnection()); }
}
internal OleDbTransaction LocalTransaction
{
set
{
OleDbConnectionInternal openConnection = GetOpenConnection();
if (null != openConnection)
{
openConnection.LocalTransaction = value;
}
}
}
[
Browsable(true),
DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden),
]
public string Provider
{
get
{
OleDbConnectionString constr = this.OleDbConnectionStringValue;
string value = ((null != constr) ? constr.ConvertValueToString(ODB.Provider, null) : null);
return ((null != value) ? value : string.Empty);
}
}
internal OleDbConnectionPoolGroupProviderInfo ProviderInfo
{
get
{
return (OleDbConnectionPoolGroupProviderInfo)PoolGroup.ProviderInfo;
}
}
public override string ServerVersion
{
get
{
return InnerConnection.ServerVersion;
}
}
[
Browsable(false),
DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden),
// ResDescriptionAttribute(SR.DbConnection_State),
]
public override ConnectionState State
{
get
{
return InnerConnection.State;
}
}
[EditorBrowsable(EditorBrowsableState.Advanced)]
public void ResetState()
{
if (IsOpen)
{
object value = GetDataSourcePropertyValue(OleDbPropertySetGuid.DataSourceInfo, ODB.DBPROP_CONNECTIONSTATUS);
if (value is int)
{
int connectionStatus = (int)value;
switch (connectionStatus)
{
case ODB.DBPROPVAL_CS_UNINITIALIZED: // provider closed on us
case ODB.DBPROPVAL_CS_COMMUNICATIONFAILURE: // broken connection
GetOpenConnection().DoomThisConnection();
NotifyWeakReference(OleDbReferenceCollection.Canceling);
Close();
break;
case ODB.DBPROPVAL_CS_INITIALIZED: // everything is okay
break;
default: // have to assume everything is okay
Debug.Assert(false, "Unknown 'Connection Status' value " + connectionStatus.ToString("G", CultureInfo.InvariantCulture));
break;
}
}
}
}
public event OleDbInfoMessageEventHandler InfoMessage
{
add
{
Events.AddHandler(EventInfoMessage, value);
}
remove
{
Events.RemoveHandler(EventInfoMessage, value);
}
}
internal UnsafeNativeMethods.ICommandText ICommandText()
{
Debug.Assert(null != GetOpenConnection(), "ICommandText closed");
return GetOpenConnection().ICommandText();
}
private IDBPropertiesWrapper IDBProperties()
{
Debug.Assert(null != GetOpenConnection(), "IDBProperties closed");
return GetOpenConnection().IDBProperties();
}
internal IOpenRowsetWrapper IOpenRowset()
{
Debug.Assert(null != GetOpenConnection(), "IOpenRowset closed");
return GetOpenConnection().IOpenRowset();
}
internal int SqlSupport()
{
Debug.Assert(null != this.OleDbConnectionStringValue, "no OleDbConnectionString SqlSupport");
return this.OleDbConnectionStringValue.GetSqlSupport(this);
}
internal bool SupportMultipleResults()
{
Debug.Assert(null != this.OleDbConnectionStringValue, "no OleDbConnectionString SupportMultipleResults");
return this.OleDbConnectionStringValue.GetSupportMultipleResults(this);
}
internal bool SupportIRow(OleDbCommand cmd)
{
Debug.Assert(null != this.OleDbConnectionStringValue, "no OleDbConnectionString SupportIRow");
return this.OleDbConnectionStringValue.GetSupportIRow(this, cmd);
}
internal int QuotedIdentifierCase()
{
Debug.Assert(null != this.OleDbConnectionStringValue, "no OleDbConnectionString QuotedIdentifierCase");
int quotedIdentifierCase;
object value = GetDataSourcePropertyValue(OleDbPropertySetGuid.DataSourceInfo, ODB.DBPROP_QUOTEDIDENTIFIERCASE);
if (value is int)
{// not OleDbPropertyStatus
quotedIdentifierCase = (int)value;
}
else
{
quotedIdentifierCase = -1;
}
return quotedIdentifierCase;
}
internal bool ForceNewConnection { get { return false; } set {; } }
public new OleDbTransaction BeginTransaction()
{
return BeginTransaction(IsolationLevel.Unspecified);
}
public new OleDbTransaction BeginTransaction(IsolationLevel isolationLevel)
{
return (OleDbTransaction)InnerConnection.BeginTransaction(isolationLevel);
}
public override void ChangeDatabase(string value)
{
CheckStateOpen(ADP.ChangeDatabase);
if ((null == value) || (0 == value.Trim().Length))
{
throw ADP.EmptyDatabaseName();
}
SetDataSourcePropertyValue(OleDbPropertySetGuid.DataSource, ODB.DBPROP_CURRENTCATALOG, ODB.Current_Catalog, true, value);
}
internal void CheckStateOpen(string method)
{
ConnectionState state = State;
if (ConnectionState.Open != state)
{
throw ADP.OpenConnectionRequired(method, state);
}
}
object ICloneable.Clone()
{
OleDbConnection clone = new OleDbConnection(this);
return clone;
}
public override void Close()
{
InnerConnection.CloseConnection(this, ConnectionFactory);
// does not require GC.KeepAlive(this) because of OnStateChange
}
public new OleDbCommand CreateCommand()
{
return new OleDbCommand("", this);
}
private void DisposeMe(bool disposing)
{
if (disposing)
{ // release mananged objects
if (DesignMode)
{
// release the object pool in design-mode so that
// native MDAC can be properly released during shutdown
OleDbConnection.ReleaseObjectPool();
}
}
}
// suppress this message - we cannot use SafeHandle here.
[SuppressMessage("Microsoft.Reliability", "CA2004:RemoveCallsToGCKeepAlive")]
protected override DbTransaction BeginDbTransaction(IsolationLevel isolationLevel)
{
DbTransaction transaction = InnerConnection.BeginTransaction(isolationLevel);
// InnerConnection doesn't maintain a ref on the outer connection (this) and
// subsequently leaves open the possibility that the outer connection could be GC'ed before the DbTransaction
// is fully hooked up (leaving a DbTransaction with a null connection property). Ensure that this is reachable
// until the completion of BeginTransaction with KeepAlive
GC.KeepAlive(this);
return transaction;
}
internal object GetDataSourcePropertyValue(Guid propertySet, int propertyID)
{
OleDbConnectionInternal connection = GetOpenConnection();
return connection.GetDataSourcePropertyValue(propertySet, propertyID);
}
internal object GetDataSourceValue(Guid propertySet, int propertyID)
{
object value = GetDataSourcePropertyValue(propertySet, propertyID);
if ((value is OleDbPropertyStatus) || Convert.IsDBNull(value))
{
value = null;
}
return value;
}
private OleDbConnectionInternal GetOpenConnection()
{
DbConnectionInternal innerConnection = InnerConnection;
return (innerConnection as OleDbConnectionInternal);
}
internal void GetLiteralQuotes(string method, out string quotePrefix, out string quoteSuffix)
{
CheckStateOpen(method);
OleDbConnectionPoolGroupProviderInfo info = ProviderInfo;
if (info.HasQuoteFix)
{
quotePrefix = info.QuotePrefix;
quoteSuffix = info.QuoteSuffix;
}
else
{
OleDbConnectionInternal connection = GetOpenConnection();
quotePrefix = connection.GetLiteralInfo(ODB.DBLITERAL_QUOTE_PREFIX);
quoteSuffix = connection.GetLiteralInfo(ODB.DBLITERAL_QUOTE_SUFFIX);
if (null == quotePrefix)
{
quotePrefix = "";
}
if (null == quoteSuffix)
{
quoteSuffix = quotePrefix;
}
info.SetQuoteFix(quotePrefix, quoteSuffix);
}
}
public DataTable GetOleDbSchemaTable(Guid schema, object[] restrictions)
{
CheckStateOpen(ADP.GetOleDbSchemaTable);
OleDbConnectionInternal connection = GetOpenConnection();
if (OleDbSchemaGuid.DbInfoLiterals == schema)
{
if ((null == restrictions) || (0 == restrictions.Length))
{
return connection.BuildInfoLiterals();
}
throw ODB.InvalidRestrictionsDbInfoLiteral("restrictions");
}
else if (OleDbSchemaGuid.SchemaGuids == schema)
{
if ((null == restrictions) || (0 == restrictions.Length))
{
return connection.BuildSchemaGuids();
}
throw ODB.InvalidRestrictionsSchemaGuids("restrictions");
}
else if (OleDbSchemaGuid.DbInfoKeywords == schema)
{
if ((null == restrictions) || (0 == restrictions.Length))
{
return connection.BuildInfoKeywords();
}
throw ODB.InvalidRestrictionsDbInfoKeywords("restrictions");
}
if (connection.SupportSchemaRowset(schema))
{
return connection.GetSchemaRowset(schema, restrictions);
}
else
{
using (IDBSchemaRowsetWrapper wrapper = connection.IDBSchemaRowset())
{
if (null == wrapper.Value)
{
throw ODB.SchemaRowsetsNotSupported(Provider);
}
}
throw ODB.NotSupportedSchemaTable(schema, this);
}
}
internal DataTable GetSchemaRowset(Guid schema, object[] restrictions)
{
Debug.Assert(null != GetOpenConnection(), "GetSchemaRowset closed");
return GetOpenConnection().GetSchemaRowset(schema, restrictions);
}
internal bool HasLiveReader(OleDbCommand cmd)
{
bool result = false;
OleDbConnectionInternal openConnection = GetOpenConnection();
if (null != openConnection)
{
result = openConnection.HasLiveReader(cmd);
}
return result;
}
internal void OnInfoMessage(UnsafeNativeMethods.IErrorInfo errorInfo, OleDbHResult errorCode)
{
OleDbInfoMessageEventHandler handler = (OleDbInfoMessageEventHandler)Events[EventInfoMessage];
if (null != handler)
{
try
{
OleDbException exception = OleDbException.CreateException(errorInfo, errorCode, null);
OleDbInfoMessageEventArgs e = new OleDbInfoMessageEventArgs(exception);
handler(this, e);
}
catch (Exception e)
{ // eat the exception
// UNDONE - should not be catching all exceptions!!!
if (!ADP.IsCatchableOrSecurityExceptionType(e))
{
throw;
}
ADP.TraceExceptionWithoutRethrow(e);
}
}
#if DEBUG
else
{
OleDbException exception = OleDbException.CreateException(errorInfo, errorCode, null);
}
#endif
}
public override void Open()
{
InnerConnection.OpenConnection(this, ConnectionFactory);
// need to manually enlist in some cases, because
// native OLE DB doesn't know about SysTx transactions.
if ((0 != (ODB.DBPROPVAL_OS_TXNENLISTMENT & ((OleDbConnectionString)(this.ConnectionOptions)).OleDbServices))
&& ADP.NeedManualEnlistment())
{
GetOpenConnection().EnlistTransactionInternal(SysTx.Transaction.Current);
}
}
internal void SetDataSourcePropertyValue(Guid propertySet, int propertyID, string description, bool required, object value)
{
CheckStateOpen(ADP.SetProperties);
OleDbHResult hr;
using (IDBPropertiesWrapper idbProperties = IDBProperties())
{
using (DBPropSet propSet = DBPropSet.CreateProperty(propertySet, propertyID, required, value))
{
hr = idbProperties.Value.SetProperties(propSet.PropertySetCount, propSet);
if (hr < 0)
{
Exception e = OleDbConnection.ProcessResults(hr, null, this);
if (OleDbHResult.DB_E_ERRORSOCCURRED == hr)
{
StringBuilder builder = new StringBuilder();
Debug.Assert(1 == propSet.PropertySetCount, "too many PropertySets");
tagDBPROP[] dbprops = propSet.GetPropertySet(0, out propertySet);
Debug.Assert(1 == dbprops.Length, "too many Properties");
ODB.PropsetSetFailure(builder, description, dbprops[0].dwStatus);
e = ODB.PropsetSetFailure(builder.ToString(), e);
}
if (null != e)
{
throw e;
}
}
else
{
SafeNativeMethods.Wrapper.ClearErrorInfo();
}
}
}
}
internal bool SupportSchemaRowset(Guid schema)
{
return GetOpenConnection().SupportSchemaRowset(schema);
}
internal OleDbTransaction ValidateTransaction(OleDbTransaction transaction, string method)
{
return GetOpenConnection().ValidateTransaction(transaction, method);
}
internal static Exception ProcessResults(OleDbHResult hresult, OleDbConnection connection, object src)
{
if ((0 <= (int)hresult) && ((null == connection) || (null == connection.Events[EventInfoMessage])))
{
SafeNativeMethods.Wrapper.ClearErrorInfo();
return null;
}
// ErrorInfo object is to be checked regardless the hresult returned by the function called
Exception e = null;
UnsafeNativeMethods.IErrorInfo errorInfo = null;
OleDbHResult hr = UnsafeNativeMethods.GetErrorInfo(0, out errorInfo); // 0 - IErrorInfo exists, 1 - no IErrorInfo
if ((OleDbHResult.S_OK == hr) && (null != errorInfo))
{
if (hresult < 0)
{
// UNDONE: if authentication failed - throw a unique exception object type
//if (/*OLEDB_Error.DB_SEC_E_AUTH_FAILED*/unchecked((int)0x80040E4D) == hr) {
//}
//else if (/*OLEDB_Error.DB_E_CANCELED*/unchecked((int)0x80040E4E) == hr) {
//}
// else {
e = OleDbException.CreateException(errorInfo, hresult, null);
//}
if (OleDbHResult.DB_E_OBJECTOPEN == hresult)
{
e = ADP.OpenReaderExists(e);
}
ResetState(connection);
}
else if (null != connection)
{
connection.OnInfoMessage(errorInfo, hresult);
}
else
{
}
Marshal.ReleaseComObject(errorInfo);
}
else if (0 < hresult)
{
// @devnote: OnInfoMessage with no ErrorInfo
}
else if ((int)hresult < 0)
{
e = ODB.NoErrorInformation((null != connection) ? connection.Provider : null, hresult, null); // OleDbException
ResetState(connection);
}
if (null != e)
{
ADP.TraceExceptionAsReturnValue(e);
}
return e;
}
// @devnote: should be multithread safe
public static void ReleaseObjectPool()
{
OleDbConnectionString.ReleaseObjectPool();
OleDbConnectionInternal.ReleaseObjectPool();
OleDbConnectionFactory.SingletonInstance.ClearAllPools();
}
private static void ResetState(OleDbConnection connection)
{
if (null != connection)
{
connection.ResetState();
}
}
}
}
| |
//
// Authors:
// Duane Wandless
// Miguel de Icaza
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.Drawing;
using System.Runtime.InteropServices;
using MonoMac.ObjCRuntime;
using MonoMac.Foundation;
using MonoMac.CoreFoundation;
using MonoMac.CoreGraphics;
namespace MonoMac.ImageIO {
public enum CGImageSourceStatus {
Complete = 0,
Incomplete = -1,
ReadingHeader = -2,
UnknownType = -3,
InvalidData = -4,
UnexpectedEOF = -5,
}
public class CGImageOptions {
static IntPtr kTypeIdentifierHint;
static IntPtr kShouldCache;
static IntPtr kShouldAllowFloat;
static void Init ()
{
if (kTypeIdentifierHint != IntPtr.Zero)
return;
IntPtr lib = Dlfcn.dlopen (Constants.ImageIOLibrary, 0);
kTypeIdentifierHint = Dlfcn.GetIntPtr (lib, "kCGImageSourceTypeIdentifierHint");
kShouldCache = Dlfcn.GetIntPtr (lib, "kCGImageSourceShouldCache");
kShouldAllowFloat = Dlfcn.GetIntPtr (lib, "kCGImageSourceShouldAllowFloat");
Dlfcn.dlclose (lib);
}
public string BestGuessTypeIdentifier { get; set; }
public bool ShouldCache { get; set; }
public bool ShouldAllowFloat { get; set; }
internal virtual NSMutableDictionary ToDictionary ()
{
Init ();
var dict = new NSMutableDictionary ();
IntPtr thandle = CFBoolean.TrueObject.Handle;
if (BestGuessTypeIdentifier != null)
dict.LowlevelSetObject (new NSString (BestGuessTypeIdentifier), kTypeIdentifierHint);
if (ShouldCache)
dict.LowlevelSetObject (thandle, kShouldCache);
if (ShouldAllowFloat)
dict.LowlevelSetObject (thandle, kShouldAllowFloat);
return dict;
}
}
public class CGImageThumbnailOptions : CGImageOptions {
static IntPtr kCreateThumbnailFromImageIfAbsent;
static IntPtr kCreateThumbnailFromImageAlways;
static IntPtr kThumbnailMaxPixelSize;
static IntPtr kCreateThumbnailWithTransform;
static void Init ()
{
if (kCreateThumbnailWithTransform != IntPtr.Zero)
return;
IntPtr lib = Dlfcn.dlopen (Constants.ImageIOLibrary, 0);
kCreateThumbnailFromImageIfAbsent = Dlfcn.GetIntPtr (lib, "kCGImageSourceCreateThumbnailFromImageIfAbsent");
kCreateThumbnailFromImageAlways = Dlfcn.GetIntPtr (lib, "kCGImageSourceCreateThumbnailFromImageAlways");
kThumbnailMaxPixelSize = Dlfcn.GetIntPtr (lib, "kCGImageSourceThumbnailMaxPixelSize");
kCreateThumbnailWithTransform = Dlfcn.GetIntPtr (lib, "kCGImageSourceCreateThumbnailWithTransform");
Dlfcn.dlclose (lib);
}
public bool CreateThumbnailFromImageIfAbsent { get; set; }
public bool CreateThumbnailFromImageAlways { get; set; }
public int? MaxPixelSize { get; set; }
public bool CreateThumbnailWithTransform { get; set; }
internal override NSMutableDictionary ToDictionary ()
{
Init ();
var dict = base.ToDictionary ();
IntPtr thandle = CFBoolean.TrueObject.Handle;
if (CreateThumbnailFromImageIfAbsent)
dict.LowlevelSetObject (thandle, kCreateThumbnailFromImageIfAbsent);
if (CreateThumbnailFromImageAlways)
dict.LowlevelSetObject (thandle, kCreateThumbnailFromImageAlways);
if (MaxPixelSize.HasValue)
dict.LowlevelSetObject (new NSNumber (MaxPixelSize.Value), kThumbnailMaxPixelSize);
if (CreateThumbnailWithTransform)
dict.LowlevelSetObject (thandle, kCreateThumbnailWithTransform);
return dict;
}
}
public class CGImageSource : INativeObject, IDisposable
{
[DllImport (Constants.ImageIOLibrary, EntryPoint="CGImageSourceGetTypeID")]
public extern static int GetTypeID ();
[DllImport (Constants.ImageIOLibrary)]
extern static IntPtr CGImageSourceCopyTypeIdentifiers ();
public static string [] TypeIdentifiers {
get {
return NSArray.StringArrayFromHandle (CGImageSourceCopyTypeIdentifiers ());
}
}
internal IntPtr handle;
// invoked by marshallers
internal CGImageSource (IntPtr handle) : this (handle, false)
{
this.handle = handle;
}
[Preserve (Conditional=true)]
internal CGImageSource (IntPtr handle, bool owns)
{
this.handle = handle;
if (!owns)
CFObject.CFRetain (handle);
}
~CGImageSource ()
{
Dispose (false);
}
public void Dispose ()
{
Dispose (true);
GC.SuppressFinalize (this);
}
public IntPtr Handle {
get { return handle; }
}
protected virtual void Dispose (bool disposing)
{
if (handle != IntPtr.Zero){
CFObject.CFRelease (handle);
handle = IntPtr.Zero;
}
}
[DllImport (Constants.ImageIOLibrary)]
extern static IntPtr CGImageSourceCreateWithURL(IntPtr url, IntPtr options);
public static CGImageSource FromUrl (NSUrl url)
{
return FromUrl (url, null);
}
public static CGImageSource FromUrl (NSUrl url, CGImageOptions options)
{
if (url == null)
throw new ArgumentNullException ("url");
var dict = options == null ? null : options.ToDictionary ();
var ret = new CGImageSource (CGImageSourceCreateWithURL (url.Handle, dict == null ? IntPtr.Zero : dict.Handle), true);
dict.Dispose ();
return ret;
}
[DllImport (Constants.ImageIOLibrary)]
extern static IntPtr CGImageSourceCreateWithDataProvider (IntPtr provider, IntPtr options);
public static CGImageSource FromDataProvider (CGDataProvider provider)
{
return FromDataProvider (provider, null);
}
public static CGImageSource FromDataProvider (CGDataProvider provider, CGImageOptions options)
{
if (provider == null)
throw new ArgumentNullException ("provider");
var dict = options == null ? null : options.ToDictionary ();
var ret = new CGImageSource (CGImageSourceCreateWithDataProvider (provider.Handle, dict == null ? IntPtr.Zero : dict.Handle), true);
dict.Dispose ();
return ret;
}
[DllImport (Constants.ImageIOLibrary)]
extern static IntPtr CGImageSourceCreateWithData (IntPtr data, IntPtr options);
public static CGImageSource FromData (NSData data)
{
return FromData (data, null);
}
public static CGImageSource FromData (NSData data, CGImageOptions options)
{
if (data == null)
throw new ArgumentNullException ("data");
var dict = options == null ? null : options.ToDictionary ();
var ret = new CGImageSource (CGImageSourceCreateWithData (data.Handle, dict == null ? IntPtr.Zero : dict.Handle), true);
dict.Dispose ();
return ret;
}
[DllImport (Constants.ImageIOLibrary)]
extern static IntPtr CGImageSourceGetType (IntPtr handle);
public string TypeIdentifier {
get {
return NSString.FromHandle (CGImageSourceGetType (handle));
}
}
[DllImport (Constants.ImageIOLibrary)]
extern static int CGImageSourceGetCount (IntPtr handle);
public int ImageCount {
get {
return CGImageSourceGetCount (handle);
}
}
[DllImport (Constants.ImageIOLibrary)]
extern static IntPtr CGImageSourceCopyProperties (IntPtr handle, IntPtr dictOptions);
public NSDictionary CopyProperties (NSDictionary dict)
{
return new NSDictionary (CGImageSourceCopyProperties (handle, dict == null ? IntPtr.Zero : dict.Handle));
}
[DllImport (Constants.ImageIOLibrary)]
extern static IntPtr CGImageSourceCopyPropertiesAtIndex (IntPtr handle, int idx, IntPtr dictOptions);
public NSDictionary CopyProperties (NSDictionary dict, int imageIndex)
{
return new NSDictionary (CGImageSourceCopyPropertiesAtIndex (handle, imageIndex, dict == null ? IntPtr.Zero : dict.Handle));
}
//
// TODO: we could introduce a strongly typed CopyProperties to more easily examine properties
// instead of a Dictionary like Obj-C does
//
[DllImport (Constants.ImageIOLibrary)]
extern static IntPtr CGImageSourceCreateImageAtIndex(IntPtr isrc, int index, IntPtr options);
public CGImage CreateImage (int index, CGImageOptions options)
{
var dict = options == null ? null : options.ToDictionary ();
var ret = CGImageSourceCreateImageAtIndex (handle, index, dict == null ? IntPtr.Zero : dict.Handle);
dict.Dispose ();
return new CGImage (ret, true);
}
[DllImport (Constants.ImageIOLibrary)]
extern static IntPtr CGImageSourceCreateThumbnailAtIndex (IntPtr isrc, int index, IntPtr options);
public CGImage CreateThumbnail (int index, CGImageThumbnailOptions options)
{
var dict = options == null ? null : options.ToDictionary ();
var ret = CGImageSourceCreateThumbnailAtIndex (handle, index, dict == null ? IntPtr.Zero : dict.Handle);
dict.Dispose ();
return new CGImage (ret, true);
}
[DllImport (Constants.ImageIOLibrary)]
extern static IntPtr CGImageSourceCreateIncremental (IntPtr options);
public static CGImageSource CreateIncremental (CGImageOptions options)
{
var dict = options == null ? null : options.ToDictionary ();
var ret = new CGImageSource (CGImageSourceCreateIncremental (dict == null ? IntPtr.Zero : dict.Handle), true);
dict.Dispose ();
return ret;
}
[DllImport (Constants.ImageIOLibrary)]
extern static void CGImageSourceUpdateData (IntPtr handle, IntPtr data, bool final);
public void UpdateData (NSData data, bool final)
{
if (data == null)
throw new ArgumentNullException ("data");
CGImageSourceUpdateData (handle, data.Handle, final);
}
[DllImport (Constants.ImageIOLibrary)]
extern static void CGImageSourceUpdateDataProvider (IntPtr handle, IntPtr dataProvider);
public void UpdateDataProvider (CGDataProvider provider)
{
if (provider == null)
throw new ArgumentNullException ("provider");
CGImageSourceUpdateDataProvider (handle, provider.Handle);
}
[DllImport (Constants.ImageIOLibrary)]
extern static CGImageSourceStatus CGImageSourceGetStatus (IntPtr handle);
public CGImageSourceStatus GetStatus ()
{
return CGImageSourceGetStatus (handle);
}
[DllImport (Constants.ImageIOLibrary)]
extern static CGImageSourceStatus CGImageSourceGetStatusAtIndex (IntPtr handle, int idx);
public CGImageSourceStatus GetStatus (int index)
{
return CGImageSourceGetStatusAtIndex (handle, index);
}
}
}
| |
using System;
partial class formDC : System.Windows.Forms.Form
{
/// <summary>
/// Designer variable used to keep track of non-visual components.
/// </summary>
private System.ComponentModel.IContainer components;
/// <summary>
/// Disposes resources used by the form.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing) {
if (components != null) {
components.Dispose();
}
}
base.Dispose(disposing);
}
/// <summary>
/// This method is required for Windows Forms designer support.
/// Do not change the method contents inside the source code editor. The Forms designer might
/// not be able to load this method if it was changed manually.
/// </summary>
private void InitializeComponent()
{
this.textboxBuyAmount = new System.Windows.Forms.TextBox();
this.textboxBuyPrice = new System.Windows.Forms.TextBox();
this.buttonClose = new System.Windows.Forms.Button();
this.buttonBuy = new System.Windows.Forms.Button();
this.labelBuyAmount = new System.Windows.Forms.Label();
this.labelBuyPrice = new System.Windows.Forms.Label();
this.comboboxFamily = new System.Windows.Forms.ComboBox();
this.comboboxName = new System.Windows.Forms.ComboBox();
this.comboboxCategory = new System.Windows.Forms.ComboBox();
this.comboboxGenre = new System.Windows.Forms.ComboBox();
this.labelGenre = new System.Windows.Forms.Label();
this.labelFamily = new System.Windows.Forms.Label();
this.labelCategory = new System.Windows.Forms.Label();
this.labelName = new System.Windows.Forms.Label();
this.groupboxItemInfo = new System.Windows.Forms.GroupBox();
this.labelItemBrandDisplay = new System.Windows.Forms.Label();
this.labelItemBrand = new System.Windows.Forms.Label();
this.labelItemCategoryDisplay = new System.Windows.Forms.Label();
this.labelItemCategory = new System.Windows.Forms.Label();
this.labelItemItemNameDisplay = new System.Windows.Forms.Label();
this.labelItemItemName = new System.Windows.Forms.Label();
this.labelItemCompanyDisplay = new System.Windows.Forms.Label();
this.labelItemCompany = new System.Windows.Forms.Label();
this.labelItemGenreDisplay = new System.Windows.Forms.Label();
this.labelItemGenre = new System.Windows.Forms.Label();
this.labelItemFamilyDisplay = new System.Windows.Forms.Label();
this.labelInfoFamily = new System.Windows.Forms.Label();
this.textboxPriceTotal = new System.Windows.Forms.TextBox();
this.labelPriceTotal = new System.Windows.Forms.Label();
this.groupboxStatistics = new System.Windows.Forms.GroupBox();
this.labelStatisticsItemTierDisplay = new System.Windows.Forms.Label();
this.labelStatisticsItemTier = new System.Windows.Forms.Label();
this.labelStatisticsPopularityDisplay = new System.Windows.Forms.Label();
this.labelStatisticsPopularity = new System.Windows.Forms.Label();
this.labelStatisticsBaseWorthDisplay = new System.Windows.Forms.Label();
this.labelStatisticsBaseWorth = new System.Windows.Forms.Label();
this.labelStatisticsRarityDisplay = new System.Windows.Forms.Label();
this.labelStatisticsRarity = new System.Windows.Forms.Label();
this.labelStatisticsQualityDisplay = new System.Windows.Forms.Label();
this.labelStatisticsQuality = new System.Windows.Forms.Label();
this.groupboxVarious = new System.Windows.Forms.GroupBox();
this.labelVariousDescriptionDisplay = new System.Windows.Forms.Label();
this.labelVariousDescription = new System.Windows.Forms.Label();
this.labelVariousPicturePathDisplay = new System.Windows.Forms.Label();
this.labelVariousPicturePath = new System.Windows.Forms.Label();
this.groupboxItemInfo.SuspendLayout();
this.groupboxStatistics.SuspendLayout();
this.groupboxVarious.SuspendLayout();
this.SuspendLayout();
//
//textboxBuyAmount
//
this.textboxBuyAmount.Location = new System.Drawing.Point(181, 325);
this.textboxBuyAmount.Name = "textboxBuyAmount";
this.textboxBuyAmount.Size = new System.Drawing.Size(95, 20);
this.textboxBuyAmount.TabIndex = 72;
this.textboxBuyAmount.TextChanged += this.textboxBuyAmount_TextChanged;
//
//textboxBuyPrice
//
this.textboxBuyPrice.Location = new System.Drawing.Point(12, 325);
this.textboxBuyPrice.Name = "textboxBuyPrice";
this.textboxBuyPrice.ReadOnly = true;
this.textboxBuyPrice.Size = new System.Drawing.Size(163, 20);
this.textboxBuyPrice.TabIndex = 71;
//
//buttonClose
//
this.buttonClose.Location = new System.Drawing.Point(199, 351);
this.buttonClose.Name = "buttonClose";
this.buttonClose.Size = new System.Drawing.Size(178, 25);
this.buttonClose.TabIndex = 67;
this.buttonClose.Text = "Close";
this.buttonClose.UseVisualStyleBackColor = true;
this.buttonClose.Click += this.buttonClose_Click;
//
//buttonBuy
//
this.buttonBuy.Location = new System.Drawing.Point(12, 351);
this.buttonBuy.Name = "buttonBuy";
this.buttonBuy.Size = new System.Drawing.Size(181, 25);
this.buttonBuy.TabIndex = 66;
this.buttonBuy.Text = "Buy";
this.buttonBuy.UseVisualStyleBackColor = true;
this.buttonBuy.Click += this.buttonBuy_Click;
//
//labelBuyAmount
//
this.labelBuyAmount.AutoSize = true;
this.labelBuyAmount.Location = new System.Drawing.Point(181, 309);
this.labelBuyAmount.Name = "labelBuyAmount";
this.labelBuyAmount.Size = new System.Drawing.Size(75, 13);
this.labelBuyAmount.TabIndex = 65;
this.labelBuyAmount.Text = "Amount to buy";
//
//labelBuyPrice
//
this.labelBuyPrice.AutoSize = true;
this.labelBuyPrice.Location = new System.Drawing.Point(12, 309);
this.labelBuyPrice.Name = "labelBuyPrice";
this.labelBuyPrice.Size = new System.Drawing.Size(146, 13);
this.labelBuyPrice.TabIndex = 62;
this.labelBuyPrice.Text = "Current Buy Price -50%\\+25%";
//
//comboboxFamily
//
this.comboboxFamily.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.comboboxFamily.FormattingEnabled = true;
this.comboboxFamily.Location = new System.Drawing.Point(12, 25);
this.comboboxFamily.Name = "comboboxFamily";
this.comboboxFamily.Size = new System.Drawing.Size(365, 21);
this.comboboxFamily.TabIndex = 49;
this.comboboxFamily.SelectedIndexChanged += this.comboboxFamily_SelectedIndexChanged;
//
//comboboxName
//
this.comboboxName.DropDownStyle = System.Windows.Forms.ComboBoxStyle.Simple;
this.comboboxName.FormattingEnabled = true;
this.comboboxName.Location = new System.Drawing.Point(383, 25);
this.comboboxName.Name = "comboboxName";
this.comboboxName.Size = new System.Drawing.Size(365, 359);
this.comboboxName.TabIndex = 54;
this.comboboxName.SelectedIndexChanged += this.comboboxName_SelectedIndexChanged;
//
//comboboxCategory
//
this.comboboxCategory.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.comboboxCategory.FormattingEnabled = true;
this.comboboxCategory.Location = new System.Drawing.Point(12, 65);
this.comboboxCategory.Name = "comboboxCategory";
this.comboboxCategory.Size = new System.Drawing.Size(365, 21);
this.comboboxCategory.TabIndex = 50;
this.comboboxCategory.SelectedIndexChanged += this.comboboxCategory_SelectedIndexChanged;
//
//comboboxGenre
//
this.comboboxGenre.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.comboboxGenre.FormattingEnabled = true;
this.comboboxGenre.Location = new System.Drawing.Point(12, 105);
this.comboboxGenre.Name = "comboboxGenre";
this.comboboxGenre.Size = new System.Drawing.Size(365, 21);
this.comboboxGenre.TabIndex = 52;
this.comboboxGenre.SelectedIndexChanged += this.comboboxGenre_SelectedIndexChanged;
//
//labelGenre
//
this.labelGenre.AutoSize = true;
this.labelGenre.Location = new System.Drawing.Point(12, 89);
this.labelGenre.Name = "labelGenre";
this.labelGenre.Size = new System.Drawing.Size(36, 13);
this.labelGenre.TabIndex = 60;
this.labelGenre.Text = "Genre";
//
//labelFamily
//
this.labelFamily.AutoSize = true;
this.labelFamily.Location = new System.Drawing.Point(12, 9);
this.labelFamily.Name = "labelFamily";
this.labelFamily.Size = new System.Drawing.Size(36, 13);
this.labelFamily.TabIndex = 59;
this.labelFamily.Text = "Family";
//
//labelCategory
//
this.labelCategory.AutoSize = true;
this.labelCategory.Location = new System.Drawing.Point(12, 49);
this.labelCategory.Name = "labelCategory";
this.labelCategory.Size = new System.Drawing.Size(49, 13);
this.labelCategory.TabIndex = 57;
this.labelCategory.Text = "Category";
//
//labelName
//
this.labelName.AutoSize = true;
this.labelName.Location = new System.Drawing.Point(380, 9);
this.labelName.Name = "labelName";
this.labelName.Size = new System.Drawing.Size(100, 13);
this.labelName.TabIndex = 55;
this.labelName.Text = "Product Name/Title";
//
//groupboxItemInfo
//
this.groupboxItemInfo.Controls.Add(this.labelItemBrandDisplay);
this.groupboxItemInfo.Controls.Add(this.labelItemBrand);
this.groupboxItemInfo.Controls.Add(this.labelItemCategoryDisplay);
this.groupboxItemInfo.Controls.Add(this.labelItemCategory);
this.groupboxItemInfo.Controls.Add(this.labelItemItemNameDisplay);
this.groupboxItemInfo.Controls.Add(this.labelItemItemName);
this.groupboxItemInfo.Controls.Add(this.labelItemCompanyDisplay);
this.groupboxItemInfo.Controls.Add(this.labelItemCompany);
this.groupboxItemInfo.Controls.Add(this.labelItemGenreDisplay);
this.groupboxItemInfo.Controls.Add(this.labelItemGenre);
this.groupboxItemInfo.Controls.Add(this.labelItemFamilyDisplay);
this.groupboxItemInfo.Controls.Add(this.labelInfoFamily);
this.groupboxItemInfo.Location = new System.Drawing.Point(12, 132);
this.groupboxItemInfo.Name = "groupboxItemInfo";
this.groupboxItemInfo.Size = new System.Drawing.Size(177, 118);
this.groupboxItemInfo.TabIndex = 73;
this.groupboxItemInfo.TabStop = false;
this.groupboxItemInfo.Text = "Item Information";
//
//labelItemBrandDisplay
//
this.labelItemBrandDisplay.AutoSize = true;
this.labelItemBrandDisplay.Location = new System.Drawing.Point(112, 84);
this.labelItemBrandDisplay.Name = "labelItemBrandDisplay";
this.labelItemBrandDisplay.Size = new System.Drawing.Size(0, 13);
this.labelItemBrandDisplay.TabIndex = 64;
//
//labelItemBrand
//
this.labelItemBrand.AutoSize = true;
this.labelItemBrand.Location = new System.Drawing.Point(6, 84);
this.labelItemBrand.Name = "labelItemBrand";
this.labelItemBrand.Size = new System.Drawing.Size(38, 13);
this.labelItemBrand.TabIndex = 64;
this.labelItemBrand.Text = "Brand:";
//
//labelItemCategoryDisplay
//
this.labelItemCategoryDisplay.AutoSize = true;
this.labelItemCategoryDisplay.Location = new System.Drawing.Point(112, 33);
this.labelItemCategoryDisplay.Name = "labelItemCategoryDisplay";
this.labelItemCategoryDisplay.Size = new System.Drawing.Size(0, 13);
this.labelItemCategoryDisplay.TabIndex = 64;
//
//labelItemCategory
//
this.labelItemCategory.AutoSize = true;
this.labelItemCategory.Location = new System.Drawing.Point(6, 33);
this.labelItemCategory.Name = "labelItemCategory";
this.labelItemCategory.Size = new System.Drawing.Size(52, 13);
this.labelItemCategory.TabIndex = 64;
this.labelItemCategory.Text = "Category:";
//
//labelItemItemNameDisplay
//
this.labelItemItemNameDisplay.AutoSize = true;
this.labelItemItemNameDisplay.Location = new System.Drawing.Point(112, 101);
this.labelItemItemNameDisplay.Name = "labelItemItemNameDisplay";
this.labelItemItemNameDisplay.Size = new System.Drawing.Size(0, 13);
this.labelItemItemNameDisplay.TabIndex = 63;
//
//labelItemItemName
//
this.labelItemItemName.AutoSize = true;
this.labelItemItemName.Location = new System.Drawing.Point(6, 101);
this.labelItemItemName.Name = "labelItemItemName";
this.labelItemItemName.Size = new System.Drawing.Size(61, 13);
this.labelItemItemName.TabIndex = 63;
this.labelItemItemName.Text = "Item Name:";
//
//labelItemCompanyDisplay
//
this.labelItemCompanyDisplay.AutoSize = true;
this.labelItemCompanyDisplay.Location = new System.Drawing.Point(112, 67);
this.labelItemCompanyDisplay.Name = "labelItemCompanyDisplay";
this.labelItemCompanyDisplay.Size = new System.Drawing.Size(0, 13);
this.labelItemCompanyDisplay.TabIndex = 61;
//
//labelItemCompany
//
this.labelItemCompany.AutoSize = true;
this.labelItemCompany.Location = new System.Drawing.Point(6, 67);
this.labelItemCompany.Name = "labelItemCompany";
this.labelItemCompany.Size = new System.Drawing.Size(54, 13);
this.labelItemCompany.TabIndex = 61;
this.labelItemCompany.Text = "Company:";
//
//labelItemGenreDisplay
//
this.labelItemGenreDisplay.AutoSize = true;
this.labelItemGenreDisplay.Location = new System.Drawing.Point(112, 50);
this.labelItemGenreDisplay.Name = "labelItemGenreDisplay";
this.labelItemGenreDisplay.Size = new System.Drawing.Size(0, 13);
this.labelItemGenreDisplay.TabIndex = 63;
//
//labelItemGenre
//
this.labelItemGenre.AutoSize = true;
this.labelItemGenre.Location = new System.Drawing.Point(6, 50);
this.labelItemGenre.Name = "labelItemGenre";
this.labelItemGenre.Size = new System.Drawing.Size(39, 13);
this.labelItemGenre.TabIndex = 63;
this.labelItemGenre.Text = "Genre:";
//
//labelItemFamilyDisplay
//
this.labelItemFamilyDisplay.AutoSize = true;
this.labelItemFamilyDisplay.Location = new System.Drawing.Point(112, 16);
this.labelItemFamilyDisplay.Name = "labelItemFamilyDisplay";
this.labelItemFamilyDisplay.Size = new System.Drawing.Size(0, 13);
this.labelItemFamilyDisplay.TabIndex = 61;
//
//labelInfoFamily
//
this.labelInfoFamily.AutoSize = true;
this.labelInfoFamily.Location = new System.Drawing.Point(6, 16);
this.labelInfoFamily.Name = "labelInfoFamily";
this.labelInfoFamily.Size = new System.Drawing.Size(39, 13);
this.labelInfoFamily.TabIndex = 61;
this.labelInfoFamily.Text = "Family:";
//
//textboxPriceTotal
//
this.textboxPriceTotal.Location = new System.Drawing.Point(282, 325);
this.textboxPriceTotal.Name = "textboxPriceTotal";
this.textboxPriceTotal.ReadOnly = true;
this.textboxPriceTotal.Size = new System.Drawing.Size(95, 20);
this.textboxPriceTotal.TabIndex = 72;
//
//labelPriceTotal
//
this.labelPriceTotal.AutoSize = true;
this.labelPriceTotal.Location = new System.Drawing.Point(282, 309);
this.labelPriceTotal.Name = "labelPriceTotal";
this.labelPriceTotal.Size = new System.Drawing.Size(58, 13);
this.labelPriceTotal.TabIndex = 65;
this.labelPriceTotal.Text = "Total Price";
//
//groupboxStatistics
//
this.groupboxStatistics.Controls.Add(this.labelStatisticsItemTierDisplay);
this.groupboxStatistics.Controls.Add(this.labelStatisticsItemTier);
this.groupboxStatistics.Controls.Add(this.labelStatisticsPopularityDisplay);
this.groupboxStatistics.Controls.Add(this.labelStatisticsPopularity);
this.groupboxStatistics.Controls.Add(this.labelStatisticsBaseWorthDisplay);
this.groupboxStatistics.Controls.Add(this.labelStatisticsBaseWorth);
this.groupboxStatistics.Controls.Add(this.labelStatisticsRarityDisplay);
this.groupboxStatistics.Controls.Add(this.labelStatisticsRarity);
this.groupboxStatistics.Controls.Add(this.labelStatisticsQualityDisplay);
this.groupboxStatistics.Controls.Add(this.labelStatisticsQuality);
this.groupboxStatistics.Location = new System.Drawing.Point(196, 132);
this.groupboxStatistics.Name = "groupboxStatistics";
this.groupboxStatistics.Size = new System.Drawing.Size(181, 118);
this.groupboxStatistics.TabIndex = 74;
this.groupboxStatistics.TabStop = false;
this.groupboxStatistics.Text = "Statistics";
//
//labelStatisticsItemTierDisplay
//
this.labelStatisticsItemTierDisplay.AutoSize = true;
this.labelStatisticsItemTierDisplay.Location = new System.Drawing.Point(112, 84);
this.labelStatisticsItemTierDisplay.Name = "labelStatisticsItemTierDisplay";
this.labelStatisticsItemTierDisplay.Size = new System.Drawing.Size(0, 13);
this.labelStatisticsItemTierDisplay.TabIndex = 64;
//
//labelStatisticsItemTier
//
this.labelStatisticsItemTier.AutoSize = true;
this.labelStatisticsItemTier.Location = new System.Drawing.Point(6, 84);
this.labelStatisticsItemTier.Name = "labelStatisticsItemTier";
this.labelStatisticsItemTier.Size = new System.Drawing.Size(51, 13);
this.labelStatisticsItemTier.TabIndex = 64;
this.labelStatisticsItemTier.Text = "Item Tier:";
//
//labelStatisticsPopularityDisplay
//
this.labelStatisticsPopularityDisplay.AutoSize = true;
this.labelStatisticsPopularityDisplay.Location = new System.Drawing.Point(112, 33);
this.labelStatisticsPopularityDisplay.Name = "labelStatisticsPopularityDisplay";
this.labelStatisticsPopularityDisplay.Size = new System.Drawing.Size(0, 13);
this.labelStatisticsPopularityDisplay.TabIndex = 64;
//
//labelStatisticsPopularity
//
this.labelStatisticsPopularity.AutoSize = true;
this.labelStatisticsPopularity.Location = new System.Drawing.Point(6, 33);
this.labelStatisticsPopularity.Name = "labelStatisticsPopularity";
this.labelStatisticsPopularity.Size = new System.Drawing.Size(56, 13);
this.labelStatisticsPopularity.TabIndex = 64;
this.labelStatisticsPopularity.Text = "Popularity:";
//
//labelStatisticsBaseWorthDisplay
//
this.labelStatisticsBaseWorthDisplay.AutoSize = true;
this.labelStatisticsBaseWorthDisplay.Location = new System.Drawing.Point(112, 67);
this.labelStatisticsBaseWorthDisplay.Name = "labelStatisticsBaseWorthDisplay";
this.labelStatisticsBaseWorthDisplay.Size = new System.Drawing.Size(0, 13);
this.labelStatisticsBaseWorthDisplay.TabIndex = 61;
//
//labelStatisticsBaseWorth
//
this.labelStatisticsBaseWorth.AutoSize = true;
this.labelStatisticsBaseWorth.Location = new System.Drawing.Point(6, 67);
this.labelStatisticsBaseWorth.Name = "labelStatisticsBaseWorth";
this.labelStatisticsBaseWorth.Size = new System.Drawing.Size(66, 13);
this.labelStatisticsBaseWorth.TabIndex = 61;
this.labelStatisticsBaseWorth.Text = "Base Worth:";
//
//labelStatisticsRarityDisplay
//
this.labelStatisticsRarityDisplay.AutoSize = true;
this.labelStatisticsRarityDisplay.Location = new System.Drawing.Point(112, 50);
this.labelStatisticsRarityDisplay.Name = "labelStatisticsRarityDisplay";
this.labelStatisticsRarityDisplay.Size = new System.Drawing.Size(0, 13);
this.labelStatisticsRarityDisplay.TabIndex = 63;
//
//labelStatisticsRarity
//
this.labelStatisticsRarity.AutoSize = true;
this.labelStatisticsRarity.Location = new System.Drawing.Point(6, 50);
this.labelStatisticsRarity.Name = "labelStatisticsRarity";
this.labelStatisticsRarity.Size = new System.Drawing.Size(37, 13);
this.labelStatisticsRarity.TabIndex = 63;
this.labelStatisticsRarity.Text = "Rarity:";
//
//labelStatisticsQualityDisplay
//
this.labelStatisticsQualityDisplay.AutoSize = true;
this.labelStatisticsQualityDisplay.Location = new System.Drawing.Point(112, 16);
this.labelStatisticsQualityDisplay.Name = "labelStatisticsQualityDisplay";
this.labelStatisticsQualityDisplay.Size = new System.Drawing.Size(0, 13);
this.labelStatisticsQualityDisplay.TabIndex = 61;
//
//labelStatisticsQuality
//
this.labelStatisticsQuality.AutoSize = true;
this.labelStatisticsQuality.Location = new System.Drawing.Point(6, 16);
this.labelStatisticsQuality.Name = "labelStatisticsQuality";
this.labelStatisticsQuality.Size = new System.Drawing.Size(42, 13);
this.labelStatisticsQuality.TabIndex = 61;
this.labelStatisticsQuality.Text = "Quality:";
//
//groupboxVarious
//
this.groupboxVarious.Controls.Add(this.labelVariousDescriptionDisplay);
this.groupboxVarious.Controls.Add(this.labelVariousDescription);
this.groupboxVarious.Controls.Add(this.labelVariousPicturePathDisplay);
this.groupboxVarious.Controls.Add(this.labelVariousPicturePath);
this.groupboxVarious.Location = new System.Drawing.Point(12, 256);
this.groupboxVarious.Name = "groupboxVarious";
this.groupboxVarious.Size = new System.Drawing.Size(365, 50);
this.groupboxVarious.TabIndex = 75;
this.groupboxVarious.TabStop = false;
this.groupboxVarious.Text = "Various";
//
//labelVariousDescriptionDisplay
//
this.labelVariousDescriptionDisplay.AutoSize = true;
this.labelVariousDescriptionDisplay.Location = new System.Drawing.Point(112, 33);
this.labelVariousDescriptionDisplay.Name = "labelVariousDescriptionDisplay";
this.labelVariousDescriptionDisplay.Size = new System.Drawing.Size(0, 13);
this.labelVariousDescriptionDisplay.TabIndex = 64;
//
//labelVariousDescription
//
this.labelVariousDescription.AutoSize = true;
this.labelVariousDescription.Location = new System.Drawing.Point(6, 33);
this.labelVariousDescription.Name = "labelVariousDescription";
this.labelVariousDescription.Size = new System.Drawing.Size(63, 13);
this.labelVariousDescription.TabIndex = 64;
this.labelVariousDescription.Text = "Description:";
//
//labelVariousPicturePathDisplay
//
this.labelVariousPicturePathDisplay.AutoSize = true;
this.labelVariousPicturePathDisplay.Location = new System.Drawing.Point(112, 16);
this.labelVariousPicturePathDisplay.Name = "labelVariousPicturePathDisplay";
this.labelVariousPicturePathDisplay.Size = new System.Drawing.Size(0, 13);
this.labelVariousPicturePathDisplay.TabIndex = 61;
//
//labelVariousPicturePath
//
this.labelVariousPicturePath.AutoSize = true;
this.labelVariousPicturePath.Location = new System.Drawing.Point(6, 16);
this.labelVariousPicturePath.Name = "labelVariousPicturePath";
this.labelVariousPicturePath.Size = new System.Drawing.Size(93, 13);
this.labelVariousPicturePath.TabIndex = 61;
this.labelVariousPicturePath.Text = "Picture Path && File";
//
//formDC
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6f, 13f);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(760, 386);
this.Controls.Add(this.groupboxVarious);
this.Controls.Add(this.groupboxStatistics);
this.Controls.Add(this.groupboxItemInfo);
this.Controls.Add(this.textboxPriceTotal);
this.Controls.Add(this.comboboxFamily);
this.Controls.Add(this.textboxBuyAmount);
this.Controls.Add(this.comboboxName);
this.Controls.Add(this.comboboxCategory);
this.Controls.Add(this.textboxBuyPrice);
this.Controls.Add(this.comboboxGenre);
this.Controls.Add(this.buttonClose);
this.Controls.Add(this.labelGenre);
this.Controls.Add(this.labelPriceTotal);
this.Controls.Add(this.labelBuyAmount);
this.Controls.Add(this.labelFamily);
this.Controls.Add(this.buttonBuy);
this.Controls.Add(this.labelBuyPrice);
this.Controls.Add(this.labelCategory);
this.Controls.Add(this.labelName);
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedToolWindow;
this.MaximizeBox = false;
this.MinimizeBox = false;
this.Name = "formDC";
this.Text = "Buying Goods";
Load += this.formItemManagement_Load;
this.groupboxItemInfo.ResumeLayout(false);
this.groupboxItemInfo.PerformLayout();
this.groupboxStatistics.ResumeLayout(false);
this.groupboxStatistics.PerformLayout();
this.groupboxVarious.ResumeLayout(false);
this.groupboxVarious.PerformLayout();
this.ResumeLayout(false);
this.PerformLayout();
}
private System.Windows.Forms.Label labelVariousPicturePathDisplay;
private System.Windows.Forms.GroupBox groupboxVarious;
private System.Windows.Forms.Label labelVariousPicturePath;
private System.Windows.Forms.Label labelStatisticsQuality;
private System.Windows.Forms.Label labelStatisticsQualityDisplay;
private System.Windows.Forms.Label labelStatisticsRarity;
private System.Windows.Forms.Label labelStatisticsRarityDisplay;
private System.Windows.Forms.Label labelStatisticsBaseWorth;
private System.Windows.Forms.Label labelStatisticsBaseWorthDisplay;
private System.Windows.Forms.Label labelVariousDescription;
private System.Windows.Forms.Label labelVariousDescriptionDisplay;
private System.Windows.Forms.Label labelStatisticsPopularity;
private System.Windows.Forms.Label labelStatisticsPopularityDisplay;
private System.Windows.Forms.Label labelStatisticsItemTier;
private System.Windows.Forms.Label labelStatisticsItemTierDisplay;
private System.Windows.Forms.GroupBox groupboxStatistics;
private System.Windows.Forms.Label labelItemFamilyDisplay;
private System.Windows.Forms.Label labelItemGenreDisplay;
private System.Windows.Forms.Label labelItemCompanyDisplay;
private System.Windows.Forms.Label labelItemItemNameDisplay;
private System.Windows.Forms.Label labelItemCategoryDisplay;
private System.Windows.Forms.Label labelItemBrandDisplay;
private System.Windows.Forms.Label labelInfoFamily;
private System.Windows.Forms.Label labelItemGenre;
private System.Windows.Forms.Label labelItemCompany;
private System.Windows.Forms.Label labelItemItemName;
private System.Windows.Forms.Label labelItemCategory;
private System.Windows.Forms.Label labelItemBrand;
private System.Windows.Forms.Label labelPriceTotal;
private System.Windows.Forms.TextBox textboxPriceTotal;
private System.Windows.Forms.GroupBox groupboxItemInfo;
private System.Windows.Forms.TextBox textboxBuyAmount;
private System.Windows.Forms.TextBox textboxBuyPrice;
private System.Windows.Forms.Button buttonClose;
private System.Windows.Forms.Button buttonBuy;
private System.Windows.Forms.Label labelBuyAmount;
private System.Windows.Forms.Label labelBuyPrice;
private System.Windows.Forms.ComboBox comboboxFamily;
private System.Windows.Forms.ComboBox comboboxName;
private System.Windows.Forms.ComboBox comboboxCategory;
private System.Windows.Forms.ComboBox comboboxGenre;
private System.Windows.Forms.Label labelGenre;
private System.Windows.Forms.Label labelFamily;
private System.Windows.Forms.Label labelCategory;
private System.Windows.Forms.Label labelName;
}
| |
using System;
using FreeImageAPI;
using System.Drawing;
namespace Sample05
{
class Program
{
static void Main(string[] args)
{
// Check if FreeImage.dll is available (can be in %path%).
if (!FreeImage.IsAvailable())
{
Console.WriteLine("FreeImage.dll seems to be missing. Aborting.");
return;
}
Sample sample = new Sample();
// The example will flip the bitmap by manually accessing the
// bitmaps scanlines and swapping them
sample.Example01();
// The example will access each pixel of the bitmap manually
// and change its color intensity to 3/4 of the original value
// which will have a darker bitmap as result.
sample.Example02();
// The example will access and swap the bitmaps palette from
// 'FIC_MINISBLACK' to 'FIC_MINISWHITE'. Then it will swap each pixels
// palette index so that each pixel is assigned to the its old value
// so that the bitmaps "pixeldata" stays the same.
sample.Example03();
}
}
public class Sample
{
FIBITMAP dib = new FIBITMAP();
public void Example01()
{
// Load sample file
dib = FreeImage.LoadEx("Sample.jpg", FREE_IMAGE_LOAD_FLAGS.JPEG_ACCURATE);
// Check whether loading succeeded
if (dib.IsNull)
{
Console.WriteLine("Sample.jpg could not be loaded. Aborting.");
return;
}
// Check whether the bitmap has 24 bpp color depth to ensure
// using RGBTRIPPLE is correct.
if (FreeImage.GetBPP(dib) != 24)
{
Console.WriteLine("Sample.jpg is no 24 bpp bitmap. Aborting.");
FreeImage.UnloadEx(ref dib);
return;
}
// Store height of the bitmap
int height = (int)FreeImage.GetHeight(dib);
// Iterate over half of the bitmaps scanlines and swap
// line[1] with line[height], line[2] with line[height-1] etc which will
// flip the image.
for (int i = 0; i < (height / 2); i++)
{
// Get scanline from the bottom part of the bitmap
Scanline<RGBTRIPLE> scanlineBottom = new Scanline<RGBTRIPLE>(dib, i);
// Get scanline from the top part of the bitmap
Scanline<RGBTRIPLE> scanlineTop = new Scanline<RGBTRIPLE>(dib, height - 1 - i);
// Get arrays of RGBTRIPPLEs that contain the bitmaps real pixel data
// of the two scanlines.
RGBTRIPLE[] rgbtBottom = scanlineBottom.Data;
RGBTRIPLE[] rgbtTop = scanlineTop.Data;
// Restore the scanline across to switch the bitmaps lines.
scanlineBottom.Data = rgbtTop;
scanlineTop.Data = rgbtBottom;
}
// Store the bitmap to disk
if (!FreeImage.SaveEx(ref dib, "SampleOut01.jpg", FREE_IMAGE_SAVE_FLAGS.JPEG_QUALITYGOOD, true))
{
Console.WriteLine("Error while saving 'SampleOut01.jpg'");
FreeImage.UnloadEx(ref dib);
}
}
public void Example02()
{
dib = FreeImage.LoadEx("Sample.jpg", FREE_IMAGE_LOAD_FLAGS.JPEG_ACCURATE);
// Check whether loading succeeded
if (dib.IsNull)
{
Console.WriteLine("Sample.jpg could not be loaded. Aborting.");
return;
}
// Check whether the bitmap has 24 bpp color depth to ensure
// using RGBTRIPPLE is correct.
if (FreeImage.GetBPP(dib) != 24)
{
Console.WriteLine("Sample.jpg is no 24 bpp bitmap. Aborting.");
FreeImage.UnloadEx(ref dib);
return;
}
// Iterate over all scanlines
for (int i = 0; i < FreeImage.GetHeight(dib); i++)
{
// Get scanline
Scanline<RGBTRIPLE> scanline = new Scanline<RGBTRIPLE>(dib, i);
// Get pixeldata from scanline
RGBTRIPLE[] rgbt = scanline.Data;
// Iterate over each pixel reducing the colors intensity to 3/4 which
// will darken the bitmap.
for (int j = 0; j < rgbt.Length; j++)
{
rgbt[j].rgbtBlue = (byte)((int)rgbt[j].rgbtBlue * 3 / 4);
rgbt[j].rgbtGreen = (byte)((int)rgbt[j].rgbtGreen * 3 / 4);
rgbt[j].rgbtRed = (byte)((int)rgbt[j].rgbtRed * 3 / 4);
// In case no direct access to the data is implemented
// the following way is equivalent:
//
// Color color = rgbt[j].color;
// rgbt[j].color = Color.FromArgb(color.R * 3 / 4, color.G * 3 / 4, color.B * 3 / 4);
}
// Write the darkened scanline back to memory
scanline.Data = rgbt;
}
// Store the bitmap to disk
if (!FreeImage.SaveEx(ref dib, "SampleOut02.jpg", FREE_IMAGE_SAVE_FLAGS.JPEG_QUALITYGOOD, true))
{
Console.WriteLine("Error while saving 'SampleOut02.jpg'");
FreeImage.UnloadEx(ref dib);
}
}
public void Example03()
{
dib = FreeImage.LoadEx("Sample.tif");
// Check whether loading succeeded
if (dib.IsNull)
{
Console.WriteLine("Sample.tif could not be loaded. Aborting.");
return;
}
// Check whether the bitmap has 4 bpp color depth to ensure
// using FI4B is correct.
if (FreeImage.GetBPP(dib) != 4)
{
Console.WriteLine("Sample.tif is no 4 bpp bitmap. Aborting.");
FreeImage.UnloadEx(ref dib);
return;
}
// Get the bitmaps palette
Palette palette = FreeImage.GetPaletteEx(dib);
int size = (int)palette.Length;
// Check whether the palette has a color (is valid)
if (size == 0)
{
Console.WriteLine("Sample.tif has no valid palette. Aborting.");
FreeImage.UnloadEx(ref dib);
return;
}
// Swapping the palette
for (int i = 0; i < size / 2; i++)
{
RGBQUAD temp = palette[i];
palette[i] = palette[size - 1 - i];
palette[size - 1 - i] = temp;
}
// Iterate over each scanline
for (int i = 0; i < FreeImage.GetHeight(dib); i++)
{
// Get scanline
Scanline<FI4BIT> scanline = new Scanline<FI4BIT>(dib, i);
// Iterate over all pixels swapping the palette index
// so that the color will stay the same
for (int j = 0; j < scanline.Length; j++)
{
scanline[j] = (byte)(size - 1 - scanline[j]);
}
}
// Save the bitmap to disk
if (!FreeImage.SaveEx(ref dib, "SampleOut03.tif", FREE_IMAGE_SAVE_FLAGS.TIFF_LZW, true))
{
Console.WriteLine("Error while saving 'SampleOut03.tif'");
FreeImage.UnloadEx(ref dib);
}
}
}
}
| |
using System;
using NTumbleBit.BouncyCastle.Crypto.Utilities;
using NTumbleBit.BouncyCastle.Utilities;
namespace NTumbleBit.BouncyCastle.Crypto.Digests
{
/**
* implementation of SHA-1 as outlined in "Handbook of Applied Cryptography", pages 346 - 349.
*
* It is interesting to ponder why the, apart from the extra IV, the other difference here from MD5
* is the "endianness" of the word processing!
*/
internal class Sha1Digest
: GeneralDigest
{
private const int DigestLength = 20;
private uint H1, H2, H3, H4, H5;
private uint[] X = new uint[80];
private int xOff;
public Sha1Digest()
{
Reset();
}
/**
* Copy constructor. This will copy the state of the provided
* message digest.
*/
public Sha1Digest(Sha1Digest t)
: base(t)
{
CopyIn(t);
}
private void CopyIn(Sha1Digest t)
{
base.CopyIn(t);
H1 = t.H1;
H2 = t.H2;
H3 = t.H3;
H4 = t.H4;
H5 = t.H5;
Array.Copy(t.X, 0, X, 0, t.X.Length);
xOff = t.xOff;
}
public override string AlgorithmName
{
get
{
return "SHA-1";
}
}
public override int GetDigestSize()
{
return DigestLength;
}
internal override void ProcessWord(
byte[] input,
int inOff)
{
X[xOff] = Pack.BE_To_UInt32(input, inOff);
if(++xOff == 16)
{
ProcessBlock();
}
}
internal override void ProcessLength(long bitLength)
{
if(xOff > 14)
{
ProcessBlock();
}
X[14] = (uint)((ulong)bitLength >> 32);
X[15] = (uint)((ulong)bitLength);
}
public override int DoFinal(
byte[] output,
int outOff)
{
Finish();
Pack.UInt32_To_BE(H1, output, outOff);
Pack.UInt32_To_BE(H2, output, outOff + 4);
Pack.UInt32_To_BE(H3, output, outOff + 8);
Pack.UInt32_To_BE(H4, output, outOff + 12);
Pack.UInt32_To_BE(H5, output, outOff + 16);
Reset();
return DigestLength;
}
/**
* reset the chaining variables
*/
public override void Reset()
{
base.Reset();
H1 = 0x67452301;
H2 = 0xefcdab89;
H3 = 0x98badcfe;
H4 = 0x10325476;
H5 = 0xc3d2e1f0;
xOff = 0;
Array.Clear(X, 0, X.Length);
}
//
// Additive constants
//
private const uint Y1 = 0x5a827999;
private const uint Y2 = 0x6ed9eba1;
private const uint Y3 = 0x8f1bbcdc;
private const uint Y4 = 0xca62c1d6;
private static uint F(uint u, uint v, uint w)
{
return (u & v) | (~u & w);
}
private static uint H(uint u, uint v, uint w)
{
return u ^ v ^ w;
}
private static uint G(uint u, uint v, uint w)
{
return (u & v) | (u & w) | (v & w);
}
internal override void ProcessBlock()
{
//
// expand 16 word block into 80 word block.
//
for(int i = 16; i < 80; i++)
{
uint t = X[i - 3] ^ X[i - 8] ^ X[i - 14] ^ X[i - 16];
X[i] = t << 1 | t >> 31;
}
//
// set up working variables.
//
uint A = H1;
uint B = H2;
uint C = H3;
uint D = H4;
uint E = H5;
//
// round 1
//
int idx = 0;
for(int j = 0; j < 4; j++)
{
// E = rotateLeft(A, 5) + F(B, C, D) + E + X[idx++] + Y1
// B = rotateLeft(B, 30)
E += (A << 5 | (A >> 27)) + F(B, C, D) + X[idx++] + Y1;
B = B << 30 | (B >> 2);
D += (E << 5 | (E >> 27)) + F(A, B, C) + X[idx++] + Y1;
A = A << 30 | (A >> 2);
C += (D << 5 | (D >> 27)) + F(E, A, B) + X[idx++] + Y1;
E = E << 30 | (E >> 2);
B += (C << 5 | (C >> 27)) + F(D, E, A) + X[idx++] + Y1;
D = D << 30 | (D >> 2);
A += (B << 5 | (B >> 27)) + F(C, D, E) + X[idx++] + Y1;
C = C << 30 | (C >> 2);
}
//
// round 2
//
for(int j = 0; j < 4; j++)
{
// E = rotateLeft(A, 5) + H(B, C, D) + E + X[idx++] + Y2
// B = rotateLeft(B, 30)
E += (A << 5 | (A >> 27)) + H(B, C, D) + X[idx++] + Y2;
B = B << 30 | (B >> 2);
D += (E << 5 | (E >> 27)) + H(A, B, C) + X[idx++] + Y2;
A = A << 30 | (A >> 2);
C += (D << 5 | (D >> 27)) + H(E, A, B) + X[idx++] + Y2;
E = E << 30 | (E >> 2);
B += (C << 5 | (C >> 27)) + H(D, E, A) + X[idx++] + Y2;
D = D << 30 | (D >> 2);
A += (B << 5 | (B >> 27)) + H(C, D, E) + X[idx++] + Y2;
C = C << 30 | (C >> 2);
}
//
// round 3
//
for(int j = 0; j < 4; j++)
{
// E = rotateLeft(A, 5) + G(B, C, D) + E + X[idx++] + Y3
// B = rotateLeft(B, 30)
E += (A << 5 | (A >> 27)) + G(B, C, D) + X[idx++] + Y3;
B = B << 30 | (B >> 2);
D += (E << 5 | (E >> 27)) + G(A, B, C) + X[idx++] + Y3;
A = A << 30 | (A >> 2);
C += (D << 5 | (D >> 27)) + G(E, A, B) + X[idx++] + Y3;
E = E << 30 | (E >> 2);
B += (C << 5 | (C >> 27)) + G(D, E, A) + X[idx++] + Y3;
D = D << 30 | (D >> 2);
A += (B << 5 | (B >> 27)) + G(C, D, E) + X[idx++] + Y3;
C = C << 30 | (C >> 2);
}
//
// round 4
//
for(int j = 0; j < 4; j++)
{
// E = rotateLeft(A, 5) + H(B, C, D) + E + X[idx++] + Y4
// B = rotateLeft(B, 30)
E += (A << 5 | (A >> 27)) + H(B, C, D) + X[idx++] + Y4;
B = B << 30 | (B >> 2);
D += (E << 5 | (E >> 27)) + H(A, B, C) + X[idx++] + Y4;
A = A << 30 | (A >> 2);
C += (D << 5 | (D >> 27)) + H(E, A, B) + X[idx++] + Y4;
E = E << 30 | (E >> 2);
B += (C << 5 | (C >> 27)) + H(D, E, A) + X[idx++] + Y4;
D = D << 30 | (D >> 2);
A += (B << 5 | (B >> 27)) + H(C, D, E) + X[idx++] + Y4;
C = C << 30 | (C >> 2);
}
H1 += A;
H2 += B;
H3 += C;
H4 += D;
H5 += E;
//
// reset start of the buffer.
//
xOff = 0;
Array.Clear(X, 0, 16);
}
public override IMemoable Copy()
{
return new Sha1Digest(this);
}
public override void Reset(IMemoable other)
{
Sha1Digest d = (Sha1Digest)other;
CopyIn(d);
}
}
}
| |
/****************************************************************************/
/* */
/* The Mondo Libraries */
/* */
/* Namespace: Mondo.Common */
/* File: DataObjectSource.cs */
/* Class(es): IDataObjectSource, DataObjectSource, DBRow, */
/* DataReaderObjectSource, XmlObjectSource, */
/* XmlAttributeSource, DataSourceDictionary, */
/* DBRowDictionary, DataSourceList, DBRowList */
/* */
/* Purpose: Data objects and collections */
/* */
/* Original Author: Jim Lightfoot */
/* Creation Date: 16 Sep 2004 */
/* */
/* Copyright (c) 2004-2016 - Jim Lightfoot, All rights reserved */
/* */
/* Licensed under the MIT license: */
/* http://www.opensource.org/licenses/mit-license.php */
/* */
/****************************************************************************/
using System;
using System.Data;
using System.Linq.Expressions;
using System.Xml;
using System.Reflection;
using System.Data.SqlTypes;
using System.Data.Common;
using System.Dynamic;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using Microsoft.Win32;
using Mondo.Xml;
namespace Mondo.Common
{
/****************************************************************************/
/****************************************************************************/
public interface IModel
{
bool Modified {get;set;}
bool ReadOnly {get;set;}
void OnBeforeSave();
void OnAfterSave();
}
/****************************************************************************/
/****************************************************************************/
/// <summary>
/// interface for objects that can return attributed (column) data
/// The enumeration enumerates the columns names
/// </summary>
public interface IDataObjectSource : IModel, IDynamicMetaObjectProvider
{
string Get(string strColumnName, string defaultVal = "");
object GetObject(string strColumnName);
IDataObjectSource GetSubObject(string idSubObject);
DataSourceList GetSubList(string idSubList);
void SetValue(string strColumnName, string strValue);
void SetValue(string strColumnName, int iValue);
void SetValue(string strColumnName, long iValue);
void SetValue(string strColumnName, bool bValue);
void SetValue(string strColumnName, decimal dValue);
void SetValue(string strColumnName, double dValue);
void SetValue(string strColumnName, float fValue);
void SetValue(string strColumnName, Guid guidValue);
void SetValue(string strColumnName, DateTime dtValue);
IEnumerable Columns {get;}
}
/****************************************************************************/
/****************************************************************************/
public static class DataObjectSourceExtensions
{
/****************************************************************************/
public static T Get<T>(this IDataObjectSource ds, string strColumnName, T defaultVal = default(T), bool required = false) where T : struct
{
string val = ds.Get(strColumnName);
return(Utility.Convert<T>(val, defaultVal));
}
/****************************************************************************/
public static T ToObject<T>(this IDataObjectSource ds) where T : new()
{
T obj = new T();
Type type = obj.GetType();
PropertyInfo[] properties = type.GetProperties();
foreach(PropertyInfo property in properties)
{
string name = property.Name;
if(property.PropertyType.Name == "String")
{
string value = ds.Get(name);
property.SetValue(obj, value);
}
else if(property.PropertyType.Name.StartsWith("Nullable"))
{
object value = ds.Get(name, null);
if(value != null)
property.SetValue(obj, Utility.ConvertType(value, property.PropertyType.GenericTypeArguments[0]));
}
else if(property.PropertyType.IsValueType)
{
object value = ds.Get(name);
property.SetValue(obj, Utility.ConvertType(value, property.PropertyType));
}
}
return obj;
}
/****************************************************************************/
public static IList<T> ToList<T>(this DataSourceList dsl) where T : new()
{
List<T> list = new List<T>();
foreach(IDataObjectSource ds in dsl)
list.Add(ds.ToObject<T>());
return list;
}
}
/****************************************************************************/
public interface IDataObjectSourceFilter
{
bool Matches(IDataObjectSource objSource, string strColumnName);
}
/****************************************************************************/
/****************************************************************************/
/// <summary>
/// interface for objects that can return attributed (column) data
/// The enumeration enumerates the columns names
/// </summary>
public interface IHierarchicalDataSource : IDataObjectSource
{
IEnumerable<IHierarchicalDataSource> GetChildren(string strFilter);
IDataObjectSource Attributes {get;}
}
/****************************************************************************/
/****************************************************************************/
public interface IDataSourceContainer
{
IDataObjectSource DataSource {get;}
}
/****************************************************************************/
/****************************************************************************/
/// <summary>
/// Abstract implementation of IDataObjectSource
/// </summary>
public abstract class DataObjectSource : IDataObjectSource
{
private bool m_bModified = false;
private bool m_bReadOnly = false;
/****************************************************************************/
protected DataObjectSource()
{
}
/****************************************************************************/
public static IDataObjectSource Create(object objValue)
{
if(objValue == null)
return(new NullDataSource());
if(objValue is IDataObjectSource)
return(objValue as IDataObjectSource);
if(objValue is IDataSourceContainer)
return((objValue as IDataSourceContainer).DataSource);
if(objValue is IDictionary<string, string>)
return new DictionaryDataSource<string>(objValue as IDictionary<string, string>);
if(objValue is IDictionary<string, object>)
return new DictionaryDataSource<object>(objValue as IDictionary<string, object>);
if(objValue is XmlNode)
return(new XmlObjectSource(objValue as XmlNode));
if(objValue is DataRow)
return(new DBRow(objValue as DataRow));
if(objValue is DataTable)
{
DataTable dtTable = objValue as DataTable;
if(dtTable.Rows.Count == 0)
return(new NullDataSource());
return(new DBRow(dtTable.Rows[0]));
}
if(objValue is DataView)
{
foreach(DataRow objRow in (objValue as DataView))
return(new DBRow(objRow));
return(new NullDataSource());
}
if(objValue is DataSet)
{
DataSet dsDataSet = objValue as DataSet;
if(dsDataSet.Tables.Count == 0)
return(new NullDataSource());
DataTable dtTable = dsDataSet.Tables[0];
if(dtTable.Rows.Count == 0)
return(new NullDataSource());
return(new DBRow(dsDataSet));
}
if(objValue is DbDataReader)
return(new DataReaderObjectSource(objValue as DbDataReader));
if(objValue is RegistryKey)
return(new RegistryDataSource(objValue as RegistryKey));
return(new DataObject(objValue));
}
#region IDataObjectSource Members
public abstract string Get(string strColumnName, string defaultVal = "");
public abstract object GetObject(string strColumnName);
public abstract IEnumerable Columns {get;}
/****************************************************************************/
public virtual IDataObjectSource GetSubObject(string idSubObject)
{
return(null);
}
/****************************************************************************/
public virtual DataSourceList GetSubList(string idSubList)
{
return(null);
}
/****************************************************************************/
public abstract void SetValue(string strColumnName, string strValue);
public virtual void SetValue(string strColumnName, int iValue) {SetValue(strColumnName, iValue.ToString());}
public virtual void SetValue(string strColumnName, float fValue) {SetValue(strColumnName, fValue.ToString());}
public virtual void SetValue(string strColumnName, long iValue) {SetValue(strColumnName, iValue.ToString());}
public virtual void SetValue(string strColumnName, bool bValue) {SetValue(strColumnName, bValue.ToString());}
public virtual void SetValue(string strColumnName, decimal dValue) {SetValue(strColumnName, dValue.ToString());}
public virtual void SetValue(string strColumnName, double dValue) {SetValue(strColumnName, dValue.ToString());}
public virtual void SetValue(string strColumnName, Guid guidValue) {SetValue(strColumnName, guidValue.ToString());}
public virtual void SetValue(string strColumnName, DateTime dtValue) {SetValue(strColumnName, dtValue.ToString());}
#endregion
/****************************************************************************/
public virtual bool Modified
{
get {return(m_bModified);}
set {m_bModified = value;}
}
/****************************************************************************/
public virtual bool ReadOnly
{
get {return(m_bReadOnly);}
set {m_bReadOnly = value;}
}
/****************************************************************************/
public virtual void OnBeforeSave()
{
// Do nothing in base class
}
/****************************************************************************/
public virtual void OnAfterSave()
{
// Do nothing in base class
}
/****************************************************************************/
public virtual DynamicMetaObject GetMetaObject(System.Linq.Expressions.Expression param)
{
return new DataSourceDynamicMetaObject(param, this);
}
/****************************************************************************/
/****************************************************************************/
internal class DataSourceDynamicMetaObject : DynamicMetaObject
{
/****************************************************************************/
internal DataSourceDynamicMetaObject(Expression parameter, DataObjectSource src)
: base(parameter, BindingRestrictions.Empty, src)
{
}
/****************************************************************************/
public override DynamicMetaObject BindGetMember(GetMemberBinder binder)
{
// One parameter
Expression[] parameters = new Expression[]
{
Expression.Constant(binder.Name)
};
DynamicMetaObject getObject = new DynamicMetaObject
(
Expression.Call
(
Expression.Convert(Expression, LimitType),
typeof(DataObjectSource).GetMethod("GetObject"),
parameters
),
BindingRestrictions.GetTypeRestriction(Expression, LimitType)
);
return getObject;
}
}
}
/****************************************************************************/
/****************************************************************************/
/// <summary>
/// A DataObjectSource implementation for a registry key (RegistryKey)
/// </summary>
public class RegistryDataSource : DataObjectSource
{
private RegistryKey m_objKey;
/****************************************************************************/
public RegistryDataSource(RegistryKey objKey)
{
m_objKey = objKey;
}
/****************************************************************************/
public override string Get(string strColumnName, string defaultVal = "")
{
return(m_objKey.GetValue(strColumnName).Normalized());
}
/****************************************************************************/
public override object GetObject(string strColumnName)
{
return Get(strColumnName);
}
/****************************************************************************/
public override void SetValue(string strColumnName, string strValue)
{
if(!this.ReadOnly)
m_objKey.SetValue(strColumnName, strValue);
}
/****************************************************************************/
public override IEnumerable Columns
{
get { return(new RegistryDataSourceList(m_objKey)); }
}
}
/****************************************************************************/
/****************************************************************************/
public class DictionaryDataSource<T> : DataObjectSource
{
private readonly IDictionary<string, T> _values;
/***********************************************************************/
public DictionaryDataSource(IDictionary<string, T> values)
{
_values = values;
}
/***********************************************************************/
public override string Get(string columnName, string defaultVal = "")
{
if(_values.ContainsKey(columnName))
return _values[columnName].ToString();
return defaultVal;
}
/***********************************************************************/
public override object GetObject(string columnName)
{
return _values[columnName];
}
/***********************************************************************/
public override IEnumerable Columns
{
get
{
return null;
}
}
/***********************************************************************/
public override void SetValue(string strColumnName, string strValue)
{
// This is readonly data source
throw new NotSupportedException();
}
}
/****************************************************************************/
/****************************************************************************/
/// <summary>
/// A DataObjectSource implementation for null data source
/// </summary>
public sealed class NullDataSource : DataObjectSource
{
/****************************************************************************/
public NullDataSource()
{
}
/****************************************************************************/
public override IEnumerable Columns
{
get { return(null); }
}
/****************************************************************************/
public override string Get(string idColumn, string defaultVal = "")
{
return("");
}
/****************************************************************************/
public override object GetObject(string strColumnName)
{
return null;
}
/****************************************************************************/
public override void SetValue(string strColumnName, string strValue)
{
// Override to do nothing
}
/****************************************************************************/
public override bool ReadOnly
{
get {return(true);}
set {}
}
}
/****************************************************************************/
/****************************************************************************/
/// <summary>
/// A DataObjectSource implementation for a database row (DataRow)
/// </summary>
public sealed class DBRow : DataObjectSource
{
private DataRow m_objRow = null;
private DataSet m_objDataSet = null;
/************************************************************************/
public DBRow(DataRow objRow)
{
m_objRow = objRow;
}
/************************************************************************/
public DBRow(DataSet objDataSet)
{
m_objRow = objDataSet.Tables[0].Rows[0];
m_objDataSet = objDataSet;
}
/************************************************************************/
public DBRow(DataTable objTable)
{
m_objRow = objTable.Rows[0];
}
/****************************************************************************/
public DBRow()
{
}
/****************************************************************************/
public DataRow DataSource
{
get {return(m_objRow);}
set {m_objRow = value;}
}
/****************************************************************************/
public DataSet DataSet
{
get {return(m_objDataSet);}
}
/****************************************************************************/
public override DataSourceList GetSubList(string idSubList)
{
if(m_objDataSet != null && m_objDataSet.Tables.Contains(idSubList))
return(DataSourceList.Create(m_objDataSet.Tables[idSubList]));
return(null);
}
/****************************************************************************/
public DataSourceList GetSubList(int iIndex)
{
if(m_objDataSet != null && m_objDataSet.Tables.Count > iIndex)
return(DataSourceList.Create(m_objDataSet.Tables[iIndex]));
return(null);
}
/****************************************************************************/
public override IEnumerable Columns
{
get
{
return(m_objRow.Table.Columns);
}
}
/****************************************************************************/
public override void SetValue(string strColumnName, string strValue)
{
throw new NotSupportedException();
}
/****************************************************************************/
public override string Get(string idColumn, string defaultVal = "")
{
try
{
return(m_objRow[idColumn].ToString().Trim());
}
catch
{
return(defaultVal);
}
}
/****************************************************************************/
public override object GetObject(string idColumn)
{
object obj = m_objRow[idColumn];
if(obj is DBNull)
return null;
return obj;
}
/****************************************************************************/
public static string GetColumn(DataRow objRow, string idColumn)
{
try
{
return(objRow[idColumn].ToString().Trim());
}
catch
{
return("");
}
}
/****************************************************************************/
public static T GetColumn<T>(DataRow objRow, string idColumn, T defaultVal = default(T)) where T : struct
{
string val = GetColumn(objRow, idColumn);
return(Utility.Convert<T>(val, defaultVal));
}
}
/****************************************************************************/
/****************************************************************************/
public class DataSourceDictionary : Dictionary<Guid, IDataObjectSource>
{
/****************************************************************************/
public DataSourceDictionary()
{
}
}
/****************************************************************************/
/****************************************************************************/
public class DBRowDictionary : DataSourceDictionary
{
/****************************************************************************/
public DBRowDictionary(DataTable dtData, string strColumnName)
{
DataRowCollection aRows = dtData.Rows;
foreach(DataRow row in aRows)
{
DBRow dbRow = new DBRow(row);
this.Add(dbRow.Get<Guid>(strColumnName), dbRow);
}
}
}
/****************************************************************************/
/****************************************************************************/
/// <summary>
/// A DataObjectSource implementation for a database reader (DbDataReader)
/// </summary>
public class DataReaderObjectSource : DataObjectSource
{
private DbDataReader m_objDataReader;
/****************************************************************************/
public DataReaderObjectSource(DbDataReader objReader)
{
m_objDataReader = objReader;
}
/****************************************************************************/
public override IEnumerable Columns
{
get
{
int nColumns = m_objDataReader.FieldCount;
string[] aColumns = new string[nColumns];
for(int i = 0; i < nColumns; ++i)
aColumns[i] = m_objDataReader.GetName(i);
return(aColumns);
}
}
/****************************************************************************/
public override string Get(string strColumnName, string defaultVal = "")
{
try
{
return(m_objDataReader[strColumnName].ToString().Trim());
}
catch
{
return(defaultVal);
}
}
/****************************************************************************/
public override object GetObject(string strColumnName)
{
return m_objDataReader[strColumnName];
}
/****************************************************************************/
public override void SetValue(string strColumnName, string strValue)
{
throw new NotSupportedException();
}
/****************************************************************************/
public override bool ReadOnly
{
get {return(true);}
set {}
}
}
/****************************************************************************/
/****************************************************************************/
/// <summary>
/// A DataObjectSource implementation for an XmlNode where the data items are child nodes
/// </summary>
public class XmlObjectSource : DataObjectSource, IHierarchicalDataSource
{
private XmlNode m_xmlSource;
/****************************************************************************/
public XmlObjectSource(XmlNode xmlSource)
{
m_xmlSource = xmlSource;
}
/****************************************************************************/
public XmlNode DataSource
{
get {return(m_xmlSource);}
set {m_xmlSource = value;}
}
/****************************************************************************/
public override IEnumerable Columns
{
get
{
int nColumns = m_xmlSource.ChildNodes.Count;
string[] aColumns = new string[nColumns];
for(int i = 0; i < nColumns; ++i)
aColumns[i] = m_xmlSource.ChildNodes[i].LocalName;
return(aColumns);
}
}
/****************************************************************************/
public override string Get(string strColumnName, string defaultVal = "")
{
return(m_xmlSource.GetChildText(strColumnName, defaultVal));
}
/****************************************************************************/
public override object GetObject(string strColumnName)
{
XmlNode node = m_xmlSource.SelectSingleNode(strColumnName);
if(node.HasChildElements())
return (IDynamicMetaObjectProvider) new XmlObjectSource(node);
return GetData(node);
}
/****************************************************************************/
private object GetData(XmlNode node)
{
string val = node.InnerText;
long lVal = 0;
if(long.TryParse(val, out lVal))
return lVal;
decimal dVal = 0;
if(decimal.TryParse(val, out dVal))
return dVal;
DateTime dtVal = DateTime.MinValue;
if(DateTime.TryParse(val, out dtVal))
return dtVal;
return val;
}
/****************************************************************************/
public override void SetValue(string strColumnName, string strValue)
{
if(!this.ReadOnly)
{
string strCurrentValue = Get(strColumnName);
if(strCurrentValue != strValue)
{
m_xmlSource.SetChildText(strColumnName, strValue);
this.Modified = true;
}
}
return;
}
#region IHierarchicalDataSource Members
/****************************************************************************/
public IEnumerable<IHierarchicalDataSource> GetChildren(string strFilter)
{
if(string.IsNullOrEmpty(strFilter))
strFilter = "*";
List<IHierarchicalDataSource> aChildren = new List<IHierarchicalDataSource>();
foreach(XmlNode xmlChild in m_xmlSource.SelectNodes(strFilter))
aChildren.Add(new XmlObjectSource(xmlChild));
return(aChildren);
}
/****************************************************************************/
public IDataObjectSource Attributes
{
get
{
return(new XmlAttributeSource(m_xmlSource));
}
}
#endregion
}
/****************************************************************************/
/****************************************************************************/
/// <summary>
/// A DataObjectSource implementation for an XmlNode where the data items are attributes
/// </summary>
public class XmlAttributeSource : DataObjectSource
{
private XmlNode m_xmlSource;
/****************************************************************************/
public XmlAttributeSource(XmlNode xmlSource)
{
m_xmlSource = xmlSource;
}
/****************************************************************************/
public XmlNode DataSource
{
get {return(m_xmlSource);}
set {m_xmlSource = value;}
}
/****************************************************************************/
public override IEnumerable Columns
{
get
{
int nColumns = m_xmlSource.Attributes.Count;
string[] aColumns = new string[nColumns];
for(int i = 0; i < nColumns; ++i)
aColumns[i] = m_xmlSource.Attributes[i].Name;
return(aColumns);
}
}
/****************************************************************************/
public override string Get(string strColumnName, string defaultVal = "")
{
return(m_xmlSource.GetAttribute(strColumnName, defaultVal));
}
/****************************************************************************/
public override object GetObject(string strColumnName)
{
return(m_xmlSource.GetAttribute(strColumnName));
}
/****************************************************************************/
public override void SetValue(string strColumnName, string strValue)
{
if(!this.ReadOnly)
{
string strCurrentValue = Get(strColumnName);
if(strCurrentValue != strValue)
{
m_xmlSource.SetAttribute(strColumnName, strValue);
this.Modified = true;
}
}
return;
}
}
/****************************************************************************/
/****************************************************************************/
public interface IDataSourceSortable
{
void Sort(string idAttribute, bool bAscending);
}
/****************************************************************************/
/****************************************************************************/
public abstract class DataSourceList : ICollection, IEnumerable, IDataSourceSortable
{
private IEnumerable m_objSource = null;
/****************************************************************************/
protected DataSourceList(IEnumerable objSource)
{
m_objSource = objSource;
}
/****************************************************************************/
protected DataSourceList()
{
}
/****************************************************************************/
public static DataSourceList Create(object objData)
{
if(objData == null)
return(null);
if(objData is DataSet)
return(new DBRowList(objData as DataSet));
if(objData is DataTable)
return(new DBRowList(objData as DataTable));
if(objData is DataView)
return(new DBRowList(objData as DataView));
if(objData is DataRowCollection)
return(new DBRowList(objData as DataRowCollection));
if(objData is XmlNodeList)
return(new XmlObjectList(objData as XmlNodeList));
if(objData is XmlDocument)
return(new XmlObjectList((objData as XmlDocument).FirstChild, "*"));
if(objData is XmlNode)
return(new XmlObjectList(objData as XmlNode, "*"));
if(objData is IEnumerable)
return(new DataObjectList(objData as IEnumerable));
if(objData is RegistryKey)
return(new RegistryDataSourceList(objData as RegistryKey));
throw new ArgumentException("Unknown list type!");
}
/****************************************************************************/
public IEnumerable Source
{
get {return(m_objSource);}
set {m_objSource = value;}
}
/****************************************************************************/
public abstract int Count {get;}
protected abstract IDataObjectSource GetObject(object objValue);
#region IEnumerable Members
/****************************************************************************/
public virtual IEnumerator GetEnumerator()
{
return(new MyEnumerator(this, m_objSource));
}
/****************************************************************************/
public class MyEnumerator : IEnumerator
{
IEnumerator m_objClient;
DataSourceList m_objList;
/****************************************************************************/
public MyEnumerator(DataSourceList objList, IEnumerable objClient)
{
m_objList = objList;
m_objClient = objClient.GetEnumerator();
}
#region IEnumerator Members
/****************************************************************************/
public object Current
{
get
{
return(m_objList.GetObject(m_objClient.Current));
}
}
/****************************************************************************/
public bool MoveNext()
{
return(m_objClient.MoveNext());
}
/****************************************************************************/
public void Reset()
{
m_objClient.Reset();
}
#endregion
}
#endregion
#region ICollection Members
public void CopyTo(Array array, int index)
{
throw new Exception("The method or operation is not implemented.");
}
public bool IsSynchronized
{
get { return(false); }
}
public object SyncRoot
{
get { return(null); }
}
#endregion
#region IDataSourceSortable Members
public virtual void Sort(string idAttribute, bool bAscending)
{
if(m_objSource is IDataSourceSortable)
(m_objSource as IDataSourceSortable).Sort(idAttribute, bAscending);
}
#endregion
}
/****************************************************************************/
/****************************************************************************/
public class DBRowList : DataSourceList
{
private DBRow m_objRow = new DBRow();
private int m_nRows = 0;
/****************************************************************************/
public DBRowList(DataRowCollection aRows) : base(aRows)
{
m_nRows = aRows.Count;
}
/****************************************************************************/
public DBRowList(DataTable dtData) : this(dtData.Rows)
{
}
/****************************************************************************/
public DBRowList(DataView dvData) : base(dvData)
{
m_nRows = dvData.Count;
}
/****************************************************************************/
public DBRowList(DataSet dsData)
{
if(dsData.Tables.Count == 0)
this.Source = new List<int>();
else
{
this.Source = dsData.Tables[0].Rows;
m_nRows = dsData.Tables[0].Rows.Count;
}
}
/****************************************************************************/
public override int Count
{
get { return(m_nRows); }
}
/****************************************************************************/
protected override IDataObjectSource GetObject(object objValue)
{
if(objValue is DataRowView)
m_objRow.DataSource = (objValue as DataRowView).Row;
else
m_objRow.DataSource = objValue as DataRow;
return(m_objRow);
}
}
/****************************************************************************/
/****************************************************************************/
public class RegistryDataSourceList : DataSourceList
{
private List<RegistryKey> m_aSubKeys = null;
/****************************************************************************/
public RegistryDataSourceList(RegistryKey objParent) : base(null)
{
m_aSubKeys = new List<RegistryKey>();
try
{
string[] aNames = objParent.GetSubKeyNames();
foreach(string strName in aNames)
{
try
{
m_aSubKeys.Add(objParent.OpenSubKey(strName, true));
}
catch(Exception ex)
{
cDebug.Capture(ex);
}
}
}
catch(Exception ex)
{
cDebug.Capture(ex);
}
this.Source = m_aSubKeys;
}
/****************************************************************************/
public RegistryDataSourceList(RegistryKey objParent, string strSubKey) : base(null)
{
m_aSubKeys = new List<RegistryKey>();
try
{
RegistryKey objKey = objParent.OpenSubKey(strSubKey, true);
string[] aNames = objKey.GetSubKeyNames();
foreach(string strName in aNames)
{
try
{
m_aSubKeys.Add(objKey.OpenSubKey(strName, true));
}
catch(Exception ex)
{
cDebug.Capture(ex);
}
}
}
catch(Exception ex)
{
cDebug.Capture(ex);
}
this.Source = m_aSubKeys;
}
/****************************************************************************/
public override int Count
{
get { return(m_aSubKeys.Count); }
}
/****************************************************************************/
protected override IDataObjectSource GetObject(object objValue)
{
return(new RegistryDataSource(objValue as RegistryKey));
}
}
/****************************************************************************/
/****************************************************************************/
public class XmlObjectList : DataSourceList
{
private XmlObjectSource m_objData = new XmlObjectSource(null);
private int m_nRows = 0;
/****************************************************************************/
public XmlObjectList(XmlNodeList aNodes) : base(aNodes)
{
m_nRows = aNodes.Count;
}
/****************************************************************************/
public XmlObjectList(XmlNode objParent, string strXPath) : this(objParent.SelectNodes(strXPath))
{
}
/****************************************************************************/
public override int Count
{
get { return(m_nRows); }
}
/****************************************************************************/
protected override IDataObjectSource GetObject(object objValue)
{
m_objData.DataSource = objValue as XmlNode;
return(m_objData);
}
}
/****************************************************************************/
/****************************************************************************/
/// <summary>
/// Wraps an IDataObjectSource over on arbitrary object using reflection to pull properties
/// </summary>
public class DataObject : DataObjectSource
{
private object m_objSource;
/****************************************************************************/
public DataObject(object objSource)
{
m_objSource = objSource;
}
/****************************************************************************/
public object DataSource
{
get {return(m_objSource);}
set {m_objSource = value;}
}
/****************************************************************************/
public override string Get(string strColumnName, string defaultVal = "")
{
try
{
return(GetObject(strColumnName).ToString());
}
catch
{
return(defaultVal);
}
}
/****************************************************************************/
public override object GetObject(string strColumnName)
{
if(strColumnName == "")
return(null);
List<string> aNames = StringList.ParseString(strColumnName, ".", true);
object objSource = m_objSource;
foreach(string strName in aNames)
{
Type objType = objSource.GetType();
PropertyInfo objProperty = objType.GetProperty(strName);
objSource = objProperty.GetValue(objSource, null);
}
return(objSource);
}
/****************************************************************************/
public static string GetString(object objSource, string strColumnName)
{
try
{
List<string> aNames = StringList.ParseString(strColumnName, ".", true);
foreach(string strName in aNames)
objSource = objSource.GetType().GetProperty(strName).GetValue(objSource, null);
return(objSource.ToString());
}
catch
{
return("");
}
}
/****************************************************************************/
private void _SetValue(string strColumnName, object objValue)
{
if(this.ReadOnly)
return;
try
{
List<string> aNames = StringList.ParseString(strColumnName, ".", true);
object objSource = m_objSource;
int nNames = aNames.Count-1;
for(int i = 0; i < nNames; ++i)
{
PropertyInfo objProperty = objSource.GetType().GetProperty(aNames[i]);
objSource = objProperty.GetValue(objSource, null);
}
string strPropName = aNames[nNames];
PropertyInfo objProperty2 = objSource.GetType().GetProperty(strPropName);
System.Type objType = objProperty2.PropertyType;
objValue = Utility.ConvertType(objValue, objType);
if(objValue is IComparable)
{
object objCurrentValue = Utility.ConvertType(Get(strColumnName), objType);
if((objValue as IComparable).CompareTo(objCurrentValue) == 0)
return;
}
this.Modified = true;
objProperty2.SetValue(objSource, objValue, null);
}
catch(Exception ex)
{
cDebug.Capture(ex);
}
return;
}
/****************************************************************************/
public override void SetValue(string strColumnName, string value) {_SetValue(strColumnName, value);}
public override void SetValue(string strColumnName, int value) {_SetValue(strColumnName, value);}
public override void SetValue(string strColumnName, float value) {_SetValue(strColumnName, value);}
public override void SetValue(string strColumnName, long value) {_SetValue(strColumnName, value);}
public override void SetValue(string strColumnName, bool value) {_SetValue(strColumnName, value);}
public override void SetValue(string strColumnName, decimal value) {_SetValue(strColumnName, value);}
public override void SetValue(string strColumnName, double value) {_SetValue(strColumnName, value);}
public override void SetValue(string strColumnName, Guid value) {_SetValue(strColumnName, value);}
public override void SetValue(string strColumnName, DateTime value) {_SetValue(strColumnName, value);}
/****************************************************************************/
public override IEnumerable Columns
{
get { return(null); }
}
/****************************************************************************/
public override IDataObjectSource GetSubObject(string idSubObject)
{
return(new DataObject(m_objSource.GetType().GetProperty(idSubObject).GetValue(m_objSource, null)));
}
/****************************************************************************/
public override DataSourceList GetSubList(string idSubList)
{
return(DataSourceList.Create(m_objSource.GetType().GetProperty(idSubList).GetValue(m_objSource, null)));
}
}
/****************************************************************************/
/****************************************************************************/
public class DataObjectList : DataSourceList
{
private List<DataObject> m_aItems = new List<DataObject>();
/****************************************************************************/
public DataObjectList(IEnumerable aList) : base(aList)
{
this.DataList = aList;
}
/****************************************************************************/
protected IEnumerable DataList
{
set
{
m_aItems.Clear();
if(value != null)
foreach(object objData in value)
m_aItems.Add(new DataObject(objData));
}
}
/****************************************************************************/
public override int Count
{
get { return(m_aItems.Count); }
}
/****************************************************************************/
public override IEnumerator GetEnumerator()
{
return(m_aItems.GetEnumerator());
}
/****************************************************************************/
protected override IDataObjectSource GetObject(object objValue)
{
throw new Exception("The method or operation is not implemented.");
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Diagnostics;
namespace System.Xml
{
internal class Base64Decoder : IncrementalReadDecoder
{
//
// Fields
//
private byte[] _buffer;
private int _startIndex;
private int _curIndex;
private int _endIndex;
private int _bits;
private int _bitsFilled;
private static readonly String s_charsBase64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
private static readonly byte[] s_mapBase64 = ConstructMapBase64();
private const int MaxValidChar = (int)'z';
private const byte Invalid = unchecked((byte)-1);
//
// IncrementalReadDecoder interface
//
internal override int DecodedCount
{
get
{
return _curIndex - _startIndex;
}
}
internal override bool IsFull
{
get
{
return _curIndex == _endIndex;
}
}
#if !SILVERLIGHT_DISABLE_SECURITY
[System.Security.SecuritySafeCritical]
#endif
internal override unsafe int Decode(char[] chars, int startPos, int len)
{
if (chars == null)
{
throw new ArgumentNullException("chars");
}
if (len < 0)
{
throw new ArgumentOutOfRangeException("len");
}
if (startPos < 0)
{
throw new ArgumentOutOfRangeException("startPos");
}
if (chars.Length - startPos < len)
{
throw new ArgumentOutOfRangeException("len");
}
if (len == 0)
{
return 0;
}
int bytesDecoded, charsDecoded;
fixed (char* pChars = &chars[startPos])
{
fixed (byte* pBytes = &_buffer[_curIndex])
{
Decode(pChars, pChars + len, pBytes, pBytes + (_endIndex - _curIndex), out charsDecoded, out bytesDecoded);
}
}
_curIndex += bytesDecoded;
return charsDecoded;
}
#if !SILVERLIGHT_DISABLE_SECURITY
[System.Security.SecuritySafeCritical]
#endif
internal override unsafe int Decode(string str, int startPos, int len)
{
if (str == null)
{
throw new ArgumentNullException("str");
}
if (len < 0)
{
throw new ArgumentOutOfRangeException("len");
}
if (startPos < 0)
{
throw new ArgumentOutOfRangeException("startPos");
}
if (str.Length - startPos < len)
{
throw new ArgumentOutOfRangeException("len");
}
if (len == 0)
{
return 0;
}
int bytesDecoded, charsDecoded;
fixed (char* pChars = str)
{
fixed (byte* pBytes = &_buffer[_curIndex])
{
Decode(pChars + startPos, pChars + startPos + len, pBytes, pBytes + (_endIndex - _curIndex), out charsDecoded, out bytesDecoded);
}
}
_curIndex += bytesDecoded;
return charsDecoded;
}
internal override void Reset()
{
_bitsFilled = 0;
_bits = 0;
}
internal override void SetNextOutputBuffer(Array buffer, int index, int count)
{
Debug.Assert(buffer != null);
Debug.Assert(count >= 0);
Debug.Assert(index >= 0);
Debug.Assert(buffer.Length - index >= count);
Debug.Assert((buffer as byte[]) != null);
_buffer = (byte[])buffer;
_startIndex = index;
_curIndex = index;
_endIndex = index + count;
}
//
// Private methods
//
private static byte[] ConstructMapBase64()
{
byte[] mapBase64 = new byte[MaxValidChar + 1];
for (int i = 0; i < mapBase64.Length; i++)
{
mapBase64[i] = Invalid;
}
for (int i = 0; i < s_charsBase64.Length; i++)
{
mapBase64[(int)s_charsBase64[i]] = (byte)i;
}
return mapBase64;
}
#if !SILVERLIGHT_DISABLE_SECURITY
[System.Security.SecurityCritical]
#endif
private unsafe void Decode(char* pChars, char* pCharsEndPos,
byte* pBytes, byte* pBytesEndPos,
out int charsDecoded, out int bytesDecoded)
{
#if DEBUG
Debug.Assert(pCharsEndPos - pChars >= 0);
Debug.Assert(pBytesEndPos - pBytes >= 0);
#endif
// walk hex digits pairing them up and shoving the value of each pair into a byte
byte* pByte = pBytes;
char* pChar = pChars;
int b = _bits;
int bFilled = _bitsFilled;
XmlCharType xmlCharType = XmlCharType.Instance;
while (pChar < pCharsEndPos && pByte < pBytesEndPos)
{
char ch = *pChar;
// end?
if (ch == '=')
{
break;
}
pChar++;
// ignore white space
if (xmlCharType.IsWhiteSpace(ch))
{
continue;
}
int digit;
if (ch > 122 || (digit = s_mapBase64[ch]) == Invalid)
{
throw new XmlException(SR.Xml_InvalidBase64Value, new string(pChars, 0, (int)(pCharsEndPos - pChars)));
}
b = (b << 6) | digit;
bFilled += 6;
if (bFilled >= 8)
{
// get top eight valid bits
*pByte++ = (byte)((b >> (bFilled - 8)) & 0xFF);
bFilled -= 8;
if (pByte == pBytesEndPos)
{
goto Return;
}
}
}
if (pChar < pCharsEndPos && *pChar == '=')
{
bFilled = 0;
// ignore padding chars
do
{
pChar++;
} while (pChar < pCharsEndPos && *pChar == '=');
// ignore whitespace after the padding chars
if (pChar < pCharsEndPos)
{
do
{
if (!xmlCharType.IsWhiteSpace(*pChar++))
{
throw new XmlException(SR.Xml_InvalidBase64Value, new string(pChars, 0, (int)(pCharsEndPos - pChars)));
}
} while (pChar < pCharsEndPos);
}
}
Return:
_bits = b;
_bitsFilled = bFilled;
bytesDecoded = (int)(pByte - pBytes);
charsDecoded = (int)(pChar - pChars);
}
}
}
| |
/*
Copyright 2019 Esri
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
using System;
using System.Drawing;
using System.IO;
using System.Runtime.InteropServices;
using System.Windows.Forms;
using ESRI.ArcGIS.ADF.BaseClasses;
using ESRI.ArcGIS.Framework;
using ESRI.ArcGIS.Geodatabase;
using ESRI.ArcGIS.Geometry;
using ESRI.ArcGIS.NetworkAnalyst;
using ESRI.ArcGIS.NetworkAnalystUI;
using System.Text;
namespace ExportNAClass
{
/// <summary>
/// This sample command allows you export a text file version
/// of the active class in the ArcGIS Network Analyst extension window after
/// completion of a successful solve.
/// </summary>
///
[ClassInterface(ClassInterfaceType.None)]
[Guid("08CE5834-8267-4a73-AFDD-2821B4B1F6EC")]
[ProgId("ExportNAClass.NAClassToTextfileCmd")]
public sealed class NAClassToTextfileCmd : BaseCommand, INAWindowCommand
{
private const string DELIMITER = "\t";
private INetworkAnalystExtension m_naExt;
public NAClassToTextfileCmd()
{
base.m_category = "Developer Samples";
base.m_caption = "Export To text file...";
base.m_message = "Export a network analysis class to a text file.";
base.m_toolTip = "Export a network analysis class to a text file.";
base.m_name = "NAClassToTextFileCmd";
try
{
string bitmapResourceName = GetType().Name + ".bmp";
base.m_bitmap = new Bitmap(GetType(), bitmapResourceName);
}
catch (Exception ex)
{
System.Diagnostics.Trace.WriteLine(ex.Message, "Invalid Bitmap");
}
}
#region COM Registration Function(s)
[ComRegisterFunction()]
[ComVisible(false)]
static void RegisterFunction(Type registerType)
{
// Required for ArcGIS Component Category Registrar support
ArcGISCategoryRegistration(registerType);
}
[ComUnregisterFunction()]
[ComVisible(false)]
static void UnregisterFunction(Type registerType)
{
// Required for ArcGIS Component Category Registrar support
ArcGISCategoryUnregistration(registerType);
}
#region ArcGIS Component Category Registrar generated code
/// <summary>
/// Required method for ArcGIS Component Category registration -
/// Do not modify the contents of this method with the code editor.
/// </summary>
private static void ArcGISCategoryRegistration(Type registerType)
{
string regKey = string.Format("HKEY_CLASSES_ROOT\\CLSID\\{{{0}}}", registerType.GUID);
ESRI.ArcGIS.ADF.CATIDs.MxCommands.Register(regKey);
// Register with NetworkAnalystWindowItemsCommand to get the
// command to show up when you right click on the class in the NAWindow
ESRI.ArcGIS.ADF.CATIDs.NetworkAnalystWindowCategoryCommand.Register(regKey);
}
/// <summary>
/// Required method for ArcGIS Component Category unregistration -
/// Do not modify the contents of this method with the code editor.
/// </summary>
private static void ArcGISCategoryUnregistration(Type registerType)
{
string regKey = string.Format("HKEY_CLASSES_ROOT\\CLSID\\{{{0}}}", registerType.GUID);
ESRI.ArcGIS.ADF.CATIDs.MxCommands.Unregister(regKey);
ESRI.ArcGIS.ADF.CATIDs.NetworkAnalystWindowCategoryCommand.Unregister(regKey);
}
#endregion
#endregion
#region "NAWindow Interaction"
private INALayer GetActiveAnalysisLayer()
{
if (m_naExt != null)
return m_naExt.NAWindow.ActiveAnalysis;
else
return null;
}
private INAWindowCategory2 GetActiveCategory()
{
if (m_naExt != null)
return m_naExt.NAWindow.ActiveCategory as INAWindowCategory2;
else
return null;
}
#endregion
#region "Overridden INAWindowCommand Methods"
public bool Applies(INALayer naLayer, INAWindowCategory Category)
{
return true;
}
#endregion
#region "Overridden BaseCommand Methods"
public override void OnCreate(object hook)
{
// Try to get the ArcGIS Network Analyst extension from the desktop app's extensions
IApplication app;
app = hook as IApplication;
if (app != null)
m_naExt = app.FindExtensionByName("Network Analyst") as INetworkAnalystExtension;
}
/// <summary>
/// This command will be enabled only for a NAClass
/// associated with a successful solve
/// </summary>
public override bool Enabled
{
get
{
// there must be an active analysis layer
INALayer naLayer = GetActiveAnalysisLayer();
if (naLayer != null)
{
// the context must be valid
INAContext naContext = naLayer.Context;
if (naContext != null)
{
return true;
}
}
return false;
}
}
public override void OnClick()
{
try
{
ExportToText();
}
catch (Exception exception)
{
MessageBox.Show(exception.Message, "Error");
}
}
#endregion
private void ExportToText()
{
SaveFileDialog sfDialog = new SaveFileDialog();
SetUpSaveDialog(ref sfDialog);
// generate the dialog and verify the user successfully clicked save
DialogResult dResult = sfDialog.ShowDialog();
if (dResult == DialogResult.OK)
{
// set up the text file to be written
FileInfo t = new FileInfo(sfDialog.FileName);
StreamWriter swText = t.CreateText();
ITable table = GetActiveCategory().DataLayer as ITable;
// write the first line of the text file as column headers
swText.WriteLine(GenerateColumnHeaderString(ref table));
// iterate through the table associated with the class
// to write out each line of data into the text file
ICursor cursor = table.Search(null, true);
IRow row = cursor.NextRow();
while (row != null)
{
swText.WriteLine(GenerateDataString(ref row));
row = cursor.NextRow();
}
swText.Close();
}
}
private void SetUpSaveDialog(ref SaveFileDialog sfDialog)
{
sfDialog.AddExtension = true;
sfDialog.Title = "Save an export of the specified class in the active analysis...";
sfDialog.DefaultExt = "txt";
sfDialog.OverwritePrompt = true;
sfDialog.FileName = "ClassExport.txt";
sfDialog.Filter = "Text files (*.txt;*.csv;*.asc;*.tab)|*.txt;*.tab;*.asc;*.csv";
sfDialog.InitialDirectory = "c:\\";
}
private string GenerateColumnHeaderString(ref ITable table)
{
IField field = null;
// export the names of the fields (tab delimited) as the first line of the export
string fieldNames = "";
for (int i = 0; i < table.Fields.FieldCount; i++)
{
field = table.Fields.get_Field(i);
if (i > 0) fieldNames += DELIMITER;
string columnName = field.Name.ToString();
// point classes have a special output of X and Y, other classes just output "Shape"
if (field.Type == esriFieldType.esriFieldTypeGeometry)
{
if (field.GeometryDef.GeometryType == esriGeometryType.esriGeometryPoint)
{
columnName = "X";
columnName += DELIMITER;
columnName += "Y";
}
}
fieldNames += columnName;
}
return fieldNames;
}
private string GenerateDataString(ref IRow row)
{
string textOut = "";
// On a zero-based index, iterate through the fields in the collection.
for (int fieldIndex = 0; fieldIndex < row.Fields.FieldCount; fieldIndex++)
{
if (fieldIndex > 0) textOut += DELIMITER;
IField field = row.Fields.get_Field(fieldIndex);
// for shape fields in a point layer, export the associated X and Y coordinates
if (field.Type == esriFieldType.esriFieldTypeGeometry)
{
if (field.GeometryDef.GeometryType == esriGeometryType.esriGeometryPoint)
{
// x y location information must be retrieved from the Feature
IPoint point = row.get_Value(fieldIndex) as ESRI.ArcGIS.Geometry.Point;
textOut += point.X.ToString();
textOut += DELIMITER;
textOut += point.Y.ToString();
}
else if (field.GeometryDef.GeometryType == esriGeometryType.esriGeometryPolyline ||
field.GeometryDef.GeometryType == esriGeometryType.esriGeometryPolygon)
{
StringBuilder stringBuffer = new StringBuilder();
var pointCollection = row.get_Value(fieldIndex) as IPointCollection;
for (int pointIndex = 0; pointIndex < pointCollection.PointCount; pointIndex++)
{
IPoint point = pointCollection.get_Point(pointIndex);
if (pointIndex > 0)
stringBuffer.Append(",");
stringBuffer.Append("{");
stringBuffer.Append(point.X);
stringBuffer.Append(",");
stringBuffer.Append(point.Y);
stringBuffer.Append(",");
stringBuffer.Append(point.Z);
stringBuffer.Append(",");
stringBuffer.Append(point.M);
stringBuffer.Append("}");
}
textOut += stringBuffer.ToString();
}
else
{
textOut += "Shape";
}
}
// Handle the Locations field for polyline and polygon barrier classes
else if (field.Name == "Locations" && field.Type == esriFieldType.esriFieldTypeBlob)
{
StringBuilder stringBuffer = new StringBuilder();
// get the location ranges out of the barrier feature
var naLocRangesObject = row as INALocationRangesObject;
if (naLocRangesObject == null) // Not a location ranges object
textOut += row.get_Value(fieldIndex).ToString();
var naLocRanges = naLocRangesObject.NALocationRanges;
if (naLocRanges == null) // does not have any location ranges
textOut += row.get_Value(fieldIndex).ToString();
// add all of the junctions included in the barrier to the Junctions dataGrid
stringBuffer.Append("{Junctions:{");
long junctionCount = naLocRanges.JunctionCount;
int junctionEID = -1;
for (int i = 0; i < junctionCount; i++)
{
naLocRanges.QueryJunction(i, ref junctionEID);
if (i > 0)
stringBuffer.Append(",");
stringBuffer.Append("{");
stringBuffer.Append(junctionEID);
stringBuffer.Append("}");
}
stringBuffer.Append("}");
// add all of the edges included in the barrier to the Edges dataGrid
stringBuffer.Append(",EdgeRanges:{");
long edgeRangeCount = naLocRanges.EdgeRangeCount;
int edgeEID = -1;
double fromPosition, toPosition;
fromPosition = toPosition = -1;
esriNetworkEdgeDirection edgeDirection = esriNetworkEdgeDirection.esriNEDNone;
for (int i = 0; i < edgeRangeCount; i++)
{
naLocRanges.QueryEdgeRange(i, ref edgeEID, ref edgeDirection, ref fromPosition, ref toPosition);
string directionValue = "";
if (edgeDirection == esriNetworkEdgeDirection.esriNEDAlongDigitized) directionValue = "Along Digitized";
else if (edgeDirection == esriNetworkEdgeDirection.esriNEDAgainstDigitized) directionValue = "Against Digitized";
if (i > 0)
stringBuffer.Append(",");
stringBuffer.Append("{");
stringBuffer.Append(edgeEID);
stringBuffer.Append(",");
stringBuffer.Append(directionValue);
stringBuffer.Append(",");
stringBuffer.Append(fromPosition);
stringBuffer.Append(",");
stringBuffer.Append(toPosition);
stringBuffer.Append("}");
}
stringBuffer.Append("}");
textOut += stringBuffer.ToString();
}
else
{
textOut += row.get_Value(fieldIndex).ToString();
}
}
return textOut;
}
}
}
| |
/*
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using QuantConnect.Interfaces;
using QuantConnect.Logging;
using QuantConnect.Orders;
using RestSharp;
using QuantConnect.Util;
namespace QuantConnect.Api
{
/// <summary>
/// QuantConnect.com Interaction Via API.
/// </summary>
public class Api : IApi, IDownloadProvider
{
private string _dataFolder;
/// <summary>
/// Returns the underlying API connection
/// </summary>
protected ApiConnection ApiConnection { get; private set; }
/// <summary>
/// Initialize the API with the given variables
/// </summary>
public virtual void Initialize(int userId, string token, string dataFolder)
{
ApiConnection = new ApiConnection(userId, token);
_dataFolder = dataFolder?.Replace("\\", "/", StringComparison.InvariantCulture);
//Allow proper decoding of orders from the API.
JsonConvert.DefaultSettings = () => new JsonSerializerSettings
{
Converters = { new OrderJsonConverter() }
};
}
/// <summary>
/// Check if Api is successfully connected with correct credentials
/// </summary>
public bool Connected => ApiConnection.Connected;
/// <summary>
/// Create a project with the specified name and language via QuantConnect.com API
/// </summary>
/// <param name="name">Project name</param>
/// <param name="language">Programming language to use</param>
/// <param name="organizationId">Optional param for specifying organization to create project under.
/// If none provided web defaults to preferred.</param>
/// <returns>Project object from the API.</returns>
public ProjectResponse CreateProject(string name, Language language, string organizationId = null)
{
var request = new RestRequest("projects/create", Method.POST)
{
RequestFormat = DataFormat.Json
};
// Only include organization Id if its not null or empty
string jsonParams;
if (string.IsNullOrEmpty(organizationId))
{
jsonParams = JsonConvert.SerializeObject(new
{
name,
language
});
}
else
{
jsonParams = JsonConvert.SerializeObject(new
{
name,
language,
organizationId
});
}
request.AddParameter("application/json", jsonParams, ParameterType.RequestBody);
ApiConnection.TryRequest(request, out ProjectResponse result);
return result;
}
/// <summary>
/// Get details about a single project
/// </summary>
/// <param name="projectId">Id of the project</param>
/// <returns><see cref="ProjectResponse"/> that contains information regarding the project</returns>
public ProjectResponse ReadProject(int projectId)
{
var request = new RestRequest("projects/read", Method.POST)
{
RequestFormat = DataFormat.Json
};
request.AddParameter("application/json", JsonConvert.SerializeObject(new
{
projectId
}), ParameterType.RequestBody);
ApiConnection.TryRequest(request, out ProjectResponse result);
return result;
}
/// <summary>
/// List details of all projects
/// </summary>
/// <returns><see cref="ProjectResponse"/> that contains information regarding the project</returns>
public ProjectResponse ListProjects()
{
var request = new RestRequest("projects/read", Method.POST)
{
RequestFormat = DataFormat.Json
};
ApiConnection.TryRequest(request, out ProjectResponse result);
return result;
}
/// <summary>
/// Add a file to a project
/// </summary>
/// <param name="projectId">The project to which the file should be added</param>
/// <param name="name">The name of the new file</param>
/// <param name="content">The content of the new file</param>
/// <returns><see cref="ProjectFilesResponse"/> that includes information about the newly created file</returns>
public ProjectFilesResponse AddProjectFile(int projectId, string name, string content)
{
var request = new RestRequest("files/create", Method.POST)
{
RequestFormat = DataFormat.Json
};
request.AddParameter("application/json", JsonConvert.SerializeObject(new
{
projectId,
name,
content
}), ParameterType.RequestBody);
ApiConnection.TryRequest(request, out ProjectFilesResponse result);
return result;
}
/// <summary>
/// Update the name of a file
/// </summary>
/// <param name="projectId">Project id to which the file belongs</param>
/// <param name="oldFileName">The current name of the file</param>
/// <param name="newFileName">The new name for the file</param>
/// <returns><see cref="RestResponse"/> indicating success</returns>
public RestResponse UpdateProjectFileName(int projectId, string oldFileName, string newFileName)
{
var request = new RestRequest("files/update", Method.POST)
{
RequestFormat = DataFormat.Json
};
request.AddParameter("application/json", JsonConvert.SerializeObject(new
{
projectId,
name = oldFileName,
newName = newFileName
}), ParameterType.RequestBody);
ApiConnection.TryRequest(request, out RestResponse result);
return result;
}
/// <summary>
/// Update the contents of a file
/// </summary>
/// <param name="projectId">Project id to which the file belongs</param>
/// <param name="fileName">The name of the file that should be updated</param>
/// <param name="newFileContents">The new contents of the file</param>
/// <returns><see cref="RestResponse"/> indicating success</returns>
public RestResponse UpdateProjectFileContent(int projectId, string fileName, string newFileContents)
{
var request = new RestRequest("files/update", Method.POST)
{
RequestFormat = DataFormat.Json
};
request.AddParameter("application/json", JsonConvert.SerializeObject(new
{
projectId,
name = fileName,
content = newFileContents
}), ParameterType.RequestBody);
ApiConnection.TryRequest(request, out RestResponse result);
return result;
}
/// <summary>
/// Read all files in a project
/// </summary>
/// <param name="projectId">Project id to which the file belongs</param>
/// <returns><see cref="ProjectFilesResponse"/> that includes the information about all files in the project</returns>
public ProjectFilesResponse ReadProjectFiles(int projectId)
{
var request = new RestRequest("files/read", Method.POST)
{
RequestFormat = DataFormat.Json
};
request.AddParameter("application/json", JsonConvert.SerializeObject(new
{
projectId
}), ParameterType.RequestBody);
ApiConnection.TryRequest(request, out ProjectFilesResponse result);
return result;
}
/// <summary>
/// Read a file in a project
/// </summary>
/// <param name="projectId">Project id to which the file belongs</param>
/// <param name="fileName">The name of the file</param>
/// <returns><see cref="ProjectFilesResponse"/> that includes the file information</returns>
public ProjectFilesResponse ReadProjectFile(int projectId, string fileName)
{
var request = new RestRequest("files/read", Method.POST)
{
RequestFormat = DataFormat.Json
};
request.AddParameter("application/json", JsonConvert.SerializeObject(new
{
projectId,
name = fileName
}), ParameterType.RequestBody);
ApiConnection.TryRequest(request, out ProjectFilesResponse result);
return result;
}
/// <summary>
/// Delete a file in a project
/// </summary>
/// <param name="projectId">Project id to which the file belongs</param>
/// <param name="name">The name of the file that should be deleted</param>
/// <returns><see cref="ProjectFilesResponse"/> that includes the information about all files in the project</returns>
public RestResponse DeleteProjectFile(int projectId, string name)
{
var request = new RestRequest("files/delete", Method.POST)
{
RequestFormat = DataFormat.Json
};
request.AddParameter("application/json", JsonConvert.SerializeObject(new
{
projectId,
name,
}), ParameterType.RequestBody);
ApiConnection.TryRequest(request, out RestResponse result);
return result;
}
/// <summary>
/// Delete a project
/// </summary>
/// <param name="projectId">Project id we own and wish to delete</param>
/// <returns>RestResponse indicating success</returns>
public RestResponse DeleteProject(int projectId)
{
var request = new RestRequest("projects/delete", Method.POST)
{
RequestFormat = DataFormat.Json
};
request.AddParameter("application/json", JsonConvert.SerializeObject(new
{
projectId
}), ParameterType.RequestBody);
ApiConnection.TryRequest(request, out RestResponse result);
return result;
}
/// <summary>
/// Create a new compile job request for this project id.
/// </summary>
/// <param name="projectId">Project id we wish to compile.</param>
/// <returns>Compile object result</returns>
public Compile CreateCompile(int projectId)
{
var request = new RestRequest("compile/create", Method.POST)
{
RequestFormat = DataFormat.Json
};
request.AddParameter("application/json", JsonConvert.SerializeObject(new
{
projectId
}), ParameterType.RequestBody);
ApiConnection.TryRequest(request, out Compile result);
return result;
}
/// <summary>
/// Read a compile packet job result.
/// </summary>
/// <param name="projectId">Project id we sent for compile</param>
/// <param name="compileId">Compile id return from the creation request</param>
/// <returns><see cref="Compile"/></returns>
public Compile ReadCompile(int projectId, string compileId)
{
var request = new RestRequest("compile/read", Method.POST)
{
RequestFormat = DataFormat.Json
};
request.AddParameter("application/json", JsonConvert.SerializeObject(new
{
projectId,
compileId
}), ParameterType.RequestBody);
ApiConnection.TryRequest(request, out Compile result);
return result;
}
/// <summary>
/// Create a new backtest request and get the id.
/// </summary>
/// <param name="projectId">Id for the project to backtest</param>
/// <param name="compileId">Compile id for the project</param>
/// <param name="backtestName">Name for the new backtest</param>
/// <returns><see cref="Backtest"/>t</returns>
public Backtest CreateBacktest(int projectId, string compileId, string backtestName)
{
var request = new RestRequest("backtests/create", Method.POST)
{
RequestFormat = DataFormat.Json
};
request.AddParameter("application/json", JsonConvert.SerializeObject(new
{
projectId,
compileId,
backtestName
}), ParameterType.RequestBody);
ApiConnection.TryRequest(request, out BacktestResponseWrapper result);
// Use API Response values for Backtest Values
result.Backtest.Success = result.Success;
result.Backtest.Errors = result.Errors;
// Return only the backtest object
return result.Backtest;
}
/// <summary>
/// Read out a backtest in the project id specified.
/// </summary>
/// <param name="projectId">Project id to read</param>
/// <param name="backtestId">Specific backtest id to read</param>
/// <param name="getCharts">True will return backtest charts</param>
/// <returns><see cref="Backtest"/></returns>
public Backtest ReadBacktest(int projectId, string backtestId, bool getCharts = true)
{
var request = new RestRequest("backtests/read", Method.POST)
{
RequestFormat = DataFormat.Json
};
request.AddParameter("application/json", JsonConvert.SerializeObject(new
{
projectId,
backtestId
}), ParameterType.RequestBody);
ApiConnection.TryRequest(request, out BacktestResponseWrapper result);
if (!result.Success)
{
// place an empty place holder so we can return any errors back to the user and not just null
result.Backtest = new Backtest { BacktestId = backtestId };
}
// Go fetch the charts if the backtest is completed and success
else if (getCharts && result.Backtest.Completed)
{
// For storing our collected charts
var updatedCharts = new Dictionary<string, Chart>();
// Create backtest requests for each chart that is empty
foreach (var chart in result.Backtest.Charts)
{
if (!chart.Value.Series.IsNullOrEmpty())
{
continue;
}
var chartRequest = new RestRequest("backtests/read", Method.POST)
{
RequestFormat = DataFormat.Json
};
chartRequest.AddParameter("application/json", JsonConvert.SerializeObject(new
{
projectId,
backtestId,
chart = chart.Key.Replace(' ', '+')
}), ParameterType.RequestBody);
ApiConnection.TryRequest(chartRequest, out BacktestResponseWrapper chartResponse);
// Add this chart to our updated collection
if (chartResponse.Success)
{
updatedCharts.Add(chart.Key, chartResponse.Backtest.Charts[chart.Key]);
}
}
// Update our result
foreach(var updatedChart in updatedCharts)
{
result.Backtest.Charts[updatedChart.Key] = updatedChart.Value;
}
}
// Use API Response values for Backtest Values
result.Backtest.Success = result.Success;
result.Backtest.Errors = result.Errors;
// Return only the backtest object
return result.Backtest;
}
/// <summary>
/// Update a backtest name
/// </summary>
/// <param name="projectId">Project for the backtest we want to update</param>
/// <param name="backtestId">Backtest id we want to update</param>
/// <param name="name">Name we'd like to assign to the backtest</param>
/// <param name="note">Note attached to the backtest</param>
/// <returns><see cref="RestResponse"/></returns>
public RestResponse UpdateBacktest(int projectId, string backtestId, string name = "", string note = "")
{
var request = new RestRequest("backtests/update", Method.POST)
{
RequestFormat = DataFormat.Json
};
request.AddParameter("application/json", JsonConvert.SerializeObject(new
{
projectId,
backtestId,
name,
note
}), ParameterType.RequestBody);
ApiConnection.TryRequest(request, out Backtest result);
return result;
}
/// <summary>
/// List all the backtests for a project
/// </summary>
/// <param name="projectId">Project id we'd like to get a list of backtest for</param>
/// <returns><see cref="BacktestList"/></returns>
public BacktestList ListBacktests(int projectId)
{
var request = new RestRequest("backtests/read", Method.POST)
{
RequestFormat = DataFormat.Json
};
request.AddParameter("application/json", JsonConvert.SerializeObject(new
{
projectId,
}), ParameterType.RequestBody);
ApiConnection.TryRequest(request, out BacktestList result);
return result;
}
/// <summary>
/// Delete a backtest from the specified project and backtestId.
/// </summary>
/// <param name="projectId">Project for the backtest we want to delete</param>
/// <param name="backtestId">Backtest id we want to delete</param>
/// <returns><see cref="RestResponse"/></returns>
public RestResponse DeleteBacktest(int projectId, string backtestId)
{
var request = new RestRequest("backtests/delete", Method.POST)
{
RequestFormat = DataFormat.Json
};
request.AddParameter("application/json", JsonConvert.SerializeObject(new
{
projectId,
backtestId
}), ParameterType.RequestBody);
ApiConnection.TryRequest(request, out RestResponse result);
return result;
}
/// <summary>
/// Create a live algorithm.
/// </summary>
/// <param name="projectId">Id of the project on QuantConnect</param>
/// <param name="compileId">Id of the compilation on QuantConnect</param>
/// <param name="nodeId">Id of the node that will run the algorithm</param>
/// <param name="baseLiveAlgorithmSettings">Brokerage specific <see cref="BaseLiveAlgorithmSettings">BaseLiveAlgorithmSettings</see>.</param>
/// <param name="versionId">The version of the Lean used to run the algorithm.
/// -1 is master, however, sometimes this can create problems with live deployments.
/// If you experience problems using, try specifying the version of Lean you would like to use.</param>
/// <returns>Information regarding the new algorithm <see cref="LiveAlgorithm"/></returns>
public LiveAlgorithm CreateLiveAlgorithm(int projectId,
string compileId,
string nodeId,
BaseLiveAlgorithmSettings baseLiveAlgorithmSettings,
string versionId = "-1")
{
var request = new RestRequest("live/create", Method.POST)
{
RequestFormat = DataFormat.Json
};
request.AddParameter("application/json", JsonConvert.SerializeObject(
new LiveAlgorithmApiSettingsWrapper
(projectId,
compileId,
nodeId,
baseLiveAlgorithmSettings,
versionId)
), ParameterType.RequestBody);
LiveAlgorithm result;
ApiConnection.TryRequest(request, out result);
return result;
}
/// <summary>
/// Get a list of live running algorithms for user
/// </summary>
/// <param name="status">Filter the statuses of the algorithms returned from the api</param>
/// <param name="startTime">Earliest launched time of the algorithms returned by the Api</param>
/// <param name="endTime">Latest launched time of the algorithms returned by the Api</param>
/// <returns><see cref="LiveList"/></returns>
public LiveList ListLiveAlgorithms(AlgorithmStatus? status = null,
DateTime? startTime = null,
DateTime? endTime = null)
{
// Only the following statuses are supported by the Api
if (status.HasValue &&
status != AlgorithmStatus.Running &&
status != AlgorithmStatus.RuntimeError &&
status != AlgorithmStatus.Stopped &&
status != AlgorithmStatus.Liquidated)
{
throw new ArgumentException(
"The Api only supports Algorithm Statuses of Running, Stopped, RuntimeError and Liquidated");
}
var request = new RestRequest("live/read", Method.POST)
{
RequestFormat = DataFormat.Json
};
var epochStartTime = startTime == null ? 0 : Time.DateTimeToUnixTimeStamp(startTime.Value);
var epochEndTime = endTime == null ? Time.DateTimeToUnixTimeStamp(DateTime.UtcNow) : Time.DateTimeToUnixTimeStamp(endTime.Value);
JObject obj = new JObject
{
{ "start", epochStartTime },
{ "end", epochEndTime }
};
if (status.HasValue)
{
obj.Add("status", status.ToString());
}
request.AddParameter("application/json", JsonConvert.SerializeObject(obj), ParameterType.RequestBody);
ApiConnection.TryRequest(request, out LiveList result);
return result;
}
/// <summary>
/// Read out a live algorithm in the project id specified.
/// </summary>
/// <param name="projectId">Project id to read</param>
/// <param name="deployId">Specific instance id to read</param>
/// <returns><see cref="LiveAlgorithmResults"/></returns>
public LiveAlgorithmResults ReadLiveAlgorithm(int projectId, string deployId)
{
var request = new RestRequest("live/read", Method.POST)
{
RequestFormat = DataFormat.Json
};
request.AddParameter("application/json", JsonConvert.SerializeObject(new
{
projectId,
deployId
}), ParameterType.RequestBody);
ApiConnection.TryRequest(request, out LiveAlgorithmResults result);
return result;
}
/// <summary>
/// Liquidate a live algorithm from the specified project and deployId.
/// </summary>
/// <param name="projectId">Project for the live instance we want to stop</param>
/// <returns><see cref="RestResponse"/></returns>
public RestResponse LiquidateLiveAlgorithm(int projectId)
{
var request = new RestRequest("live/update/liquidate", Method.POST)
{
RequestFormat = DataFormat.Json
};
request.AddParameter("application/json", JsonConvert.SerializeObject(new
{
projectId
}), ParameterType.RequestBody);
ApiConnection.TryRequest(request, out RestResponse result);
return result;
}
/// <summary>
/// Stop a live algorithm from the specified project and deployId.
/// </summary>
/// <param name="projectId">Project for the live instance we want to stop</param>
/// <returns><see cref="RestResponse"/></returns>
public RestResponse StopLiveAlgorithm(int projectId)
{
var request = new RestRequest("live/update/stop", Method.POST)
{
RequestFormat = DataFormat.Json
};
request.AddParameter("application/json", JsonConvert.SerializeObject(new
{
projectId
}), ParameterType.RequestBody);
ApiConnection.TryRequest(request, out RestResponse result);
return result;
}
/// <summary>
/// Gets the logs of a specific live algorithm
/// </summary>
/// <param name="projectId">Project Id of the live running algorithm</param>
/// <param name="algorithmId">Algorithm Id of the live running algorithm</param>
/// <param name="startTime">No logs will be returned before this time</param>
/// <param name="endTime">No logs will be returned after this time</param>
/// <returns><see cref="LiveLog"/> List of strings that represent the logs of the algorithm</returns>
public LiveLog ReadLiveLogs(int projectId, string algorithmId, DateTime? startTime = null, DateTime? endTime = null)
{
var epochStartTime = startTime == null ? 0 : Time.DateTimeToUnixTimeStamp(startTime.Value);
var epochEndTime = endTime == null ? Time.DateTimeToUnixTimeStamp(DateTime.UtcNow) : Time.DateTimeToUnixTimeStamp(endTime.Value);
var request = new RestRequest("live/read/log", Method.POST)
{
RequestFormat = DataFormat.Json
};
request.AddParameter("application/json", JsonConvert.SerializeObject(new
{
format = "json",
projectId,
algorithmId,
start = epochStartTime,
end = epochEndTime
}), ParameterType.RequestBody);
ApiConnection.TryRequest(request, out LiveLog result);
return result;
}
/// <summary>
/// Gets the link to the downloadable data.
/// </summary>
/// <param name="filePath">File path representing the data requested</param>
/// <param name="organizationId">Organization to download from</param>
/// <returns><see cref="Link"/> to the downloadable data.</returns>
public DataLink ReadDataLink(string filePath, string organizationId)
{
if (filePath == null)
{
throw new ArgumentException("Api.ReadDataLink(): Filepath must not be null");
}
// Prepare filePath for request
filePath = FormatPathForDataRequest(filePath);
var request = new RestRequest("data/read", Method.POST)
{
RequestFormat = DataFormat.Json
};
request.AddParameter("application/json", JsonConvert.SerializeObject(new
{
format = "link",
filePath,
organizationId
}), ParameterType.RequestBody);
ApiConnection.TryRequest(request, out DataLink result);
return result;
}
/// <summary>
/// Get valid data entries for a given filepath from data/list
/// </summary>
/// <returns></returns>
public DataList ReadDataDirectory(string filePath)
{
if (filePath == null)
{
throw new ArgumentException("Api.ReadDataDirectory(): Filepath must not be null");
}
// Prepare filePath for request
filePath = FormatPathForDataRequest(filePath);
// Verify the filePath for this request is at least three directory deep
// (requirement of endpoint)
if (filePath.Count(x => x == '/') < 3)
{
throw new ArgumentException($"Api.ReadDataDirectory(): Data directory requested must be at least" +
$" three directories deep. FilePath: {filePath}");
}
var request = new RestRequest("data/list", Method.POST)
{
RequestFormat = DataFormat.Json
};
request.AddParameter("application/json", JsonConvert.SerializeObject(new
{
filePath
}), ParameterType.RequestBody);
ApiConnection.TryRequest(request, out DataList result);
return result;
}
/// <summary>
/// Gets data prices from data/prices
/// </summary>
public DataPricesList ReadDataPrices(string organizationId)
{
var request = new RestRequest("data/prices", Method.POST)
{
RequestFormat = DataFormat.Json
};
request.AddParameter("application/json", JsonConvert.SerializeObject(new
{
organizationId
}), ParameterType.RequestBody);
ApiConnection.TryRequest(request, out DataPricesList result);
return result;
}
/// <summary>
/// Read out the report of a backtest in the project id specified.
/// </summary>
/// <param name="projectId">Project id to read</param>
/// <param name="backtestId">Specific backtest id to read</param>
/// <returns><see cref="BacktestReport"/></returns>
public BacktestReport ReadBacktestReport(int projectId, string backtestId)
{
var request = new RestRequest("backtests/read/report", Method.POST)
{
RequestFormat = DataFormat.Json
};
request.AddParameter("application/json", JsonConvert.SerializeObject(new
{
backtestId,
projectId
}), ParameterType.RequestBody);
ApiConnection.TryRequest(request, out BacktestReport report);
return report;
}
/// <summary>
/// Method to purchase and download data from QuantConnect
/// </summary>
/// <param name="filePath">File path representing the data requested</param>
/// <param name="organizationId">Organization to buy the data with</param>
/// <returns>A <see cref="bool"/> indicating whether the data was successfully downloaded or not.</returns>
public bool DownloadData(string filePath, string organizationId)
{
// Get a link to the data
var dataLink = ReadDataLink(filePath, organizationId);
// Make sure the link was successfully retrieved
if (!dataLink.Success)
{
Log.Trace($"Api.DownloadData(): Failed to get link for {filePath}. " +
$"Errors: {string.Join(',', dataLink.Errors)}");
return false;
}
// Make sure the directory exist before writing
var directory = Path.GetDirectoryName(filePath);
if (!Directory.Exists(directory))
{
Directory.CreateDirectory(directory);
}
try
{
// Download the file
var uri = new Uri(dataLink.Url);
using var client = new HttpClient();
using var dataStream = client.GetStreamAsync(uri);
using var fileStream = new FileStream(filePath, FileMode.Create);
dataStream.Result.CopyTo(fileStream);
}
catch
{
Log.Error($"Api.DownloadData(): Failed to download zip for path ({filePath})");
return false;
}
return true;
}
/// <summary>
/// Get the algorithm status from the user with this algorithm id.
/// </summary>
/// <param name="algorithmId">String algorithm id we're searching for.</param>
/// <returns>Algorithm status enum</returns>
public virtual AlgorithmControl GetAlgorithmStatus(string algorithmId)
{
return new AlgorithmControl()
{
ChartSubscription = "*"
};
}
/// <summary>
/// Algorithm passes back its current status to the UX.
/// </summary>
/// <param name="status">Status of the current algorithm</param>
/// <param name="algorithmId">String algorithm id we're setting.</param>
/// <param name="message">Message for the algorithm status event</param>
/// <returns>Algorithm status enum</returns>
public virtual void SetAlgorithmStatus(string algorithmId, AlgorithmStatus status, string message = "")
{
//
}
/// <summary>
/// Send the statistics to storage for performance tracking.
/// </summary>
/// <param name="algorithmId">Identifier for algorithm</param>
/// <param name="unrealized">Unrealized gainloss</param>
/// <param name="fees">Total fees</param>
/// <param name="netProfit">Net profi</param>
/// <param name="holdings">Algorithm holdings</param>
/// <param name="equity">Total equity</param>
/// <param name="netReturn">Net return for the deployment</param>
/// <param name="volume">Volume traded</param>
/// <param name="trades">Total trades since inception</param>
/// <param name="sharpe">Sharpe ratio since inception</param>
public virtual void SendStatistics(string algorithmId, decimal unrealized, decimal fees, decimal netProfit, decimal holdings, decimal equity, decimal netReturn, decimal volume, int trades, double sharpe)
{
//
}
/// <summary>
/// Send an email to the user associated with the specified algorithm id
/// </summary>
/// <param name="algorithmId">The algorithm id</param>
/// <param name="subject">The email subject</param>
/// <param name="body">The email message body</param>
public virtual void SendUserEmail(string algorithmId, string subject, string body)
{
//
}
/// <summary>
/// Local implementation for downloading data to algorithms
/// </summary>
/// <param name="address">URL to download</param>
/// <param name="headers">KVP headers</param>
/// <param name="userName">Username for basic authentication</param>
/// <param name="password">Password for basic authentication</param>
/// <returns></returns>
public virtual string Download(string address, IEnumerable<KeyValuePair<string, string>> headers, string userName, string password)
{
using (var client = new WebClient { Credentials = new NetworkCredential(userName, password) })
{
client.Proxy = WebRequest.GetSystemWebProxy();
if (headers != null)
{
foreach (var header in headers)
{
client.Headers.Add(header.Key, header.Value);
}
}
// Add a user agent header in case the requested URI contains a query.
client.Headers.Add("user-agent", "QCAlgorithm.Download(): User Agent Header");
try
{
return client.DownloadString(address);
}
catch (WebException exception)
{
var message = $"Api.Download(): Failed to download data from {address}";
if (!userName.IsNullOrEmpty() || !password.IsNullOrEmpty())
{
message += $" with username: {userName} and password {password}";
}
throw new WebException($"{message}. Please verify the source for missing http:// or https://", exception);
}
}
}
/// <summary>
/// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
/// </summary>
/// <filterpriority>2</filterpriority>
public virtual void Dispose()
{
// NOP
}
/// <summary>
/// Generate a secure hash for the authorization headers.
/// </summary>
/// <returns>Time based hash of user token and timestamp.</returns>
public static string CreateSecureHash(int timestamp, string token)
{
// Create a new hash using current UTC timestamp.
// Hash must be generated fresh each time.
var data = $"{token}:{timestamp.ToStringInvariant()}";
return data.ToSHA256();
}
/// <summary>
/// Create a new node in the organization, node configuration is defined by the
/// <see cref="SKU"/>
/// </summary>
/// <param name="name">The name of the new node</param>
/// <param name="organizationId">ID of the organization</param>
/// <param name="sku"><see cref="SKU"/> Object representing configuration</param>
/// <returns>Returns <see cref="CreatedNode"/> which contains API response and
/// <see cref="Node"/></returns>
public CreatedNode CreateNode(string name, string organizationId, SKU sku)
{
var request = new RestRequest("nodes/create", Method.POST)
{
RequestFormat = DataFormat.Json
};
request.AddParameter("application/json", JsonConvert.SerializeObject(new
{
name,
organizationId,
sku = sku.ToString()
}), ParameterType.RequestBody);
ApiConnection.TryRequest(request, out CreatedNode result);
return result;
}
/// <summary>
/// Reads the nodes associated with the organization, creating a
/// <see cref="NodeList"/> for the response
/// </summary>
/// <param name="organizationId">ID of the organization</param>
/// <returns><see cref="NodeList"/> containing Backtest, Research, and Live Nodes</returns>
public NodeList ReadNodes(string organizationId)
{
var request = new RestRequest("nodes/read", Method.POST)
{
RequestFormat = DataFormat.Json
};
request.AddParameter("application/json", JsonConvert.SerializeObject(new
{
organizationId,
}), ParameterType.RequestBody);
ApiConnection.TryRequest(request, out NodeList result);
return result;
}
/// <summary>
/// Update an organizations node with a new name
/// </summary>
/// <param name="nodeId">The node ID of the node you want to update</param>
/// <param name="newName">The new name for that node</param>
/// <param name="organizationId">ID of the organization</param>
/// <returns><see cref="RestResponse"/> containing success response and errors</returns>
public RestResponse UpdateNode(string nodeId, string newName, string organizationId)
{
var request = new RestRequest("nodes/update", Method.POST)
{
RequestFormat = DataFormat.Json
};
request.AddParameter("application/json", JsonConvert.SerializeObject(new
{
nodeId,
name = newName,
organizationId
}), ParameterType.RequestBody);
ApiConnection.TryRequest(request, out RestResponse result);
return result;
}
/// <summary>
/// Delete a node from an organization, requires node ID.
/// </summary>
/// <param name="nodeId">The node ID of the node you want to delete</param>
/// <param name="organizationId">ID of the organization</param>
/// <returns><see cref="RestResponse"/> containing success response and errors</returns>
public RestResponse DeleteNode(string nodeId, string organizationId)
{
var request = new RestRequest("nodes/delete", Method.POST)
{
RequestFormat = DataFormat.Json
};
request.AddParameter("application/json", JsonConvert.SerializeObject(new
{
nodeId,
organizationId
}), ParameterType.RequestBody);
ApiConnection.TryRequest(request, out RestResponse result);
return result;
}
/// <summary>
/// Stop a running node in a organization
/// </summary>
/// <param name="nodeId">The node ID of the node you want to stop</param>
/// <param name="organizationId">ID of the organization</param>
/// <returns><see cref="RestResponse"/> containing success response and errors</returns>
public RestResponse StopNode(string nodeId, string organizationId)
{
var request = new RestRequest("nodes/stop", Method.POST)
{
RequestFormat = DataFormat.Json
};
request.AddParameter("application/json", JsonConvert.SerializeObject(new
{
nodeId,
organizationId
}), ParameterType.RequestBody);
ApiConnection.TryRequest(request, out RestResponse result);
return result;
}
/// <summary>
/// Will read the organization account status
/// </summary>
/// <param name="organizationId">The target organization id, if null will return default organization</param>
public Account ReadAccount(string organizationId = null)
{
var request = new RestRequest("account/read", Method.POST)
{
RequestFormat = DataFormat.Json
};
if (organizationId != null)
{
request.AddParameter("application/json", JsonConvert.SerializeObject(new { organizationId }), ParameterType.RequestBody);
}
ApiConnection.TryRequest(request, out Account account);
return account;
}
/// <summary>
/// Get a list of organizations tied to this account
/// </summary>
/// <returns></returns>
public List<Organization> ListOrganizations()
{
var request = new RestRequest("organizations/list", Method.POST)
{
RequestFormat = DataFormat.Json
};
ApiConnection.TryRequest(request, out OrganizationResponseList response);
return response.List;
}
/// <summary>
/// Fetch organization data from web API
/// </summary>
/// <param name="organizationId"></param>
/// <returns></returns>
public Organization ReadOrganization(string organizationId = null)
{
var request = new RestRequest("organizations/read", Method.POST)
{
RequestFormat = DataFormat.Json
};
if (organizationId != null)
{
request.AddParameter("application/json", JsonConvert.SerializeObject(new { organizationId }), ParameterType.RequestBody);
}
ApiConnection.TryRequest(request, out OrganizationResponse response);
return response.Organization;
}
/// <summary>
/// Helper method to normalize path for api data requests
/// </summary>
/// <param name="filePath">Filepath to format</param>
/// <returns>Normalized path</returns>
public string FormatPathForDataRequest(string filePath)
{
if (filePath == null)
{
Log.Error("Api.FormatPathForDataRequest(): Cannot format null string");
return null;
}
// Normalize windows paths to linux format
filePath = filePath.Replace("\\", "/", StringComparison.InvariantCulture);
// First remove data root directory from path for request if included
if (filePath.StartsWith(_dataFolder, StringComparison.InvariantCulture))
{
filePath = filePath.Substring(_dataFolder.Length);
}
// Trim '/' from start, this can cause issues for _dataFolders without final directory separator in the config
filePath = filePath.TrimStart('/');
return filePath;
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using Xunit;
namespace System.ComponentModel.EventBasedAsync.Tests
{
public class BackgroundWorkerTests
{
private const int TimeoutShort = 300;
private const int TimeoutLong = 30000;
[Fact]
public void TestBackgroundWorkerBasic()
{
var orignal = SynchronizationContext.Current;
try
{
SynchronizationContext.SetSynchronizationContext(null);
const int expectedResult = 42;
const int expectedReportCallsCount = 5;
int actualReportCallsCount = 0;
var worker = new BackgroundWorker() { WorkerReportsProgress = true };
var progressBarrier = new Barrier(2, barrier => ++actualReportCallsCount);
var workerCompletedEvent = new ManualResetEventSlim(false);
worker.DoWork += (sender, e) =>
{
for (int i = 0; i < expectedReportCallsCount; i++)
{
worker.ReportProgress(i);
progressBarrier.SignalAndWait();
}
e.Result = expectedResult;
};
worker.RunWorkerCompleted += (sender, e) =>
{
try
{
Assert.Equal(expectedResult, (int)e.Result);
Assert.False(worker.IsBusy);
}
finally
{
workerCompletedEvent.Set();
}
};
worker.ProgressChanged += (sender, e) =>
{
progressBarrier.SignalAndWait();
};
worker.RunWorkerAsync();
// wait for singal from WhenRunWorkerCompleted
Assert.True(workerCompletedEvent.Wait(TimeoutLong));
Assert.False(worker.IsBusy);
Assert.Equal(expectedReportCallsCount, actualReportCallsCount);
}
finally
{
SynchronizationContext.SetSynchronizationContext(orignal);
}
}
#region TestCancelAsync
private ManualResetEventSlim manualResetEvent3;
[Fact]
public void TestCancelAsync()
{
BackgroundWorker bw = new BackgroundWorker();
bw.DoWork += DoWorkExpectCancel;
bw.WorkerSupportsCancellation = true;
manualResetEvent3 = new ManualResetEventSlim(false);
bw.RunWorkerAsync("Message");
bw.CancelAsync();
bool ret = manualResetEvent3.Wait(TimeoutLong);
Assert.True(ret);
// there could be race condition between worker thread cancellation and completion which will set the CancellationPending to false
// if it is completed already, we don't check cancellation
if (bw.IsBusy) // not complete
{
if (!bw.CancellationPending)
{
for (int i = 0; i < 1000; i++)
{
Wait(TimeoutShort);
if (bw.CancellationPending)
{
break;
}
}
}
// Check again
if (bw.IsBusy)
Assert.True(bw.CancellationPending, "Cancellation in Main thread");
}
}
private void DoWorkExpectCancel(object sender, DoWorkEventArgs e)
{
Assert.Equal("Message", e.Argument);
var bw = sender as BackgroundWorker;
if (bw.CancellationPending)
{
manualResetEvent3.Set();
return;
}
// we want to wait for cancellation - wait max (1000 * TimeoutShort) milliseconds
for (int i = 0; i < 1000; i++)
{
Wait(TimeoutShort);
if (bw.CancellationPending)
{
break;
}
}
Assert.True(bw.CancellationPending, "Cancellation in Worker thread");
// signal no matter what, even if it's not cancelled by now
manualResetEvent3.Set();
}
#endregion
[Fact]
public void TestThrowExceptionInDoWork()
{
var original = SynchronizationContext.Current;
try
{
SynchronizationContext.SetSynchronizationContext(null);
const string expectedArgument = "Exception";
const string expectedExceptionMsg = "Exception from DoWork";
var bw = new BackgroundWorker();
var workerCompletedEvent = new ManualResetEventSlim(false);
bw.DoWork += (sender, e) =>
{
Assert.Same(bw, sender);
Assert.Same(expectedArgument, e.Argument);
throw new TestException(expectedExceptionMsg);
};
bw.RunWorkerCompleted += (sender, e) =>
{
try
{
TestException ex = Assert.Throws<TestException>(() => e.Result);
Assert.Equal(expectedExceptionMsg, ex.Message);
}
finally
{
workerCompletedEvent.Set();
}
};
bw.RunWorkerAsync(expectedArgument);
Assert.True(workerCompletedEvent.Wait(TimeoutLong), "Background work timeout");
}
finally
{
SynchronizationContext.SetSynchronizationContext(original);
}
}
[Fact]
public void CtorTest()
{
var bw = new BackgroundWorker();
Assert.False(bw.IsBusy);
Assert.False(bw.WorkerReportsProgress);
Assert.False(bw.WorkerSupportsCancellation);
Assert.False(bw.CancellationPending);
}
[Fact]
public void RunWorkerAsyncTwice()
{
var bw = new BackgroundWorker();
var barrier = new Barrier(2);
bw.DoWork += (sender, e) =>
{
barrier.SignalAndWait();
barrier.SignalAndWait();
};
bw.RunWorkerAsync();
barrier.SignalAndWait();
try
{
Assert.True(bw.IsBusy);
Assert.Throws<InvalidOperationException>(() => bw.RunWorkerAsync());
}
finally
{
barrier.SignalAndWait();
}
}
[Fact]
public void TestCancelInsideDoWork()
{
var original = SynchronizationContext.Current;
try
{
SynchronizationContext.SetSynchronizationContext(null);
var bw = new BackgroundWorker() { WorkerSupportsCancellation = true };
var barrier = new Barrier(2);
bw.DoWork += (sender, e) =>
{
barrier.SignalAndWait();
barrier.SignalAndWait();
if (bw.CancellationPending)
{
e.Cancel = true;
}
};
bw.RunWorkerCompleted += (sender, e) =>
{
Assert.True(e.Cancelled);
barrier.SignalAndWait();
};
bw.RunWorkerAsync();
barrier.SignalAndWait();
bw.CancelAsync();
barrier.SignalAndWait();
Assert.True(barrier.SignalAndWait(TimeoutLong), "Background work timeout");
}
finally
{
SynchronizationContext.SetSynchronizationContext(original);
}
}
[Fact]
public void TestCancelAsyncWithoutCancellationSupport()
{
var bw = new BackgroundWorker() { WorkerSupportsCancellation = false };
Assert.Throws<InvalidOperationException>(() => bw.CancelAsync());
}
[Fact]
public void TestReportProgressSync()
{
var bw = new BackgroundWorker() { WorkerReportsProgress = true };
var expectedProgress = new int[] { 1, 2, 3, 4, 5 };
var actualProgress = new List<int>();
bw.ProgressChanged += (sender, e) =>
{
actualProgress.Add(e.ProgressPercentage);
};
foreach (int i in expectedProgress)
{
bw.ReportProgress(i);
}
Assert.Equal(expectedProgress, actualProgress);
}
[Fact]
public void TestReportProgressWithWorkerReportsProgressFalse()
{
var bw = new BackgroundWorker() { WorkerReportsProgress = false };
Assert.Throws<InvalidOperationException>(() => bw.ReportProgress(42));
}
[Fact]
public void DisposeTwiceShouldNotThrow()
{
var bw = new BackgroundWorker();
bw.Dispose();
bw.Dispose();
}
private static void Wait(int milliseconds)
{
Task.Delay(milliseconds).Wait();
}
}
}
| |
//------------------------------------------------------------------------------
// <copyright file="ClientSettingsStore.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//------------------------------------------------------------------------------
using System.Diagnostics.CodeAnalysis;
[assembly: SuppressMessage("Microsoft.Reliability", "CA2000:DisposeObjectsBeforeLosingScope", Scope="member", Target="System.Configuration.ClientSettingsStore+QuotaEnforcedStream.Dispose(System.Boolean):System.Void")]
namespace System.Configuration {
using System;
using System.Collections;
using System.Collections.Specialized;
using System.Configuration;
using System.Configuration.Internal;
using System.Configuration.Provider;
using System.Diagnostics;
using System.IO;
using System.Security;
using System.Security.Permissions;
using System.Xml;
/// <devdoc>
/// This class abstracts the details of config system away from the LocalFileSettingsProvider. It talks to
/// the configuration API and the relevant Sections to read and write settings.
/// It understands sections of type ClientSettingsSection.
///
/// NOTE: This API supports reading from app.exe.config and user.config, but writing only to
/// user.config.
/// </devdoc>
internal sealed class ClientSettingsStore {
private const string ApplicationSettingsGroupName = "applicationSettings";
private const string UserSettingsGroupName = "userSettings";
private const string ApplicationSettingsGroupPrefix = ApplicationSettingsGroupName + "/";
private const string UserSettingsGroupPrefix = UserSettingsGroupName + "/";
private Configuration GetUserConfig(bool isRoaming) {
ConfigurationUserLevel userLevel = isRoaming ? ConfigurationUserLevel.PerUserRoaming :
ConfigurationUserLevel.PerUserRoamingAndLocal;
return ClientSettingsConfigurationHost.OpenExeConfiguration(userLevel);
}
private ClientSettingsSection GetConfigSection(Configuration config, string sectionName, bool declare) {
string fullSectionName = UserSettingsGroupPrefix + sectionName;
ClientSettingsSection section = null;
if (config != null) {
section = config.GetSection(fullSectionName) as ClientSettingsSection;
if (section == null && declare) {
// Looks like the section isn't declared - let's declare it and try again.
DeclareSection(config, sectionName);
section = config.GetSection(fullSectionName) as ClientSettingsSection;
}
}
return section;
}
// Declares the section handler of a given section in its section group, if a declaration isn't already
// present.
private void DeclareSection(Configuration config, string sectionName) {
ConfigurationSectionGroup settingsGroup = config.GetSectionGroup(UserSettingsGroupName);
if (settingsGroup == null) {
//Declare settings group
ConfigurationSectionGroup group = new UserSettingsGroup();
config.SectionGroups.Add(UserSettingsGroupName, group);
}
settingsGroup = config.GetSectionGroup(UserSettingsGroupName);
Debug.Assert(settingsGroup != null, "Failed to declare settings group");
if (settingsGroup != null) {
ConfigurationSection section = settingsGroup.Sections[sectionName];
if (section == null) {
section = new ClientSettingsSection();
section.SectionInformation.AllowExeDefinition = ConfigurationAllowExeDefinition.MachineToLocalUser;
section.SectionInformation.RequirePermission = false;
settingsGroup.Sections.Add(sectionName, section);
}
}
}
internal IDictionary ReadSettings(string sectionName, bool isUserScoped) {
IDictionary settings = new Hashtable();
if( isUserScoped && !ConfigurationManagerInternalFactory.Instance.SupportsUserConfig) {
return settings;
}
string prefix = isUserScoped ? UserSettingsGroupPrefix : ApplicationSettingsGroupPrefix;
ConfigurationManager.RefreshSection(prefix + sectionName);
ClientSettingsSection section = ConfigurationManager.GetSection(prefix + sectionName) as ClientSettingsSection;
if (section != null) {
foreach (SettingElement setting in section.Settings) {
settings[setting.Name] = new StoredSetting(setting.SerializeAs, setting.Value.ValueXml);
}
}
return settings;
}
internal static IDictionary ReadSettingsFromFile(string configFileName, string sectionName, bool isUserScoped) {
IDictionary settings = new Hashtable();
if( isUserScoped && !ConfigurationManagerInternalFactory.Instance.SupportsUserConfig) {
return settings;
}
string prefix = isUserScoped ? UserSettingsGroupPrefix : ApplicationSettingsGroupPrefix;
ExeConfigurationFileMap fileMap = new ExeConfigurationFileMap();
// NOTE: When isUserScoped is true, we don't care if configFileName represents a roaming file or
// a local one. All we want is three levels of configuration. So, we use the PerUserRoaming level.
ConfigurationUserLevel userLevel = isUserScoped ? ConfigurationUserLevel.PerUserRoaming : ConfigurationUserLevel.None;
if (isUserScoped) {
fileMap.ExeConfigFilename = ConfigurationManagerInternalFactory.Instance.ApplicationConfigUri;
fileMap.RoamingUserConfigFilename = configFileName;
}
else {
fileMap.ExeConfigFilename = configFileName;
}
Configuration config = ConfigurationManager.OpenMappedExeConfiguration(fileMap, userLevel);
ClientSettingsSection section = config.GetSection(prefix + sectionName) as ClientSettingsSection;
if (section != null) {
foreach (SettingElement setting in section.Settings) {
settings[setting.Name] = new StoredSetting(setting.SerializeAs, setting.Value.ValueXml);
}
}
return settings;
}
internal ConnectionStringSettingsCollection ReadConnectionStrings() {
return PrivilegedConfigurationManager.ConnectionStrings;
}
internal void RevertToParent(string sectionName, bool isRoaming) {
if (!ConfigurationManagerInternalFactory.Instance.SupportsUserConfig) {
throw new ConfigurationErrorsException(SR.GetString(SR.UserSettingsNotSupported));
}
Configuration config = GetUserConfig(isRoaming);
ClientSettingsSection section = GetConfigSection(config, sectionName, false);
// If the section is null, there is nothing to revert.
if (section != null) {
section.SectionInformation.RevertToParent();
config.Save();
}
}
internal void WriteSettings(string sectionName, bool isRoaming, IDictionary newSettings) {
if (!ConfigurationManagerInternalFactory.Instance.SupportsUserConfig) {
throw new ConfigurationErrorsException(SR.GetString(SR.UserSettingsNotSupported));
}
Configuration config = GetUserConfig(isRoaming);
ClientSettingsSection section = GetConfigSection(config, sectionName, true);
if (section != null) {
SettingElementCollection sec = section.Settings;
foreach (DictionaryEntry entry in newSettings) {
SettingElement se = sec.Get((string) entry.Key);
if (se == null) {
se = new SettingElement();
se.Name = (string) entry.Key;
sec.Add(se);
}
StoredSetting ss = (StoredSetting) entry.Value;
se.SerializeAs = ss.SerializeAs;
se.Value.ValueXml = ss.Value;
}
try {
config.Save();
}
catch (ConfigurationErrorsException ex) {
// We wrap this in an exception with our error message and throw again.
throw new ConfigurationErrorsException(SR.GetString(SR.SettingsSaveFailed, ex.Message), ex);
}
}
else {
throw new ConfigurationErrorsException(SR.GetString(SR.SettingsSaveFailedNoSection));
}
}
/// <devdoc>
/// A private configuration host that we use to write settings to config. We need this so we
/// can enforce a quota on the size of stuff written out.
/// </devdoc>
private sealed class ClientSettingsConfigurationHost : DelegatingConfigHost {
private const string ClientConfigurationHostTypeName = "System.Configuration.ClientConfigurationHost," + AssemblyRef.SystemConfiguration;
private const string InternalConfigConfigurationFactoryTypeName = "System.Configuration.Internal.InternalConfigConfigurationFactory," + AssemblyRef.SystemConfiguration;
private static volatile IInternalConfigConfigurationFactory s_configFactory;
/// <devdoc>
/// ClientConfigurationHost implements this - a way of getting some info from it without
/// depending too much on its internals.
/// </devdoc>
private IInternalConfigClientHost ClientHost {
get {
return (IInternalConfigClientHost) Host;
}
}
internal static IInternalConfigConfigurationFactory ConfigFactory {
get {
if (s_configFactory == null) {
s_configFactory = (IInternalConfigConfigurationFactory)
TypeUtil.CreateInstanceWithReflectionPermission(InternalConfigConfigurationFactoryTypeName);
}
return s_configFactory;
}
}
private ClientSettingsConfigurationHost() {}
public override void Init(IInternalConfigRoot configRoot, params object[] hostInitParams) {
Debug.Fail("Did not expect to get called here");
}
/// <devdoc>
/// We delegate this to the ClientConfigurationHost. The only thing we need to do here is to
/// build a configPath from the ConfigurationUserLevel we get passed in.
/// </devdoc>
public override void InitForConfiguration(ref string locationSubPath, out string configPath, out string locationConfigPath,
IInternalConfigRoot configRoot, params object[] hostInitConfigurationParams) {
ConfigurationUserLevel userLevel = (ConfigurationUserLevel) hostInitConfigurationParams[0];
string desiredConfigPath = null;
Host = (IInternalConfigHost) TypeUtil.CreateInstanceWithReflectionPermission(ClientConfigurationHostTypeName);
switch (userLevel) {
case ConfigurationUserLevel.None:
desiredConfigPath = ClientHost.GetExeConfigPath();
break;
case ConfigurationUserLevel.PerUserRoaming:
desiredConfigPath = ClientHost.GetRoamingUserConfigPath();
break;
case ConfigurationUserLevel.PerUserRoamingAndLocal:
desiredConfigPath = ClientHost.GetLocalUserConfigPath();
break;
default:
throw new ArgumentException(SR.GetString(SR.UnknownUserLevel));
}
Host.InitForConfiguration(ref locationSubPath, out configPath, out locationConfigPath, configRoot, null, null, desiredConfigPath);
}
private bool IsKnownConfigFile(string filename) {
return
String.Equals(filename, ConfigurationManagerInternalFactory.Instance.MachineConfigPath, StringComparison.OrdinalIgnoreCase) ||
String.Equals(filename, ConfigurationManagerInternalFactory.Instance.ApplicationConfigUri, StringComparison.OrdinalIgnoreCase) ||
String.Equals(filename, ConfigurationManagerInternalFactory.Instance.ExeLocalConfigPath, StringComparison.OrdinalIgnoreCase) ||
String.Equals(filename, ConfigurationManagerInternalFactory.Instance.ExeRoamingConfigPath, StringComparison.OrdinalIgnoreCase);
}
internal static Configuration OpenExeConfiguration(ConfigurationUserLevel userLevel) {
return ConfigFactory.Create(typeof(ClientSettingsConfigurationHost), userLevel);
}
/// <devdoc>
/// If the stream we are asked for represents a config file that we know about, we ask
/// the host to assert appropriate permissions.
/// </devdoc>
public override Stream OpenStreamForRead(string streamName) {
if (IsKnownConfigFile(streamName)) {
return Host.OpenStreamForRead(streamName, true);
}
else {
return Host.OpenStreamForRead(streamName);
}
}
/// <devdoc>
/// If the stream we are asked for represents a user.config file that we know about, we wrap it in a
/// QuotaEnforcedStream, after asking the host to assert appropriate permissions.///
/// </devdoc>
public override Stream OpenStreamForWrite(string streamName, string templateStreamName, ref object writeContext) {
Stream stream = null;
if (String.Equals(streamName, ConfigurationManagerInternalFactory.Instance.ExeLocalConfigPath, StringComparison.OrdinalIgnoreCase)) {
stream = new QuotaEnforcedStream(
Host.OpenStreamForWrite(streamName, templateStreamName, ref writeContext, true),
false);
}
else if (String.Equals(streamName, ConfigurationManagerInternalFactory.Instance.ExeRoamingConfigPath, StringComparison.OrdinalIgnoreCase)) {
stream = new QuotaEnforcedStream(
Host.OpenStreamForWrite(streamName, templateStreamName, ref writeContext, true),
true);
}
else {
stream = Host.OpenStreamForWrite(streamName, templateStreamName, ref writeContext);
}
return stream;
}
/// <devdoc>
/// If this is a stream that represents a user.config file that we know about, we ask
/// the host to assert appropriate permissions.
/// </devdoc>
public override void WriteCompleted(string streamName, bool success, object writeContext) {
if (String.Equals(streamName, ConfigurationManagerInternalFactory.Instance.ExeLocalConfigPath, StringComparison.OrdinalIgnoreCase) ||
String.Equals(streamName, ConfigurationManagerInternalFactory.Instance.ExeRoamingConfigPath, StringComparison.OrdinalIgnoreCase)) {
Host.WriteCompleted(streamName, success, writeContext, true);
}
else {
Host.WriteCompleted(streamName, success, writeContext);
}
}
}
/// <devdoc>
/// A private stream class that wraps a stream and enforces a quota. The quota enforcement uses
/// IsolatedStorageFilePermission. We override nearly all methods on the Stream class so we can
/// forward to the wrapped stream. In the methods that affect stream length, we verify that the
/// quota is respected before forwarding.
/// </devdoc>
private sealed class QuotaEnforcedStream : Stream {
private Stream _originalStream;
private bool _isRoaming;
internal QuotaEnforcedStream(Stream originalStream, bool isRoaming) {
_originalStream = originalStream;
_isRoaming = isRoaming;
Debug.Assert(_originalStream != null, "originalStream was null.");
}
public override bool CanRead {
get { return _originalStream.CanRead; }
}
public override bool CanWrite {
get { return _originalStream.CanWrite; }
}
public override bool CanSeek {
get { return _originalStream.CanSeek; }
}
public override long Length {
get { return _originalStream.Length; }
}
public override long Position {
get { return _originalStream.Position; }
set {
if (value < 0) {
throw new ArgumentOutOfRangeException("value", SR.GetString(SR.PositionOutOfRange));
}
Seek(value, SeekOrigin.Begin);
}
}
public override void Close() {
_originalStream.Close();
}
protected override void Dispose(bool disposing) {
if (disposing) {
if (_originalStream != null) {
((IDisposable)_originalStream).Dispose();
_originalStream = null;
}
}
base.Dispose(disposing);
}
public override void Flush() {
_originalStream.Flush();
}
public override void SetLength(long value) {
long oldLen = _originalStream.Length;
long newLen = value;
EnsureQuota(Math.Max(oldLen, newLen));
_originalStream.SetLength(value);
}
public override int Read(byte[] buffer, int offset, int count) {
return _originalStream.Read(buffer, offset, count);
}
public override int ReadByte() {
return _originalStream.ReadByte();
}
public override long Seek(long offset, SeekOrigin origin) {
if (!CanSeek) {
throw new NotSupportedException();
}
long oldLen = _originalStream.Length;
long newLen;
switch (origin) {
case SeekOrigin.Begin:
newLen = offset;
break;
case SeekOrigin.Current:
newLen = _originalStream.Position + offset;
break;
case SeekOrigin.End:
newLen = oldLen + offset;
break;
default:
throw new ArgumentException(SR.GetString(SR.UnknownSeekOrigin), "origin");
}
EnsureQuota(Math.Max(oldLen, newLen));
return _originalStream.Seek(offset, origin);
}
public override void Write(byte[] buffer, int offset, int count) {
if (!CanWrite) {
throw new NotSupportedException();
}
long oldLen = _originalStream.Length;
long newLen = _originalStream.CanSeek ? _originalStream.Position + (long)count :
_originalStream.Length + (long)count;
EnsureQuota(Math.Max(oldLen, newLen));
_originalStream.Write(buffer, offset, count);
}
public override void WriteByte(byte value) {
if (!CanWrite) {
throw new NotSupportedException();
}
long oldLen = _originalStream.Length;
long newLen = _originalStream.CanSeek ? _originalStream.Position + 1 : _originalStream.Length + 1;
EnsureQuota(Math.Max(oldLen, newLen));
_originalStream.WriteByte(value);
}
public override IAsyncResult BeginRead(byte[] buffer, int offset, int numBytes,
AsyncCallback userCallback, Object stateObject) {
return _originalStream.BeginRead(buffer, offset, numBytes, userCallback, stateObject);
}
public override int EndRead(IAsyncResult asyncResult) {
return _originalStream.EndRead(asyncResult);
}
public override IAsyncResult BeginWrite(byte[] buffer, int offset, int numBytes,
AsyncCallback userCallback, Object stateObject) {
if (!CanWrite) {
throw new NotSupportedException();
}
long oldLen = _originalStream.Length;
long newLen = _originalStream.CanSeek ? _originalStream.Position + (long)numBytes :
_originalStream.Length + (long)numBytes;
EnsureQuota(Math.Max(oldLen, newLen));
return _originalStream.BeginWrite(buffer, offset, numBytes, userCallback, stateObject);
}
public override void EndWrite(IAsyncResult asyncResult) {
_originalStream.EndWrite(asyncResult);
}
//
private void EnsureQuota(long size) {
IsolatedStoragePermission storagePerm = new IsolatedStorageFilePermission(PermissionState.None);
storagePerm.UserQuota = size;
storagePerm.UsageAllowed = _isRoaming? IsolatedStorageContainment.DomainIsolationByRoamingUser :
IsolatedStorageContainment.DomainIsolationByUser;
storagePerm.Demand();
}
}
}
/// <devdoc>
/// The ClientSettingsStore talks to the LocalFileSettingsProvider through a dictionary which maps from
/// setting names to StoredSetting structs. This struct contains the relevant information.
/// </devdoc>
internal struct StoredSetting {
internal StoredSetting(SettingsSerializeAs serializeAs, XmlNode value) {
SerializeAs = serializeAs;
Value = value;
}
internal SettingsSerializeAs SerializeAs;
internal XmlNode Value;
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Xunit;
namespace System.IO.Tests
{
public abstract class FileStream_AsyncReads : FileSystemTest
{
protected virtual string BufferParamName => "buffer";
protected virtual string OffsetParamName => "offset";
protected virtual string CountParamName => "count";
protected abstract Task<int> ReadAsync(FileStream stream, byte[] buffer, int offset, int count, CancellationToken cancellationToken);
private Task<int> ReadAsync(FileStream stream, byte[] buffer, int offset, int count) =>
ReadAsync(stream, buffer, offset, count, CancellationToken.None);
[Fact]
public void NullBufferThrows()
{
using (FileStream fs = new FileStream(GetTestFilePath(), FileMode.Create))
{
AssertExtensions.Throws<ArgumentNullException>(BufferParamName, () =>
FSAssert.CompletesSynchronously(ReadAsync(fs, null, 0, 1)));
}
}
[Fact]
public void NegativeOffsetThrows()
{
using (FileStream fs = new FileStream(GetTestFilePath(), FileMode.Create))
{
AssertExtensions.Throws<ArgumentOutOfRangeException>(OffsetParamName, () =>
FSAssert.CompletesSynchronously(ReadAsync(fs, new byte[1], -1, 1)));
// buffer is checked first
AssertExtensions.Throws<ArgumentNullException>(BufferParamName, () =>
FSAssert.CompletesSynchronously(ReadAsync(fs, null, -1, 1)));
}
}
[Fact]
public void NegativeCountThrows()
{
using (FileStream fs = new FileStream(GetTestFilePath(), FileMode.Create))
{
AssertExtensions.Throws<ArgumentOutOfRangeException>(CountParamName, () =>
FSAssert.CompletesSynchronously(ReadAsync(fs, new byte[1], 0, -1)));
// offset is checked before count
AssertExtensions.Throws<ArgumentOutOfRangeException>(OffsetParamName, () =>
FSAssert.CompletesSynchronously(ReadAsync(fs, new byte[1], -1, -1)));
// buffer is checked first
AssertExtensions.Throws<ArgumentNullException>(BufferParamName, () =>
FSAssert.CompletesSynchronously(ReadAsync(fs, null, -1, -1)));
}
}
[Fact]
public void BufferOutOfBoundsThrows()
{
using (FileStream fs = new FileStream(GetTestFilePath(), FileMode.Create))
{
// offset out of bounds
Assert.Throws<ArgumentException>(null, () =>
FSAssert.CompletesSynchronously(ReadAsync(fs, new byte[1], 1, 1)));
// offset out of bounds for 0 count ReadAsync
Assert.Throws<ArgumentException>(null, () =>
FSAssert.CompletesSynchronously(ReadAsync(fs, new byte[1], 2, 0)));
// offset out of bounds even for 0 length buffer
Assert.Throws<ArgumentException>(null, () =>
FSAssert.CompletesSynchronously(ReadAsync(fs, new byte[0], 1, 0)));
// combination offset and count out of bounds
Assert.Throws<ArgumentException>(null, () =>
FSAssert.CompletesSynchronously(ReadAsync(fs, new byte[2], 1, 2)));
// edges
Assert.Throws<ArgumentException>(null, () =>
FSAssert.CompletesSynchronously(ReadAsync(fs, new byte[0], int.MaxValue, 0)));
Assert.Throws<ArgumentException>(null, () =>
FSAssert.CompletesSynchronously(ReadAsync(fs, new byte[0], int.MaxValue, int.MaxValue)));
}
}
[Fact]
public void ReadAsyncDisposedThrows()
{
using (FileStream fs = new FileStream(GetTestFilePath(), FileMode.Create))
{
fs.Dispose();
Assert.Throws<ObjectDisposedException>(() =>
FSAssert.CompletesSynchronously(ReadAsync(fs, new byte[1], 0, 1)));
// even for noop ReadAsync
Assert.Throws<ObjectDisposedException>(() =>
FSAssert.CompletesSynchronously(ReadAsync(fs, new byte[1], 0, 0)));
// out of bounds checking happens first
Assert.Throws<ArgumentException>(null, () =>
FSAssert.CompletesSynchronously(ReadAsync(fs, new byte[2], 1, 2)));
// count is checked prior
AssertExtensions.Throws<ArgumentOutOfRangeException>(CountParamName, () =>
FSAssert.CompletesSynchronously(ReadAsync(fs, new byte[1], 0, -1)));
// offset is checked prior
AssertExtensions.Throws<ArgumentOutOfRangeException>(OffsetParamName, () =>
FSAssert.CompletesSynchronously(ReadAsync(fs, new byte[1], -1, -1)));
// buffer is checked first
AssertExtensions.Throws<ArgumentNullException>(BufferParamName, () =>
FSAssert.CompletesSynchronously(ReadAsync(fs, null, -1, -1)));
}
}
[Fact]
public void WriteOnlyThrows()
{
using (FileStream fs = new FileStream(GetTestFilePath(), FileMode.Create, FileAccess.Write))
{
Assert.Throws<NotSupportedException>(() =>
FSAssert.CompletesSynchronously(ReadAsync(fs, new byte[1], 0, 1)));
fs.Dispose();
// Disposed checking happens first
Assert.Throws<ObjectDisposedException>(() =>
FSAssert.CompletesSynchronously(ReadAsync(fs, new byte[1], 0, 1)));
// out of bounds checking happens first
Assert.Throws<ArgumentException>(null, () =>
FSAssert.CompletesSynchronously(ReadAsync(fs, new byte[2], 1, 2)));
// count is checked prior
AssertExtensions.Throws<ArgumentOutOfRangeException>(CountParamName, () =>
FSAssert.CompletesSynchronously(ReadAsync(fs, new byte[1], 0, -1)));
// offset is checked prior
AssertExtensions.Throws<ArgumentOutOfRangeException>(OffsetParamName, () =>
FSAssert.CompletesSynchronously(ReadAsync(fs, new byte[1], -1, -1)));
// buffer is checked first
AssertExtensions.Throws<ArgumentNullException>(BufferParamName, () =>
FSAssert.CompletesSynchronously(ReadAsync(fs, null, -1, -1)));
}
}
[Fact]
public async Task NoopReadAsyncsSucceed()
{
using (FileStream fs = new FileStream(GetTestFilePath(), FileMode.Create))
{
// note that these do not succeed synchronously even though they do nothing.
Assert.Equal(0, await ReadAsync(fs, new byte[0], 0, 0));
Assert.Equal(0, await ReadAsync(fs, new byte[1], 0, 0));
// even though offset is out of bounds of buffer, this is still allowed
// for the last element
Assert.Equal(0, await ReadAsync(fs, new byte[1], 1, 0));
Assert.Equal(0, await ReadAsync(fs, new byte[2], 1, 0));
}
}
[Fact]
public async Task EmptyFileReadAsyncSucceedSynchronously()
{
using (FileStream fs = new FileStream(GetTestFilePath(), FileMode.Create))
{
byte[] buffer = new byte[TestBuffer.Length];
// use a recognizable pattern
TestBuffer.CopyTo(buffer, 0);
// note that these do not succeed synchronously even though they do nothing.
Assert.Equal(0, await ReadAsync(fs, buffer, 0, 1));
Assert.Equal(TestBuffer, buffer);
Assert.Equal(0, await ReadAsync(fs, buffer, 0, buffer.Length));
Assert.Equal(TestBuffer, buffer);
Assert.Equal(0, await ReadAsync(fs, buffer, buffer.Length - 1, 1));
Assert.Equal(TestBuffer, buffer);
Assert.Equal(0, await ReadAsync(fs, buffer, buffer.Length / 2, buffer.Length - buffer.Length / 2));
Assert.Equal(TestBuffer, buffer);
}
}
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "In netcoreapp we modified ReadAsync/WriteAsync to complete synchronously here, but that change was not backported to netfx.")]
public async Task ReadAsyncBufferedCompletesSynchronously()
{
string fileName = GetTestFilePath();
using (var fs = new FileStream(fileName, FileMode.Create))
{
fs.Write(TestBuffer, 0, TestBuffer.Length);
fs.Write(TestBuffer, 0, TestBuffer.Length);
}
using (var fs = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete, TestBuffer.Length * 2, useAsync: true))
{
byte[] buffer = new byte[TestBuffer.Length];
// prime the internal buffer
Assert.Equal(TestBuffer.Length, await ReadAsync(fs, buffer, 0, buffer.Length));
Assert.Equal(TestBuffer, buffer);
Array.Clear(buffer, 0, buffer.Length);
// read should now complete synchronously since it is serviced by the read buffer filled in the first request
Assert.Equal(TestBuffer.Length, FSAssert.CompletesSynchronously(ReadAsync(fs, buffer, 0, buffer.Length)));
Assert.Equal(TestBuffer, buffer);
}
}
[Fact]
public async Task ReadAsyncExistingFile()
{
string fileName = GetTestFilePath();
using (FileStream fs = new FileStream(fileName, FileMode.Create))
{
fs.Write(TestBuffer, 0, TestBuffer.Length);
}
using (FileStream fs = new FileStream(fileName, FileMode.Open))
{
byte[] buffer = new byte[TestBuffer.Length];
Assert.Equal(TestBuffer.Length, await ReadAsync(fs, buffer, 0, buffer.Length));
Assert.Equal(TestBuffer, buffer);
// ReadAsync with too large buffer at front of buffer
fs.Position = 0;
buffer = new byte[TestBuffer.Length * 2];
Assert.Equal(TestBuffer.Length, await ReadAsync(fs, buffer, 0, buffer.Length));
Assert.Equal(TestBuffer, buffer.Take(TestBuffer.Length));
// Remainder of buffer should be untouched.
Assert.Equal(new byte[buffer.Length - TestBuffer.Length], buffer.Skip(TestBuffer.Length));
// ReadAsync with too large buffer in middle of buffer
fs.Position = 0;
buffer = new byte[TestBuffer.Length * 2];
Assert.Equal(TestBuffer.Length, await ReadAsync(fs, buffer, 2, buffer.Length - 2));
Assert.Equal(TestBuffer, buffer.Skip(2).Take(TestBuffer.Length));
// Remainder of buffer should be untouched.
Assert.Equal(new byte[2], buffer.Take(2));
Assert.Equal(new byte[buffer.Length - TestBuffer.Length - 2], buffer.Skip(2 + TestBuffer.Length));
}
}
[Fact]
public async Task ReadAsyncCancelledFile()
{
string fileName = GetTestFilePath();
using (FileStream fs = new FileStream(fileName, FileMode.Create))
{
while(fs.Length < 128 * 1024)
fs.Write(TestBuffer, 0, TestBuffer.Length);
}
using (FileStream fs = new FileStream(fileName, FileMode.Open))
{
byte[] buffer = new byte[fs.Length];
CancellationTokenSource cts = new CancellationTokenSource();
Task<int> readTask = ReadAsync(fs, buffer, 0, buffer.Length, cts.Token);
cts.Cancel();
try
{
await readTask;
// we may not have canceled before the task completed.
}
catch(OperationCanceledException oce)
{
// Ideally we'd be doing an Assert.Throws<OperationCanceledException>
// but since cancellation is a race condition we accept either outcome
Assert.Equal(cts.Token, oce.CancellationToken);
}
}
}
[Fact, OuterLoop]
public async Task ReadAsyncMiniStress()
{
TimeSpan testRunTime = TimeSpan.FromSeconds(10);
const int MaximumReadSize = 16 * 1024;
const int NormalReadSize = 4 * 1024;
Random rand = new Random();
DateTime testStartTime = DateTime.UtcNow;
// Generate file data
byte[] readableFileContents = new byte[MaximumReadSize * 16];
rand.NextBytes(readableFileContents);
// Create and fill file
string readableFilePath = GetTestFilePath();
using (var stream = new FileStream(readableFilePath, FileMode.CreateNew, FileAccess.Write))
{
await stream.WriteAsync(readableFileContents, 0, readableFileContents.Length);
}
using (var stream = new FileStream(readableFilePath, FileMode.Open, FileAccess.Read))
{
// Create a new token that expires between 100-1000ms
CancellationTokenSource tokenSource = new CancellationTokenSource();
tokenSource.CancelAfter(rand.Next(100, 1000));
int currentPosition = 0;
byte[] buffer = new byte[MaximumReadSize];
do
{
try
{
// 20%: random read size
int bytesToRead = (rand.NextDouble() < 0.2 ? rand.Next(16, MaximumReadSize) : NormalReadSize);
int bytesRead;
if (rand.NextDouble() < 0.1)
{
// 10%: Sync read
bytesRead = stream.Read(buffer, 0, bytesToRead);
}
else
{
// 90%: Async read
bytesRead = await ReadAsync(stream, buffer, 0, bytesToRead, tokenSource.Token);
}
// 10%: Verify data (burns a lot of CPU time)
if (rand.NextDouble() < 0.1)
{
// Validate data read
Assert.True(bytesRead + currentPosition <= readableFileContents.Length, "Too many bytes read");
Assert.Equal(readableFileContents.Skip(currentPosition).Take(bytesRead), buffer.Take(bytesRead));
}
// Advance position and reset if we are at the end
currentPosition += bytesRead;
if (currentPosition >= readableFileContents.Length)
{
currentPosition = 0;
stream.Seek(0, SeekOrigin.Begin);
}
}
catch (TaskCanceledException)
{
// Once the token has expired, generate a new one
Assert.True(tokenSource.Token.IsCancellationRequested, "Received cancellation exception before token expired");
tokenSource = new CancellationTokenSource();
tokenSource.CancelAfter(rand.Next(100, 1000));
}
} while (DateTime.UtcNow - testStartTime <= testRunTime);
}
}
}
public class FileStream_ReadAsync_AsyncReads : FileStream_AsyncReads
{
protected override Task<int> ReadAsync(FileStream stream, byte[] buffer, int offset, int count, CancellationToken cancellationToken) =>
stream.ReadAsync(buffer, offset, count, cancellationToken);
[Fact]
public void CancelledTokenFastPath()
{
var cts = new CancellationTokenSource();
cts.Cancel();
CancellationToken cancelledToken = cts.Token;
using (FileStream fs = new FileStream(GetTestFilePath(), FileMode.Create))
{
FSAssert.IsCancelled(ReadAsync(fs, new byte[1], 0, 1, cancelledToken), cancelledToken);
}
using (FileStream fs = new FileStream(GetTestFilePath(), FileMode.Create, FileAccess.Write))
{
// before write only check
FSAssert.IsCancelled(ReadAsync(fs, new byte[1], 0, 1, cancelledToken), cancelledToken);
fs.Dispose();
// before disposed check
FSAssert.IsCancelled(ReadAsync(fs, new byte[1], 0, 1, cancelledToken), cancelledToken);
// out of bounds checking happens first
Assert.Throws<ArgumentException>(null, () =>
FSAssert.CompletesSynchronously(ReadAsync(fs, new byte[2], 1, 2, cancelledToken)));
// count is checked prior
AssertExtensions.Throws<ArgumentOutOfRangeException>(CountParamName, () =>
FSAssert.CompletesSynchronously(ReadAsync(fs, new byte[1], 0, -1, cancelledToken)));
// offset is checked prior
AssertExtensions.Throws<ArgumentOutOfRangeException>(OffsetParamName, () =>
FSAssert.CompletesSynchronously(ReadAsync(fs, new byte[1], -1, -1, cancelledToken)));
// buffer is checked first
AssertExtensions.Throws<ArgumentNullException>(BufferParamName, () =>
FSAssert.CompletesSynchronously(ReadAsync(fs, null, -1, -1, cancelledToken)));
}
}
}
public class FileStream_BeginEndRead_AsyncReads : FileStream_AsyncReads
{
protected override Task<int> ReadAsync(FileStream stream, byte[] buffer, int offset, int count, CancellationToken cancellationToken) =>
Task.Factory.FromAsync(
(callback, state) => stream.BeginRead(buffer, offset, count, callback, state),
iar => stream.EndRead(iar),
null);
protected override string BufferParamName => "array";
protected override string CountParamName => "numBytes";
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Net.Sockets;
using System.Text;
namespace System.Net
{
internal enum FtpLoginState : byte
{
NotLoggedIn,
LoggedIn,
LoggedInButNeedsRelogin,
ReloginFailed
};
/// <summary>
/// <para>
/// The FtpControlStream class implements a basic FTP connection,
/// This means basic command sending and parsing.
/// </para>
/// </summary>
internal class FtpControlStream : CommandStream
{
private Socket _dataSocket;
private IPEndPoint _passiveEndPoint;
private TlsStream _tlsStream;
private StringBuilder _bannerMessage;
private StringBuilder _welcomeMessage;
private StringBuilder _exitMessage;
private WeakReference _credentials;
private string _currentTypeSetting = string.Empty;
private long _contentLength = -1;
private DateTime _lastModified;
private bool _dataHandshakeStarted = false;
private string _loginDirectory = null;
private string _establishedServerDirectory = null;
private string _requestedServerDirectory = null;
private Uri _responseUri;
private FtpLoginState _loginState = FtpLoginState.NotLoggedIn;
internal FtpStatusCode StatusCode;
internal string StatusLine;
internal NetworkCredential Credentials
{
get
{
if (_credentials != null && _credentials.IsAlive)
{
return (NetworkCredential)_credentials.Target;
}
else
{
return null;
}
}
set
{
if (_credentials == null)
{
_credentials = new WeakReference(null);
}
_credentials.Target = value;
}
}
private static readonly AsyncCallback s_acceptCallbackDelegate = new AsyncCallback(AcceptCallback);
private static readonly AsyncCallback s_connectCallbackDelegate = new AsyncCallback(ConnectCallback);
private static readonly AsyncCallback s_SSLHandshakeCallback = new AsyncCallback(SSLHandshakeCallback);
internal FtpControlStream(TcpClient client)
: base(client)
{
}
/// <summary>
/// <para>Closes the connecting socket to generate an error.</para>
/// </summary>
internal void AbortConnect()
{
Socket socket = _dataSocket;
if (socket != null)
{
try
{
socket.Close();
}
catch (ObjectDisposedException)
{
}
}
}
/// <summary>
/// Provides a wrapper for the async accept operations.
/// </summary>
private static void AcceptCallback(IAsyncResult asyncResult)
{
FtpControlStream connection = (FtpControlStream)asyncResult.AsyncState;
Socket listenSocket = connection._dataSocket;
try
{
connection._dataSocket = listenSocket.EndAccept(asyncResult);
if (!connection.ServerAddress.Equals(((IPEndPoint)connection._dataSocket.RemoteEndPoint).Address))
{
connection._dataSocket.Close();
throw new WebException(SR.net_ftp_active_address_different, WebExceptionStatus.ProtocolError);
}
connection.ContinueCommandPipeline();
}
catch (Exception e)
{
connection.CloseSocket();
connection.InvokeRequestCallback(e);
}
finally
{
listenSocket.Close();
}
}
/// <summary>
/// <para>Provides a wrapper for the async accept operations</para>
/// </summary>
private static void ConnectCallback(IAsyncResult asyncResult)
{
FtpControlStream connection = (FtpControlStream)asyncResult.AsyncState;
try
{
connection._dataSocket.EndConnect(asyncResult);
connection.ContinueCommandPipeline();
}
catch (Exception e)
{
connection.CloseSocket();
connection.InvokeRequestCallback(e);
}
}
private static void SSLHandshakeCallback(IAsyncResult asyncResult)
{
FtpControlStream connection = (FtpControlStream)asyncResult.AsyncState;
try
{
connection._tlsStream.EndAuthenticateAsClient(asyncResult);
connection.ContinueCommandPipeline();
}
catch (Exception e)
{
connection.CloseSocket();
connection.InvokeRequestCallback(e);
}
}
// Creates a FtpDataStream object, constructs a TLS stream if needed.
// In case SSL and ASYNC we delay sigaling the user stream until the handshake is done.
private PipelineInstruction QueueOrCreateFtpDataStream(ref Stream stream)
{
if (_dataSocket == null)
throw new InternalException();
//
// Re-entered pipeline with completed read on the TlsStream
//
if (_tlsStream != null)
{
stream = new FtpDataStream(_tlsStream, (FtpWebRequest)_request, IsFtpDataStreamWriteable());
_tlsStream = null;
return PipelineInstruction.GiveStream;
}
NetworkStream networkStream = new NetworkStream(_dataSocket, true);
if (UsingSecureStream)
{
FtpWebRequest request = (FtpWebRequest)_request;
TlsStream tlsStream = new TlsStream(networkStream, _dataSocket, request.RequestUri.Host, request.ClientCertificates);
networkStream = tlsStream;
if (_isAsync)
{
_tlsStream = tlsStream;
tlsStream.BeginAuthenticateAsClient(s_SSLHandshakeCallback, this);
return PipelineInstruction.Pause;
}
else
{
tlsStream.AuthenticateAsClient();
}
}
stream = new FtpDataStream(networkStream, (FtpWebRequest)_request, IsFtpDataStreamWriteable());
return PipelineInstruction.GiveStream;
}
protected override void ClearState()
{
_contentLength = -1;
_lastModified = DateTime.MinValue;
_responseUri = null;
_dataHandshakeStarted = false;
StatusCode = FtpStatusCode.Undefined;
StatusLine = null;
_dataSocket = null;
_passiveEndPoint = null;
_tlsStream = null;
base.ClearState();
}
// This is called by underlying base class code, each time a new response is received from the wire or a protocol stage is resumed.
// This function controls the setting up of a data socket/connection, and of saving off the server responses.
protected override PipelineInstruction PipelineCallback(PipelineEntry entry, ResponseDescription response, bool timeout, ref Stream stream)
{
if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"Command:{entry?.Command} Description:{response?.StatusDescription}");
// null response is not expected
if (response == null)
return PipelineInstruction.Abort;
FtpStatusCode status = (FtpStatusCode)response.Status;
//
// Update global "current status" for FtpWebRequest
//
if (status != FtpStatusCode.ClosingControl)
{
// A 221 status won't be reflected on the user FTP response
// Anything else will (by design?)
StatusCode = status;
StatusLine = response.StatusDescription;
}
// If the status code is outside the range defined in RFC (1xx to 5xx) throw
if (response.InvalidStatusCode)
throw new WebException(SR.net_InvalidStatusCode, WebExceptionStatus.ProtocolError);
// Update the banner message if any, this is a little hack because the "entry" param is null
if (_index == -1)
{
if (status == FtpStatusCode.SendUserCommand)
{
_bannerMessage = new StringBuilder();
_bannerMessage.Append(StatusLine);
return PipelineInstruction.Advance;
}
else if (status == FtpStatusCode.ServiceTemporarilyNotAvailable)
{
return PipelineInstruction.Reread;
}
else
throw GenerateException(status, response.StatusDescription, null);
}
//
// Check for the result of our attempt to use UTF8
//
if (entry.Command == "OPTS utf8 on\r\n")
{
if (response.PositiveCompletion)
{
Encoding = Encoding.UTF8;
}
else
{
Encoding = Encoding.Default;
}
return PipelineInstruction.Advance;
}
// If we are already logged in and the server returns 530 then
// the server does not support re-issuing a USER command,
// tear down the connection and start all over again
if (entry.Command.IndexOf("USER", StringComparison.Ordinal) != -1)
{
// The server may not require a password for this user, so bypass the password command
if (status == FtpStatusCode.LoggedInProceed)
{
_loginState = FtpLoginState.LoggedIn;
_index++;
}
}
//
// Throw on an error with possible recovery option
//
if (response.TransientFailure || response.PermanentFailure)
{
if (status == FtpStatusCode.ServiceNotAvailable)
{
MarkAsRecoverableFailure();
}
throw GenerateException(status, response.StatusDescription, null);
}
if (_loginState != FtpLoginState.LoggedIn
&& entry.Command.IndexOf("PASS", StringComparison.Ordinal) != -1)
{
// Note the fact that we logged in
if (status == FtpStatusCode.NeedLoginAccount || status == FtpStatusCode.LoggedInProceed)
_loginState = FtpLoginState.LoggedIn;
else
throw GenerateException(status, response.StatusDescription, null);
}
//
// Parse special cases
//
if (entry.HasFlag(PipelineEntryFlags.CreateDataConnection) && (response.PositiveCompletion || response.PositiveIntermediate))
{
bool isSocketReady;
PipelineInstruction result = QueueOrCreateDataConection(entry, response, timeout, ref stream, out isSocketReady);
if (!isSocketReady)
return result;
// otherwise we have a stream to create
}
//
// This is part of the above case and it's all about giving data stream back
//
if (status == FtpStatusCode.OpeningData || status == FtpStatusCode.DataAlreadyOpen)
{
if (_dataSocket == null)
{
return PipelineInstruction.Abort;
}
if (!entry.HasFlag(PipelineEntryFlags.GiveDataStream))
{
_abortReason = SR.Format(SR.net_ftp_invalid_status_response, status, entry.Command);
return PipelineInstruction.Abort;
}
// Parse out the Content length, if we can
TryUpdateContentLength(response.StatusDescription);
// Parse out the file name, when it is returned and use it for our ResponseUri
FtpWebRequest request = (FtpWebRequest)_request;
if (request.MethodInfo.ShouldParseForResponseUri)
{
TryUpdateResponseUri(response.StatusDescription, request);
}
return QueueOrCreateFtpDataStream(ref stream);
}
//
// Parse responses by status code exclusivelly
//
// Update welcome message
if (status == FtpStatusCode.LoggedInProceed)
{
_welcomeMessage.Append(StatusLine);
}
// OR set the user response ExitMessage
else if (status == FtpStatusCode.ClosingControl)
{
_exitMessage.Append(response.StatusDescription);
// And close the control stream socket on "QUIT"
CloseSocket();
}
// OR set us up for SSL/TLS, after this we'll be writing securely
else if (status == FtpStatusCode.ServerWantsSecureSession)
{
// If NetworkStream is a TlsStream, then this must be in the async callback
// from completing the SSL handshake.
// So just let the pipeline continue.
if (!(NetworkStream is TlsStream))
{
FtpWebRequest request = (FtpWebRequest)_request;
TlsStream tlsStream = new TlsStream(NetworkStream, Socket, request.RequestUri.Host, request.ClientCertificates);
if (_isAsync)
{
tlsStream.BeginAuthenticateAsClient(ar =>
{
try
{
tlsStream.EndAuthenticateAsClient(ar);
NetworkStream = tlsStream;
this.ContinueCommandPipeline();
}
catch (Exception e)
{
this.CloseSocket();
this.InvokeRequestCallback(e);
}
}, null);
return PipelineInstruction.Pause;
}
else
{
tlsStream.AuthenticateAsClient();
NetworkStream = tlsStream;
}
}
}
// OR parse out the file size or file time, usually a result of sending SIZE/MDTM commands
else if (status == FtpStatusCode.FileStatus)
{
FtpWebRequest request = (FtpWebRequest)_request;
if (entry.Command.StartsWith("SIZE ", StringComparison.Ordinal))
{
_contentLength = GetContentLengthFrom213Response(response.StatusDescription);
}
else if (entry.Command.StartsWith("MDTM ", StringComparison.Ordinal))
{
_lastModified = GetLastModifiedFrom213Response(response.StatusDescription);
}
}
// OR parse out our login directory
else if (status == FtpStatusCode.PathnameCreated)
{
if (entry.Command == "PWD\r\n" && !entry.HasFlag(PipelineEntryFlags.UserCommand))
{
_loginDirectory = GetLoginDirectory(response.StatusDescription);
}
}
// Asserting we have some positive response
else
{
// We only use CWD to reset ourselves back to the login directory.
if (entry.Command.IndexOf("CWD", StringComparison.Ordinal) != -1)
{
_establishedServerDirectory = _requestedServerDirectory;
}
}
// Intermediate responses require rereading
if (response.PositiveIntermediate || (!UsingSecureStream && entry.Command == "AUTH TLS\r\n"))
{
return PipelineInstruction.Reread;
}
return PipelineInstruction.Advance;
}
/// <summary>
/// <para>Creates an array of commands, that will be sent to the server</para>
/// </summary>
protected override PipelineEntry[] BuildCommandsList(WebRequest req)
{
bool resetLoggedInState = false;
FtpWebRequest request = (FtpWebRequest)req;
if (NetEventSource.IsEnabled) NetEventSource.Info(this);
_responseUri = request.RequestUri;
ArrayList commandList = new ArrayList();
if (request.EnableSsl && !UsingSecureStream)
{
commandList.Add(new PipelineEntry(FormatFtpCommand("AUTH", "TLS")));
// According to RFC we need to re-authorize with USER/PASS after we re-authenticate.
resetLoggedInState = true;
}
if (resetLoggedInState)
{
_loginDirectory = null;
_establishedServerDirectory = null;
_requestedServerDirectory = null;
_currentTypeSetting = string.Empty;
if (_loginState == FtpLoginState.LoggedIn)
_loginState = FtpLoginState.LoggedInButNeedsRelogin;
}
if (_loginState != FtpLoginState.LoggedIn)
{
Credentials = request.Credentials.GetCredential(request.RequestUri, "basic");
_welcomeMessage = new StringBuilder();
_exitMessage = new StringBuilder();
string domainUserName = string.Empty;
string password = string.Empty;
if (Credentials != null)
{
domainUserName = Credentials.UserName;
string domain = Credentials.Domain;
if (!string.IsNullOrEmpty(domain))
{
domainUserName = domain + "\\" + domainUserName;
}
password = Credentials.Password;
}
if (domainUserName.Length == 0 && password.Length == 0)
{
domainUserName = "anonymous";
password = "anonymous@";
}
commandList.Add(new PipelineEntry(FormatFtpCommand("USER", domainUserName)));
commandList.Add(new PipelineEntry(FormatFtpCommand("PASS", password), PipelineEntryFlags.DontLogParameter));
// If SSL, always configure data channel encryption after authentication to maximum RFC compatibility. The RFC allows for
// PBSZ/PROT commands to come either before or after the USER/PASS, but some servers require USER/PASS immediately after
// the AUTH TLS command.
if (request.EnableSsl && !UsingSecureStream)
{
commandList.Add(new PipelineEntry(FormatFtpCommand("PBSZ", "0")));
commandList.Add(new PipelineEntry(FormatFtpCommand("PROT", "P")));
}
commandList.Add(new PipelineEntry(FormatFtpCommand("OPTS", "utf8 on")));
commandList.Add(new PipelineEntry(FormatFtpCommand("PWD", null)));
}
GetPathOption getPathOption = GetPathOption.Normal;
if (request.MethodInfo.HasFlag(FtpMethodFlags.DoesNotTakeParameter))
{
getPathOption = GetPathOption.AssumeNoFilename;
}
else if (request.MethodInfo.HasFlag(FtpMethodFlags.ParameterIsDirectory))
{
getPathOption = GetPathOption.AssumeFilename;
}
string requestPath;
string requestDirectory;
string requestFilename;
GetPathInfo(getPathOption, request.RequestUri, out requestPath, out requestDirectory, out requestFilename);
if (requestFilename.Length == 0 && request.MethodInfo.HasFlag(FtpMethodFlags.TakesParameter))
throw new WebException(SR.net_ftp_invalid_uri);
// We optimize for having the current working directory staying at the login directory. This ensure that
// our relative paths work right and reduces unnecessary CWD commands.
// Usually, we don't change the working directory except for some FTP commands. If necessary,
// we need to reset our working directory back to the login directory.
if (_establishedServerDirectory != null && _loginDirectory != null && _establishedServerDirectory != _loginDirectory)
{
commandList.Add(new PipelineEntry(FormatFtpCommand("CWD", _loginDirectory), PipelineEntryFlags.UserCommand));
_requestedServerDirectory = _loginDirectory;
}
// For most commands, we don't need to navigate to the directory since we pass in the full
// path as part of the FTP protocol command. However, some commands require it.
if (request.MethodInfo.HasFlag(FtpMethodFlags.MustChangeWorkingDirectoryToPath) && requestDirectory.Length > 0)
{
commandList.Add(new PipelineEntry(FormatFtpCommand("CWD", requestDirectory), PipelineEntryFlags.UserCommand));
_requestedServerDirectory = requestDirectory;
}
if (!request.MethodInfo.IsCommandOnly)
{
string requestedTypeSetting = request.UseBinary ? "I" : "A";
if (_currentTypeSetting != requestedTypeSetting)
{
commandList.Add(new PipelineEntry(FormatFtpCommand("TYPE", requestedTypeSetting)));
_currentTypeSetting = requestedTypeSetting;
}
if (request.UsePassive)
{
string passiveCommand = (ServerAddress.AddressFamily == AddressFamily.InterNetwork || ServerAddress.IsIPv4MappedToIPv6) ? "PASV" : "EPSV";
commandList.Add(new PipelineEntry(FormatFtpCommand(passiveCommand, null), PipelineEntryFlags.CreateDataConnection));
}
else
{
string portCommand = (ServerAddress.AddressFamily == AddressFamily.InterNetwork || ServerAddress.IsIPv4MappedToIPv6) ? "PORT" : "EPRT";
CreateFtpListenerSocket(request);
commandList.Add(new PipelineEntry(FormatFtpCommand(portCommand, GetPortCommandLine(request))));
}
if (request.ContentOffset > 0)
{
// REST command must always be the last sent before the main file command is sent.
commandList.Add(new PipelineEntry(FormatFtpCommand("REST", request.ContentOffset.ToString(CultureInfo.InvariantCulture))));
}
}
PipelineEntryFlags flags = PipelineEntryFlags.UserCommand;
if (!request.MethodInfo.IsCommandOnly)
{
flags |= PipelineEntryFlags.GiveDataStream;
if (!request.UsePassive)
flags |= PipelineEntryFlags.CreateDataConnection;
}
if (request.MethodInfo.Operation == FtpOperation.Rename)
{
string baseDir = (requestDirectory == string.Empty)
? string.Empty : requestDirectory + "/";
commandList.Add(new PipelineEntry(FormatFtpCommand("RNFR", baseDir + requestFilename), flags));
string renameTo;
if (!string.IsNullOrEmpty(request.RenameTo)
&& request.RenameTo.StartsWith("/", StringComparison.OrdinalIgnoreCase))
{
renameTo = request.RenameTo; // Absolute path
}
else
{
renameTo = baseDir + request.RenameTo; // Relative path
}
commandList.Add(new PipelineEntry(FormatFtpCommand("RNTO", renameTo), flags));
}
else if (request.MethodInfo.HasFlag(FtpMethodFlags.DoesNotTakeParameter))
{
commandList.Add(new PipelineEntry(FormatFtpCommand(request.Method, string.Empty), flags));
}
else if (request.MethodInfo.HasFlag(FtpMethodFlags.MustChangeWorkingDirectoryToPath))
{
commandList.Add(new PipelineEntry(FormatFtpCommand(request.Method, requestFilename), flags));
}
else
{
commandList.Add(new PipelineEntry(FormatFtpCommand(request.Method, requestPath), flags));
}
commandList.Add(new PipelineEntry(FormatFtpCommand("QUIT", null)));
return (PipelineEntry[])commandList.ToArray(typeof(PipelineEntry));
}
private PipelineInstruction QueueOrCreateDataConection(PipelineEntry entry, ResponseDescription response, bool timeout, ref Stream stream, out bool isSocketReady)
{
isSocketReady = false;
if (_dataHandshakeStarted)
{
isSocketReady = true;
return PipelineInstruction.Pause; //if we already started then this is re-entering into the callback where we proceed with the stream
}
_dataHandshakeStarted = true;
// Handle passive responses by parsing the port and later doing a Connect(...)
bool isPassive = false;
int port = -1;
if (entry.Command == "PASV\r\n" || entry.Command == "EPSV\r\n")
{
if (!response.PositiveCompletion)
{
_abortReason = SR.Format(SR.net_ftp_server_failed_passive, response.Status);
return PipelineInstruction.Abort;
}
if (entry.Command == "PASV\r\n")
{
port = GetPortV4(response.StatusDescription);
}
else
{
port = GetPortV6(response.StatusDescription);
}
isPassive = true;
}
if (isPassive)
{
if (port == -1)
{
NetEventSource.Fail(this, "'port' not set.");
}
try
{
_dataSocket = CreateFtpDataSocket((FtpWebRequest)_request, Socket);
}
catch (ObjectDisposedException)
{
throw ExceptionHelper.RequestAbortedException;
}
IPEndPoint localEndPoint = new IPEndPoint(((IPEndPoint)Socket.LocalEndPoint).Address, 0);
_dataSocket.Bind(localEndPoint);
_passiveEndPoint = new IPEndPoint(ServerAddress, port);
}
PipelineInstruction result;
if (_passiveEndPoint != null)
{
IPEndPoint passiveEndPoint = _passiveEndPoint;
_passiveEndPoint = null;
if (NetEventSource.IsEnabled) NetEventSource.Info(this, "starting Connect()");
if (_isAsync)
{
_dataSocket.BeginConnect(passiveEndPoint, s_connectCallbackDelegate, this);
result = PipelineInstruction.Pause;
}
else
{
_dataSocket.Connect(passiveEndPoint);
result = PipelineInstruction.Advance; // for passive mode we end up going to the next command
}
}
else
{
if (NetEventSource.IsEnabled) NetEventSource.Info(this, "starting Accept()");
if (_isAsync)
{
_dataSocket.BeginAccept(s_acceptCallbackDelegate, this);
result = PipelineInstruction.Pause;
}
else
{
Socket listenSocket = _dataSocket;
try
{
_dataSocket = _dataSocket.Accept();
if (!ServerAddress.Equals(((IPEndPoint)_dataSocket.RemoteEndPoint).Address))
{
_dataSocket.Close();
throw new WebException(SR.net_ftp_active_address_different, WebExceptionStatus.ProtocolError);
}
isSocketReady = true; // for active mode we end up creating a stream before advancing the pipeline
result = PipelineInstruction.Pause;
}
finally
{
listenSocket.Close();
}
}
}
return result;
}
private enum GetPathOption
{
Normal,
AssumeFilename,
AssumeNoFilename
}
/// <summary>
/// <para>Gets the path component of the Uri</para>
/// </summary>
private static void GetPathInfo(GetPathOption pathOption,
Uri uri,
out string path,
out string directory,
out string filename)
{
path = uri.GetComponents(UriComponents.Path, UriFormat.Unescaped);
int index = path.LastIndexOf('/');
if (pathOption == GetPathOption.AssumeFilename &&
index != -1 && index == path.Length - 1)
{
// Remove last '/' and continue normal processing
path = path.Substring(0, path.Length - 1);
index = path.LastIndexOf('/');
}
// split path into directory and filename
if (pathOption == GetPathOption.AssumeNoFilename)
{
directory = path;
filename = string.Empty;
}
else
{
directory = path.Substring(0, index + 1);
filename = path.Substring(index + 1, path.Length - (index + 1));
}
// strip off trailing '/' on directory if present
if (directory.Length > 1 && directory[directory.Length - 1] == '/')
directory = directory.Substring(0, directory.Length - 1);
}
//
/// <summary>
/// <para>Formats an IP address (contained in a UInt32) to a FTP style command string</para>
/// </summary>
private string FormatAddress(IPAddress address, int Port)
{
byte[] localAddressInBytes = address.GetAddressBytes();
// produces a string in FTP IPAddress/Port encoding (a1, a2, a3, a4, p1, p2), for sending as a parameter
// to the port command.
StringBuilder sb = new StringBuilder(32);
for (int i = address.IsIPv4MappedToIPv6 ? 12 : 0; i < localAddressInBytes.Length; i++)
{
sb.Append(localAddressInBytes[i]);
sb.Append(',');
}
sb.Append(Port / 256);
sb.Append(',');
sb.Append(Port % 256);
return sb.ToString();
}
/// <summary>
/// <para>Formats an IP address (v6) to a FTP style command string
/// Looks something in this form: |2|1080::8:800:200C:417A|5282| </para>
/// |2|4567::0123:5678:0123:5678|0123|
/// </summary>
private string FormatAddressV6(IPAddress address, int port)
{
StringBuilder sb = new StringBuilder(43); // based on max size of IPv6 address + port + seperators
string addressString = address.ToString();
sb.Append("|2|");
sb.Append(addressString);
sb.Append('|');
sb.Append(port.ToString(NumberFormatInfo.InvariantInfo));
sb.Append('|');
return sb.ToString();
}
internal long ContentLength
{
get
{
return _contentLength;
}
}
internal DateTime LastModified
{
get
{
return _lastModified;
}
}
internal Uri ResponseUri
{
get
{
return _responseUri;
}
}
/// <summary>
/// <para>Returns the server message sent before user credentials are sent</para>
/// </summary>
internal string BannerMessage
{
get
{
return (_bannerMessage != null) ? _bannerMessage.ToString() : null;
}
}
/// <summary>
/// <para>Returns the server message sent after user credentials are sent</para>
/// </summary>
internal string WelcomeMessage
{
get
{
return (_welcomeMessage != null) ? _welcomeMessage.ToString() : null;
}
}
/// <summary>
/// <para>Returns the exit sent message on shutdown</para>
/// </summary>
internal string ExitMessage
{
get
{
return (_exitMessage != null) ? _exitMessage.ToString() : null;
}
}
/// <summary>
/// <para>Parses a response string for content length</para>
/// </summary>
private long GetContentLengthFrom213Response(string responseString)
{
string[] parsedList = responseString.Split(new char[] { ' ' });
if (parsedList.Length < 2)
throw new FormatException(SR.Format(SR.net_ftp_response_invalid_format, responseString));
return Convert.ToInt64(parsedList[1], NumberFormatInfo.InvariantInfo);
}
/// <summary>
/// <para>Parses a response string for last modified time</para>
/// </summary>
private DateTime GetLastModifiedFrom213Response(string str)
{
DateTime dateTime = _lastModified;
string[] parsedList = str.Split(new char[] { ' ', '.' });
if (parsedList.Length < 2)
{
return dateTime;
}
string dateTimeLine = parsedList[1];
if (dateTimeLine.Length < 14)
{
return dateTime;
}
int year = Convert.ToInt32(dateTimeLine.Substring(0, 4), NumberFormatInfo.InvariantInfo);
int month = Convert.ToInt16(dateTimeLine.Substring(4, 2), NumberFormatInfo.InvariantInfo);
int day = Convert.ToInt16(dateTimeLine.Substring(6, 2), NumberFormatInfo.InvariantInfo);
int hour = Convert.ToInt16(dateTimeLine.Substring(8, 2), NumberFormatInfo.InvariantInfo);
int minute = Convert.ToInt16(dateTimeLine.Substring(10, 2), NumberFormatInfo.InvariantInfo);
int second = Convert.ToInt16(dateTimeLine.Substring(12, 2), NumberFormatInfo.InvariantInfo);
int millisecond = 0;
if (parsedList.Length > 2)
{
millisecond = Convert.ToInt16(parsedList[2], NumberFormatInfo.InvariantInfo);
}
try
{
dateTime = new DateTime(year, month, day, hour, minute, second, millisecond);
dateTime = dateTime.ToLocalTime(); // must be handled in local time
}
catch (ArgumentOutOfRangeException)
{
}
catch (ArgumentException)
{
}
return dateTime;
}
/// <summary>
/// <para>Attempts to find the response Uri
/// Typical string looks like this, need to get trailing filename
/// "150 Opening BINARY mode data connection for FTP46.tmp."</para>
/// </summary>
private void TryUpdateResponseUri(string str, FtpWebRequest request)
{
Uri baseUri = request.RequestUri;
//
// Not sure what we are doing here but I guess the logic is IIS centric
//
int start = str.IndexOf("for ", StringComparison.Ordinal);
if (start == -1)
return;
start += 4;
int end = str.LastIndexOf('(');
if (end == -1)
end = str.Length;
if (end <= start)
return;
string filename = str.Substring(start, end - start);
filename = filename.TrimEnd(new char[] { ' ', '.', '\r', '\n' });
// Do minimal escaping that we need to get a valid Uri
// when combined with the baseUri
string escapedFilename;
escapedFilename = filename.Replace("%", "%25");
escapedFilename = escapedFilename.Replace("#", "%23");
// help us out if the user forgot to add a slash to the directory name
string orginalPath = baseUri.AbsolutePath;
if (orginalPath.Length > 0 && orginalPath[orginalPath.Length - 1] != '/')
{
UriBuilder uriBuilder = new UriBuilder(baseUri);
uriBuilder.Path = orginalPath + "/";
baseUri = uriBuilder.Uri;
}
Uri newUri;
if (!Uri.TryCreate(baseUri, escapedFilename, out newUri))
{
throw new FormatException(SR.Format(SR.net_ftp_invalid_response_filename, filename));
}
else
{
if (!baseUri.IsBaseOf(newUri) ||
baseUri.Segments.Length != newUri.Segments.Length - 1)
{
throw new FormatException(SR.Format(SR.net_ftp_invalid_response_filename, filename));
}
else
{
_responseUri = newUri;
}
}
}
/// <summary>
/// <para>Parses a response string for content length</para>
/// </summary>
private void TryUpdateContentLength(string str)
{
int pos1 = str.LastIndexOf('(');
if (pos1 != -1)
{
int pos2 = str.IndexOf(" bytes).", StringComparison.Ordinal);
if (pos2 != -1 && pos2 > pos1)
{
pos1++;
long result;
if (long.TryParse(str.Substring(pos1, pos2 - pos1),
NumberStyles.AllowLeadingWhite | NumberStyles.AllowTrailingWhite,
NumberFormatInfo.InvariantInfo, out result))
{
_contentLength = result;
}
}
}
}
/// <summary>
/// <para>Parses a response string for our login dir in " "</para>
/// </summary>
private string GetLoginDirectory(string str)
{
int firstQuote = str.IndexOf('"');
int lastQuote = str.LastIndexOf('"');
if (firstQuote != -1 && lastQuote != -1 && firstQuote != lastQuote)
{
return str.Substring(firstQuote + 1, lastQuote - firstQuote - 1);
}
else
{
return string.Empty;
}
}
/// <summary>
/// <para>Parses a response string for a port number</para>
/// </summary>
private int GetPortV4(string responseString)
{
string[] parsedList = responseString.Split(new char[] { ' ', '(', ',', ')' });
// We need at least the status code and the port
if (parsedList.Length <= 7)
{
throw new FormatException(SR.Format(SR.net_ftp_response_invalid_format, responseString));
}
int index = parsedList.Length - 1;
// skip the last non-number token (e.g. terminating '.')
if (!char.IsNumber(parsedList[index], 0))
index--;
int port = Convert.ToByte(parsedList[index--], NumberFormatInfo.InvariantInfo);
port = port |
(Convert.ToByte(parsedList[index--], NumberFormatInfo.InvariantInfo) << 8);
return port;
}
/// <summary>
/// <para>Parses a response string for a port number</para>
/// </summary>
private int GetPortV6(string responseString)
{
int pos1 = responseString.LastIndexOf('(');
int pos2 = responseString.LastIndexOf(')');
if (pos1 == -1 || pos2 <= pos1)
throw new FormatException(SR.Format(SR.net_ftp_response_invalid_format, responseString));
// addressInfo will contain a string of format "|||<tcp-port>|"
string addressInfo = responseString.Substring(pos1 + 1, pos2 - pos1 - 1);
string[] parsedList = addressInfo.Split(new char[] { '|' });
if (parsedList.Length < 4)
throw new FormatException(SR.Format(SR.net_ftp_response_invalid_format, responseString));
return Convert.ToInt32(parsedList[3], NumberFormatInfo.InvariantInfo);
}
/// <summary>
/// <para>Creates the Listener socket</para>
/// </summary>
private void CreateFtpListenerSocket(FtpWebRequest request)
{
// Gets an IPEndPoint for the local host for the data socket to bind to.
IPEndPoint epListener = new IPEndPoint(((IPEndPoint)Socket.LocalEndPoint).Address, 0);
try
{
_dataSocket = CreateFtpDataSocket(request, Socket);
}
catch (ObjectDisposedException)
{
throw ExceptionHelper.RequestAbortedException;
}
// Binds the data socket to the local end point.
_dataSocket.Bind(epListener);
_dataSocket.Listen(1); // Put the dataSocket in Listen mode
}
/// <summary>
/// <para>Builds a command line to send to the server with proper port and IP address of client</para>
/// </summary>
private string GetPortCommandLine(FtpWebRequest request)
{
try
{
// retrieves the IP address of the local endpoint
IPEndPoint localEP = (IPEndPoint)_dataSocket.LocalEndPoint;
if (ServerAddress.AddressFamily == AddressFamily.InterNetwork || ServerAddress.IsIPv4MappedToIPv6)
{
return FormatAddress(localEP.Address, localEP.Port);
}
else if (ServerAddress.AddressFamily == AddressFamily.InterNetworkV6)
{
return FormatAddressV6(localEP.Address, localEP.Port);
}
else
{
throw new InternalException();
}
}
catch (Exception e)
{
throw GenerateException(SR.net_ftp_protocolerror, WebExceptionStatus.ProtocolError, e); // could not open data connection
}
}
/// <summary>
/// <para>Formats a simple FTP command + parameter in correct pre-wire format</para>
/// </summary>
private string FormatFtpCommand(string command, string parameter)
{
StringBuilder stringBuilder = new StringBuilder(command.Length + ((parameter != null) ? parameter.Length : 0) + 3 /*size of ' ' \r\n*/);
stringBuilder.Append(command);
if (!string.IsNullOrEmpty(parameter))
{
stringBuilder.Append(' ');
stringBuilder.Append(parameter);
}
stringBuilder.Append("\r\n");
return stringBuilder.ToString();
}
/// <summary>
/// <para>
/// This will handle either connecting to a port or listening for one
/// </para>
/// </summary>
protected Socket CreateFtpDataSocket(FtpWebRequest request, Socket templateSocket)
{
// Safe to be called under an Assert.
Socket socket = new Socket(templateSocket.AddressFamily, templateSocket.SocketType, templateSocket.ProtocolType);
if (templateSocket.AddressFamily == AddressFamily.InterNetworkV6 && templateSocket.DualMode)
{
socket.DualMode = true;
}
return socket;
}
protected override bool CheckValid(ResponseDescription response, ref int validThrough, ref int completeLength)
{
if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"CheckValid({response.StatusBuffer})");
// If the response is less than 4 bytes long, it is too short to tell, so return true, valid so far.
if (response.StatusBuffer.Length < 4)
{
return true;
}
string responseString = response.StatusBuffer.ToString();
// Otherwise, if there is no status code for this response yet, get one.
if (response.Status == ResponseDescription.NoStatus)
{
// If the response does not start with three digits, then it is not a valid response from an FTP server.
if (!(char.IsDigit(responseString[0]) && char.IsDigit(responseString[1]) && char.IsDigit(responseString[2]) && (responseString[3] == ' ' || responseString[3] == '-')))
{
return false;
}
else
{
response.StatusCodeString = responseString.Substring(0, 3);
response.Status = Convert.ToInt16(response.StatusCodeString, NumberFormatInfo.InvariantInfo);
}
// IF a hyphen follows the status code on the first line of the response, then we have a multiline response coming.
if (responseString[3] == '-')
{
response.Multiline = true;
}
}
// If a complete line of response has been received from the server, then see if the
// overall response is complete.
// If this was not a multiline response, then the response is complete at the end of the line.
// If this was a multiline response (indicated by three digits followed by a '-' in the first line),
// then we see if the last line received started with the same three digits followed by a space.
// If it did, then this is the sign of a complete multiline response.
// If the line contained three other digits followed by the response, then this is a violation of the
// FTP protocol for multiline responses.
// All other cases indicate that the response is not yet complete.
int index = 0;
while ((index = responseString.IndexOf("\r\n", validThrough, StringComparison.Ordinal)) != -1) // gets the end line.
{
int lineStart = validThrough;
validThrough = index + 2; // validThrough now marks the end of the line being examined.
if (!response.Multiline)
{
completeLength = validThrough;
return true;
}
if (responseString.Length > lineStart + 4)
{
// If the first three characters of the response line currently being examined
// match the status code, then if they are followed by a space, then we
// have reached the end of the reply.
if (responseString.Substring(lineStart, 3) == response.StatusCodeString)
{
if (responseString[lineStart + 3] == ' ')
{
completeLength = validThrough;
return true;
}
}
}
}
return true;
}
/// <summary>
/// <para>Determines whether the stream we return is Writeable or Readable</para>
/// </summary>
private TriState IsFtpDataStreamWriteable()
{
FtpWebRequest request = _request as FtpWebRequest;
if (request != null)
{
if (request.MethodInfo.IsUpload)
{
return TriState.True;
}
else if (request.MethodInfo.IsDownload)
{
return TriState.False;
}
}
return TriState.Unspecified;
}
} // class FtpControlStream
} // namespace System.Net
| |
//
// (C) Copyright 2003-2011 by Autodesk, Inc.
//
// Permission to use, copy, modify, and distribute this software in
// object code form for any purpose and without fee is hereby granted,
// provided that the above copyright notice appears in all copies and
// that both that copyright notice and the limited warranty and
// restricted rights notice below appear in all supporting
// documentation.
//
// AUTODESK PROVIDES THIS PROGRAM "AS IS" AND WITH ALL FAULTS.
// AUTODESK SPECIFICALLY DISCLAIMS ANY IMPLIED WARRANTY OF
// MERCHANTABILITY OR FITNESS FOR A PARTICULAR USE. AUTODESK, INC.
// DOES NOT WARRANT THAT THE OPERATION OF THE PROGRAM WILL BE
// UNINTERRUPTED OR ERROR FREE.
//
// Use, duplication, or disclosure by the U.S. Government is subject to
// restrictions set forth in FAR 52.227-19 (Commercial Computer
// Software - Restricted Rights) and DFAR 252.227-7013(c)(1)(ii)
// (Rights in Technical Data and Computer Software), as applicable.
//
using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;
using System.Resources;
using System.Collections;
namespace Revit.SDK.Samples.GridCreation.CS
{
/// <summary>
/// Class to validate input data before creating grids
/// </summary>
public static class Validation
{
// Get the resource contains strings
static ResourceManager resManager = Properties.Resources.ResourceManager;
/// <summary>
/// Validate numbers in UI
/// </summary>
/// <param name="number1Ctrl">Control contains number information</param>
/// <param name="number2Ctrl">Control contains another number information</param>
/// <returns>Whether the numbers are validated</returns>
public static bool ValidateNumbers(Control number1Ctrl, Control number2Ctrl)
{
if (!ValidateNumber(number1Ctrl) || !ValidateNumber(number2Ctrl))
{
return false;
}
if (Convert.ToUInt32(number1Ctrl.Text) == 0 && Convert.ToUInt32(number2Ctrl.Text) == 0)
{
ShowWarningMessage(resManager.GetString("NumbersCannotBeBothZero"),
Properties.Resources.ResourceManager.GetString("FailureCaptionInvalidValue"));
number1Ctrl.Focus();
return false;
}
return true;
}
/// <summary>
/// Validate number value
/// </summary>
/// <param name="numberCtrl">Control contains number information</param>
/// <returns>Whether the number value is validated</returns>
public static bool ValidateNumber(Control numberCtrl)
{
if (!ValidateNotNull(numberCtrl, "Number"))
{
return false;
}
try
{
uint number = Convert.ToUInt32(numberCtrl.Text);
if (number > 200)
{
ShowWarningMessage(resManager.GetString("NumberBetween0And200"),
Properties.Resources.ResourceManager.GetString("FailureCaptionInvalidValue"));
numberCtrl.Focus();
return false;
}
}
catch(OverflowException)
{
ShowWarningMessage(resManager.GetString("NumberBetween0And200"),
Properties.Resources.ResourceManager.GetString("FailureCaptionInvalidValue"));
numberCtrl.Focus();
return false;
}
catch (Exception)
{
ShowWarningMessage(resManager.GetString("NumberFormatWrong"),
Properties.Resources.ResourceManager.GetString("FailureCaptionInvalidValue"));
numberCtrl.Focus();
return false;
}
return true;
}
/// <summary>
/// Validate length value
/// </summary>
/// <param name="lengthCtrl">Control contains length information</param>
/// <param name="typeName">Type of length</param>
/// <param name="canBeZero">Whether the length can be zero</param>
/// <returns>Whether the length value is validated</returns>
public static bool ValidateLength(Control lengthCtrl, String typeName, bool canBeZero)
{
if (!ValidateNotNull(lengthCtrl, typeName))
{
return false;
}
try
{
double length = Convert.ToDouble(lengthCtrl.Text);
if (length <= 0 && !canBeZero)
{
ShowWarningMessage(resManager.GetString(typeName + "CannotBeNegativeOrZero"),
Properties.Resources.ResourceManager.GetString("FailureCaptionInvalidValue"));
lengthCtrl.Focus();
return false;
}
else if (length < 0 && canBeZero)
{
ShowWarningMessage(resManager.GetString(typeName + "CannotBeNegative"),
Properties.Resources.ResourceManager.GetString("FailureCaptionInvalidValue"));
lengthCtrl.Focus();
return false;
}
}
catch (Exception)
{
ShowWarningMessage(resManager.GetString(typeName + "FormatWrong"),
Properties.Resources.ResourceManager.GetString("FailureCaptionInvalidValue"));
lengthCtrl.Focus();
return false;
}
return true;
}
/// <summary>
/// Validate coordinate value
/// </summary>
/// <param name="coordCtrl">Control contains coordinate information</param>
/// <returns>Whether the coordinate value is validated</returns>
public static bool ValidateCoord(Control coordCtrl)
{
if (!ValidateNotNull(coordCtrl, "Coordinate"))
{
return false;
}
try
{
Convert.ToDouble(coordCtrl.Text);
}
catch (Exception)
{
ShowWarningMessage(resManager.GetString("CoordinateFormatWrong"),
Properties.Resources.ResourceManager.GetString("FailureCaptionInvalidValue"));
coordCtrl.Focus();
return false;
}
return true;
}
/// <summary>
/// Validate start degree and end degree
/// </summary>
/// <param name="startDegree">Control contains start degree information</param>
/// <param name="endDegree">Control contains end degree information</param>
/// <returns>Whether the degree values are validated</returns>
public static bool ValidateDegrees(Control startDegree, Control endDegree)
{
if (!ValidateDegree(startDegree) || !ValidateDegree(endDegree))
{
return false;
}
if (Math.Abs(Convert.ToDouble(startDegree.Text) - Convert.ToDouble(endDegree.Text)) <= Double.Epsilon)
{
ShowWarningMessage(resManager.GetString("DegreesAreTooClose"),
Properties.Resources.ResourceManager.GetString("FailureCaptionInvalidValue"));
startDegree.Focus();
return false;
}
if (Convert.ToDouble(startDegree.Text) >= Convert.ToDouble(endDegree.Text))
{
ShowWarningMessage(resManager.GetString("StartDegreeShouldBeLessThanEndDegree"),
Properties.Resources.ResourceManager.GetString("FailureCaptionInvalidValue"));
startDegree.Focus();
return false;
}
return true;
}
/// <summary>
/// Validate degree value
/// </summary>
/// <param name="degreeCtrl">Control contains degree information</param>
/// <returns>Whether the degree value is validated</returns>
public static bool ValidateDegree(Control degreeCtrl)
{
if (!ValidateNotNull(degreeCtrl, "Degree"))
{
return false;
}
try
{
double startDegree = Convert.ToDouble(degreeCtrl.Text);
if (startDegree < 0 || startDegree > 360)
{
ShowWarningMessage(resManager.GetString("DegreeWithin0To360"),
Properties.Resources.ResourceManager.GetString("FailureCaptionInvalidValue"));
degreeCtrl.Focus();
return false;
}
}
catch (Exception)
{
ShowWarningMessage(resManager.GetString("DegreeFormatWrong"),
Properties.Resources.ResourceManager.GetString("FailureCaptionInvalidValue"));
degreeCtrl.Focus();
return false;
}
return true;
}
/// <summary>
/// Validate label
/// </summary>
/// <param name="labelCtrl">Control contains label information</param>
/// <param name="allLabels">List contains all labels in Revit document</param>
/// <returns>Whether the label value is validated</returns>
public static bool ValidateLabel(Control labelCtrl, ArrayList allLabels)
{
if (!ValidateNotNull(labelCtrl, "Label"))
{
return false;
}
String labelToBeValidated = labelCtrl.Text;
foreach (String label in allLabels)
{
if (label == labelToBeValidated)
{
ShowWarningMessage(resManager.GetString("LabelExisted"),
Properties.Resources.ResourceManager.GetString("FailureCaptionInvalidValue"));
labelCtrl.Focus();
return false;
}
}
return true;
}
/// <summary>
/// Assure value is not null
/// </summary>
/// <param name="control">Control contains information needs to be checked</param>
/// <param name="typeName">Type of information</param>
/// <returns>Whether the value is not null</returns>
public static bool ValidateNotNull(Control control, String typeName)
{
if (String.IsNullOrEmpty(control.Text.TrimStart(' ').TrimEnd(' ')))
{
ShowWarningMessage(resManager.GetString(typeName + "CannotBeNull"),
Properties.Resources.ResourceManager.GetString("FailureCaptionInvalidValue"));
control.Focus();
return false;
}
return true;
}
/// <summary>
/// Assure two labels are not same
/// </summary>
/// <param name="label1Ctrl">Control contains label information</param>
/// <param name="label2Ctrl">Control contains label information</param>
/// <returns>Whether the labels are same</returns>
public static bool ValidateLabels(Control label1Ctrl, Control label2Ctrl)
{
if (label1Ctrl.Text.TrimStart(' ').TrimEnd(' ') == label2Ctrl.Text.TrimStart(' ').TrimEnd(' '))
{
ShowWarningMessage(resManager.GetString("LabelsCannotBeSame"),
Properties.Resources.ResourceManager.GetString("FailureCaptionInvalidValue"));
label1Ctrl.Focus();
return false;
}
return true;
}
/// <summary>
/// Show a warning message box
/// </summary>
/// <param name="message">Message</param>
/// <param name="caption">title of message box</param>
public static void ShowWarningMessage(String message, String caption)
{
MessageBox.Show(message, caption, MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
}
}
| |
using ICSharpCode.SharpZipLib.Tests.TestSupport;
using ICSharpCode.SharpZipLib.Zip.Compression;
using ICSharpCode.SharpZipLib.Zip.Compression.Streams;
using NUnit.Framework;
using System;
using System.IO;
using System.Security;
using System.Text;
namespace ICSharpCode.SharpZipLib.Tests.Base
{
/// <summary>
/// This class contains test cases for Deflater/Inflater streams.
/// </summary>
[TestFixture]
public class InflaterDeflaterTestSuite
{
private void Inflate(MemoryStream ms, byte[] original, int level, bool zlib)
{
ms.Seek(0, SeekOrigin.Begin);
var inflater = new Inflater(!zlib);
var inStream = new InflaterInputStream(ms, inflater);
byte[] buf2 = new byte[original.Length];
int currentIndex = 0;
int count = buf2.Length;
try
{
while (true)
{
int numRead = inStream.Read(buf2, currentIndex, count);
if (numRead <= 0)
{
break;
}
currentIndex += numRead;
count -= numRead;
}
}
catch (Exception ex)
{
Console.WriteLine("Unexpected exception - '{0}'", ex.Message);
throw;
}
if (currentIndex != original.Length)
{
Console.WriteLine("Original {0}, new {1}", original.Length, currentIndex);
Assert.Fail("Lengths different");
}
for (int i = 0; i < original.Length; ++i)
{
if (buf2[i] != original[i])
{
string description = string.Format("Difference at {0} level {1} zlib {2} ", i, level, zlib);
if (original.Length < 2048)
{
var builder = new StringBuilder(description);
for (int d = 0; d < original.Length; ++d)
{
builder.AppendFormat("{0} ", original[d]);
}
Assert.Fail(builder.ToString());
}
else
{
Assert.Fail(description);
}
}
}
}
private MemoryStream Deflate(byte[] data, int level, bool zlib)
{
var memoryStream = new MemoryStream();
var deflater = new Deflater(level, !zlib);
using (DeflaterOutputStream outStream = new DeflaterOutputStream(memoryStream, deflater))
{
outStream.IsStreamOwner = false;
outStream.Write(data, 0, data.Length);
outStream.Flush();
outStream.Finish();
}
return memoryStream;
}
private void RandomDeflateInflate(int size, int level, bool zlib)
{
byte[] buffer = new byte[size];
var rnd = new Random();
rnd.NextBytes(buffer);
MemoryStream ms = Deflate(buffer, level, zlib);
Inflate(ms, buffer, level, zlib);
}
/// <summary>
/// Basic inflate/deflate test
/// </summary>
[Test]
[Category("Base")]
public void InflateDeflateZlib()
{
for (int level = 0; level < 10; ++level)
{
RandomDeflateInflate(100000, level, true);
}
}
private delegate void RunCompress(byte[] buffer);
private int runLevel;
private bool runZlib;
private long runCount;
private Random runRandom = new Random(5);
private void DeflateAndInflate(byte[] buffer)
{
++runCount;
MemoryStream ms = Deflate(buffer, runLevel, runZlib);
Inflate(ms, buffer, runLevel, runZlib);
}
private void TryVariants(RunCompress test, byte[] buffer, int index)
{
int worker = 0;
while (worker <= 255)
{
buffer[index] = (byte)worker;
if (index < buffer.Length - 1)
{
TryVariants(test, buffer, index + 1);
}
else
{
test(buffer);
}
worker += runRandom.Next(256);
}
}
private void TryManyVariants(int level, bool zlib, RunCompress test, byte[] buffer)
{
runLevel = level;
runZlib = zlib;
TryVariants(test, buffer, 0);
}
// TODO: Fix this
//[Test]
//[Category("Base")]
//public void SmallBlocks()
//{
// byte[] buffer = new byte[10];
// Array.Clear(buffer, 0, buffer.Length);
// TryManyVariants(0, false, new RunCompress(DeflateAndInflate), buffer);
//}
/// <summary>
/// Basic inflate/deflate test
/// </summary>
[Test]
[Category("Base")]
public void InflateDeflateNonZlib()
{
for (int level = 0; level < 10; ++level)
{
RandomDeflateInflate(100000, level, false);
}
}
[Test]
[Category("Base")]
public void CloseDeflatorWithNestedUsing()
{
string tempFile = null;
try
{
tempFile = Path.GetTempPath();
}
catch (SecurityException)
{
}
Assert.IsNotNull(tempFile, "No permission to execute this test?");
tempFile = Path.Combine(tempFile, "SharpZipTest.Zip");
using (FileStream diskFile = File.Create(tempFile))
using (DeflaterOutputStream deflator = new DeflaterOutputStream(diskFile))
using (StreamWriter txtFile = new StreamWriter(deflator))
{
txtFile.Write("Hello");
txtFile.Flush();
}
File.Delete(tempFile);
}
[Test]
[Category("Base")]
public void DeflatorStreamOwnership()
{
var memStream = new TrackedMemoryStream();
var s = new DeflaterOutputStream(memStream);
Assert.IsFalse(memStream.IsClosed, "Shouldnt be closed initially");
Assert.IsFalse(memStream.IsDisposed, "Shouldnt be disposed initially");
s.Close();
Assert.IsTrue(memStream.IsClosed, "Should be closed after parent owner close");
Assert.IsTrue(memStream.IsDisposed, "Should be disposed after parent owner close");
memStream = new TrackedMemoryStream();
s = new DeflaterOutputStream(memStream);
Assert.IsFalse(memStream.IsClosed, "Shouldnt be closed initially");
Assert.IsFalse(memStream.IsDisposed, "Shouldnt be disposed initially");
s.IsStreamOwner = false;
s.Close();
Assert.IsFalse(memStream.IsClosed, "Should not be closed after parent owner close");
Assert.IsFalse(memStream.IsDisposed, "Should not be disposed after parent owner close");
}
[Test]
[Category("Base")]
public void InflatorStreamOwnership()
{
var memStream = new TrackedMemoryStream();
var s = new InflaterInputStream(memStream);
Assert.IsFalse(memStream.IsClosed, "Shouldnt be closed initially");
Assert.IsFalse(memStream.IsDisposed, "Shouldnt be disposed initially");
s.Close();
Assert.IsTrue(memStream.IsClosed, "Should be closed after parent owner close");
Assert.IsTrue(memStream.IsDisposed, "Should be disposed after parent owner close");
memStream = new TrackedMemoryStream();
s = new InflaterInputStream(memStream);
Assert.IsFalse(memStream.IsClosed, "Shouldnt be closed initially");
Assert.IsFalse(memStream.IsDisposed, "Shouldnt be disposed initially");
s.IsStreamOwner = false;
s.Close();
Assert.IsFalse(memStream.IsClosed, "Should not be closed after parent owner close");
Assert.IsFalse(memStream.IsDisposed, "Should not be disposed after parent owner close");
}
[Test]
[Category("Base")]
public void CloseInflatorWithNestedUsing()
{
string tempFile = null;
try
{
tempFile = Path.GetTempPath();
}
catch (SecurityException)
{
}
Assert.IsNotNull(tempFile, "No permission to execute this test?");
tempFile = Path.Combine(tempFile, "SharpZipTest.Zip");
using (FileStream diskFile = File.Create(tempFile))
using (DeflaterOutputStream deflator = new DeflaterOutputStream(diskFile))
using (StreamWriter textWriter = new StreamWriter(deflator))
{
textWriter.Write("Hello");
textWriter.Flush();
}
using (FileStream diskFile = File.OpenRead(tempFile))
using (InflaterInputStream deflator = new InflaterInputStream(diskFile))
using (StreamReader textReader = new StreamReader(deflator))
{
char[] buffer = new char[5];
int readCount = textReader.Read(buffer, 0, 5);
Assert.AreEqual(5, readCount);
var b = new StringBuilder();
b.Append(buffer);
Assert.AreEqual("Hello", b.ToString());
}
File.Delete(tempFile);
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
/******************************************************************************
* This file is auto-generated from a template file by the GenerateTests.csx *
* script in tests\src\JIT\HardwareIntrinsics\Arm\Shared. In order to make *
* changes, please update the corresponding template and run according to the *
* directions listed in the file. *
******************************************************************************/
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Intrinsics;
using System.Runtime.Intrinsics.Arm;
namespace JIT.HardwareIntrinsics.Arm
{
public static partial class Program
{
private static void LeadingZeroCount_Int64()
{
var test = new ScalarUnaryOpTest__LeadingZeroCount_Int64();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.ReadUnaligned
test.RunBasicScenario_UnsafeRead();
// Validates calling via reflection works, using Unsafe.ReadUnaligned
test.RunReflectionScenario_UnsafeRead();
// Validates passing a static member works
test.RunClsVarScenario();
// Validates passing a local works, using Unsafe.ReadUnaligned
test.RunLclVarScenario_UnsafeRead();
// Validates passing the field of a local class works
test.RunClassLclFldScenario();
// Validates passing an instance member of a class works
test.RunClassFldScenario();
// Validates passing the field of a local struct works
test.RunStructLclFldScenario();
// Validates passing an instance member of a struct works
test.RunStructFldScenario();
}
else
{
// Validates we throw on unsupported hardware
test.RunUnsupportedScenario();
}
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class ScalarUnaryOpTest__LeadingZeroCount_Int64
{
private struct TestStruct
{
public Int64 _fld;
public static TestStruct Create()
{
var testStruct = new TestStruct();
testStruct._fld = TestLibrary.Generator.GetInt64();
return testStruct;
}
public void RunStructFldScenario(ScalarUnaryOpTest__LeadingZeroCount_Int64 testClass)
{
var result = ArmBase.Arm64.LeadingZeroCount(_fld);
testClass.ValidateResult(_fld, result);
}
}
private static Int64 _data;
private static Int64 _clsVar;
private Int64 _fld;
static ScalarUnaryOpTest__LeadingZeroCount_Int64()
{
_clsVar = TestLibrary.Generator.GetInt64();
}
public ScalarUnaryOpTest__LeadingZeroCount_Int64()
{
Succeeded = true;
_fld = TestLibrary.Generator.GetInt64();
_data = TestLibrary.Generator.GetInt64();
}
public bool IsSupported => ArmBase.Arm64.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead));
var result = ArmBase.Arm64.LeadingZeroCount(
Unsafe.ReadUnaligned<Int64>(ref Unsafe.As<Int64, byte>(ref _data))
);
ValidateResult(_data, result);
}
public void RunReflectionScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead));
var result = typeof(ArmBase.Arm64).GetMethod(nameof(ArmBase.Arm64.LeadingZeroCount), new Type[] { typeof(Int64) })
.Invoke(null, new object[] {
Unsafe.ReadUnaligned<Int64>(ref Unsafe.As<Int64, byte>(ref _data))
});
ValidateResult(_data, (Int32)result);
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = ArmBase.Arm64.LeadingZeroCount(
_clsVar
);
ValidateResult(_clsVar, result);
}
public void RunLclVarScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead));
var data = Unsafe.ReadUnaligned<Int64>(ref Unsafe.As<Int64, byte>(ref _data));
var result = ArmBase.Arm64.LeadingZeroCount(data);
ValidateResult(data, result);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new ScalarUnaryOpTest__LeadingZeroCount_Int64();
var result = ArmBase.Arm64.LeadingZeroCount(test._fld);
ValidateResult(test._fld, result);
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = ArmBase.Arm64.LeadingZeroCount(_fld);
ValidateResult(_fld, result);
}
public void RunStructLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario));
var test = TestStruct.Create();
var result = ArmBase.Arm64.LeadingZeroCount(test._fld);
ValidateResult(test._fld, result);
}
public void RunStructFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario));
var test = TestStruct.Create();
test.RunStructFldScenario(this);
}
public void RunUnsupportedScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario));
bool succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
succeeded = true;
}
if (!succeeded)
{
Succeeded = false;
}
}
private void ValidateResult(Int64 data, Int32 result, [CallerMemberName] string method = "")
{
var isUnexpectedResult = false;
int expectedResult = 0; for (int index = 63; (((ulong)data >> index) & 1) == 0; index--) { expectedResult++; } isUnexpectedResult = (expectedResult != result);
if (isUnexpectedResult)
{
TestLibrary.TestFramework.LogInformation($"{nameof(ArmBase.Arm64)}.{nameof(ArmBase.Arm64.LeadingZeroCount)}<Int32>(Int64): LeadingZeroCount failed:");
TestLibrary.TestFramework.LogInformation($" data: {data}");
TestLibrary.TestFramework.LogInformation($" result: {result}");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
}
}
| |
namespace Microsoft.Protocols.TestSuites.MS_ADMINS
{
using System;
using System.Collections.Generic;
using System.Net;
using System.Web.Services.Protocols;
using Microsoft.Protocols.TestSuites.Common;
using Microsoft.Protocols.TestTools;
/// <summary>
/// MS-ADMINS Adapter implementation.
/// </summary>
public partial class MS_ADMINSAdapter : ManagedAdapterBase, IMS_ADMINSAdapter
{
/// <summary>
/// A list used to record all site collection created by test cases.
/// </summary>
private static List<string> listCreatedSiteCollection = new List<string>();
/// <summary>
/// An Administration Web Services instance.
/// </summary>
private AdminSoap adminService;
/// <summary>
/// Gets or sets the destination Url of web service operation.
/// </summary>
/// <value>Destination Url of web service operation.</value>
public string Url
{
get
{
return this.adminService.Url;
}
set
{
this.adminService.Url = value;
}
}
#region Test Suite Initialization and CleanUp
/// <summary>
/// Overrides IAdapter's Initialize().
/// </summary>
/// <param name="testSite">A parameter represents an ITestSite instance.</param>
public override void Initialize(ITestSite testSite)
{
base.Initialize(testSite);
testSite.DefaultProtocolDocShortName = "MS-ADMINS";
// Initialize the AdminSoap.
this.adminService = Proxy.CreateProxy<AdminSoap>(this.Site);
// Merge the common configuration into local configuration
string conmmonConfigFileName = Common.GetConfigurationPropertyValue("CommonConfigurationFileName", this.Site);
// Execute the merge the common configuration
Common.MergeGlobalConfig(conmmonConfigFileName, this.Site);
Common.CheckCommonProperties(this.Site, true);
// Load SHOULDMAY configuration
Common.MergeSHOULDMAYConfig(this.Site);
TransportProtocol transport = Common.GetConfigurationPropertyValue<TransportProtocol>("TransportType", this.Site);
switch (transport)
{
case TransportProtocol.HTTP:
{
this.adminService.Url = Common.GetConfigurationPropertyValue("HTTPTargetServiceUrl", this.Site);
break;
}
default:
{
this.adminService.Url = Common.GetConfigurationPropertyValue("HTTPSTargetServiceUrl", this.Site);
// When request Url include HTTPS prefix, avoid closing base connection.
// Local client will accept all certificates after executing this function.
Common.AcceptServerCertificate();
break;
}
}
string userName = Common.GetConfigurationPropertyValue("UserName", this.Site);
string password = Common.GetConfigurationPropertyValue("Password", this.Site);
string domain = Common.GetConfigurationPropertyValue("Domain", this.Site);
this.adminService.Credentials = new NetworkCredential(userName, password, domain);
this.SetSoapVersion(this.adminService);
// Configure the service timeout.
string soapTimeOut = Common.GetConfigurationPropertyValue("ServiceTimeOut", this.Site);
// 60000 means the configure SOAP Timeout is in milliseconds.
this.adminService.Timeout = Convert.ToInt32(soapTimeOut) * 60000;
}
/// <summary>
/// A method used to Clean up meetings added by test case.
/// </summary>
public override void Reset()
{
base.Reset();
// Delete all sites created by test case and make sure current environment is clean.
foreach (string urlCache in listCreatedSiteCollection.ToArray())
{
this.DeleteSite(urlCache);
}
}
#endregion
/// <summary>
/// Creates a Site collection.
/// </summary>
/// <param name="url">The absolute URL of the site collection.</param>
/// <param name="title">The display name of the site collection.</param>
/// <param name="description">A description of the site collection.</param>
/// <param name="lcid">The language that is used in the site collection.</param>
/// <param name="webTemplate">The name of the site template which is used when creating the site collection.</param>
/// <param name="ownerLogin">The user name of the site collection owner.</param>
/// <param name="ownerName">The display name of the owner.</param>
/// <param name="ownerEmail">The e-mail address of the owner.</param>
/// <param name="portalUrl">The URL of the portal site for the site collection.</param>
/// <param name="portalName">The name of the portal site for the site collection.</param>
/// <returns>The CreateSite result.</returns>
public string CreateSite(string url, string title, string description, int? lcid, string webTemplate, string ownerLogin, string ownerName, string ownerEmail, string portalUrl, string portalName)
{
string result = null;
try
{
// Call CreateSite method.
result = this.adminService.CreateSite(url, title, description, lcid ?? 0, lcid.HasValue, webTemplate, ownerLogin, ownerName, ownerEmail, portalUrl, portalName);
// Add the site's url to cache list.
listCreatedSiteCollection.Add(result);
// Capture the transport related requirements and verify CreateSite response requirements.
this.VerifyTransportRelatedRequirements();
this.ValidateCreateSiteResponseData(result);
}
catch (SoapException soapEx)
{
// Validate soap fault message structure and capture related requirements.
this.VerifySoapFaultRequirements(soapEx);
throw new SoapException(soapEx.Detail.InnerText, soapEx.Code, soapEx.Actor, soapEx.Detail, soapEx);
}
catch (WebException webEx)
{
Site.Assert.Fail("Server failed to create the site collection: {0}", webEx.Message);
throw;
}
return result;
}
/// <summary>
/// Deletes the specified Site collection.
/// </summary>
/// <param name="url">The absolute URL of the site collection which is to be deleted.</param>
public void DeleteSite(string url)
{
try
{
// Call DeleteSite method.
this.adminService.DeleteSite(url);
// Capture the transport related requirements and verify DeleteSite response requirements.
this.VerifyTransportRelatedRequirements();
this.ValidateDeleteSiteResponse();
}
catch (SoapException ex)
{
Site.Log.Add(LogEntryKind.Debug, "Failed to Delete the site {0}, and the returned SOAP exception is: \r\n{1}!", url, ex.Detail.InnerXml);
// Validate soap fault message structure and capture related requirements.
this.VerifySoapFaultRequirements(ex);
throw new SoapException(ex.Detail.InnerText, ex.Code, ex.Actor, ex.Detail, ex);
}
finally
{
// Remove the deleted url from cache list.
listCreatedSiteCollection.Remove(url);
}
}
/// <summary>
/// Returns information about the languages which are used in the protocol server deployment.
/// </summary>
/// <returns>The GetLanguages result.</returns>
public GetLanguagesResponseGetLanguagesResult GetLanguages()
{
GetLanguagesResponseGetLanguagesResult getLanguagesResult = null;
try
{
getLanguagesResult = this.adminService.GetLanguages();
// Capture the transport related requirements and verify GetLanguages response requirements.
this.VerifyTransportRelatedRequirements();
this.ValidateGetLanguagesResponseData(getLanguagesResult);
}
catch (SoapException ex)
{
Site.Log.Add(LogEntryKind.Debug, "Throw exceptions while get LCID values that specify the languages used in the protocol server deployment: {0}.", ex.Message);
throw new SoapException(ex.Detail.InnerText, ex.Code, ex.Actor, ex.Detail, ex);
}
return getLanguagesResult;
}
/// <summary>
/// Set the SOAP version according to the SoapVersion property.
/// </summary>
/// <param name="adminProxy">set admin proxy</param>
private void SetSoapVersion(AdminSoap adminProxy)
{
SoapVersion soapVersion = Common.GetConfigurationPropertyValue<SoapVersion>("SoapVersion", this.Site);
switch (soapVersion)
{
case SoapVersion.SOAP11:
{
adminProxy.SoapVersion = SoapProtocolVersion.Soap11;
break;
}
default:
{
adminProxy.SoapVersion = SoapProtocolVersion.Soap12;
break;
}
}
}
}
}
| |
/*
Copyright (c) Microsoft Corporation. All rights reserved.
Licensed under the MIT License. See License.txt in the project root for license information.
*/
namespace Adxstudio.Xrm.EntityForm
{
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Adxstudio.Xrm.Core;
using Adxstudio.Xrm.Resources;
using Adxstudio.Xrm.Web;
using Adxstudio.Xrm.Web.UI.EntityForm;
using Adxstudio.Xrm.Web.UI.WebControls;
using Adxstudio.Xrm.Globalization;
using Microsoft.Xrm.Client;
using Microsoft.Xrm.Client.Messages;
using Microsoft.Xrm.Portal.Configuration;
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Client;
using Microsoft.Xrm.Sdk.Messages;
using Microsoft.Xrm.Sdk.Metadata;
internal class EntityFormFunctions
{
internal static string DefaultPreviousButtonCssClass = "button previous";
internal static string DefaultNextButtonCssClass = "button next";
internal static string DefaultSubmitButtonCssClass = "button submit";
public static readonly string DefaultAttachFileLabel = HttpUtility.JavaScriptStringEncode(ResourceManager.GetString("Attach_A_File_DefaultText"));
public static readonly string DefaultPreviousButtonText = HttpUtility.JavaScriptStringEncode(ResourceManager.GetString("Previous_Button_Label"));
public static readonly string DefaultNextButtonText = HttpUtility.JavaScriptStringEncode(ResourceManager.GetString("Next_Button_Text"));
public static readonly string DefaultSubmitButtonText = HttpUtility.JavaScriptStringEncode(ResourceManager.GetString("Submit_Button_Label_Text"));
public static readonly string DefaultSubmitButtonBusyText = HttpUtility.JavaScriptStringEncode(ResourceManager.GetString("Default_Modal_Processing_Text"));
internal static bool TryGetRecord(OrganizationServiceContext context, FormEntitySourceDefinition definition, out Entity record)
{
record = context.CreateQuery(definition.LogicalName).FirstOrDefault(o => o.GetAttributeValue<Guid>(definition.PrimaryKeyLogicalName) == definition.ID);
return record != null;
}
internal static void TrySetState(OrganizationServiceContext context, EntityReference entityReference, int state)
{
try
{
context.SetState(state, -1, entityReference);
}
catch (Exception ex)
{
ADXTrace.Instance.TraceError(TraceCategory.Application, string.Format("Failed to set statecode. {0}", ex.ToString()));
}
}
internal static string TryConvertAttributeValueToString(OrganizationServiceContext context, Dictionary<string, AttributeTypeCode?> attributeTypeCodeDictionary, string entityName, string attributeName, object value)
{
if (context == null || string.IsNullOrWhiteSpace(entityName) || string.IsNullOrWhiteSpace(attributeName))
{
return string.Empty;
}
var newValue = string.Empty;
var attributeTypeCode = attributeTypeCodeDictionary.FirstOrDefault(a => a.Key == attributeName).Value;
if (attributeTypeCode == null)
{
ADXTrace.Instance.TraceError(TraceCategory.Application, "Unable to recognize the attribute specified.");
return string.Empty;
}
try
{
switch (attributeTypeCode)
{
case AttributeTypeCode.BigInt:
newValue = value == null ? string.Empty : Convert.ToInt64(value).ToString(CultureInfo.InvariantCulture);
break;
case AttributeTypeCode.Boolean:
newValue = value == null ? string.Empty : Convert.ToBoolean(value).ToString(CultureInfo.InvariantCulture);
break;
case AttributeTypeCode.Customer:
if (value is EntityReference)
{
var entityref = value as EntityReference;
newValue = entityref.Id.ToString();
}
break;
case AttributeTypeCode.DateTime:
newValue = value == null ? string.Empty : Convert.ToDateTime(value).ToUniversalTime().ToString(CultureInfo.InvariantCulture);
break;
case AttributeTypeCode.Decimal:
newValue = value == null ? string.Empty : Convert.ToDecimal(value).ToString(CultureInfo.InvariantCulture);
break;
case AttributeTypeCode.Double:
newValue = value == null ? string.Empty : Convert.ToDouble(value).ToString(CultureInfo.InvariantCulture);
break;
case AttributeTypeCode.Integer:
newValue = value == null ? string.Empty : Convert.ToInt32(value).ToString(CultureInfo.InvariantCulture);
break;
case AttributeTypeCode.Lookup:
if (value is EntityReference)
{
var entityref = value as EntityReference;
newValue = entityref.Id.ToString();
}
break;
case AttributeTypeCode.Memo:
newValue = value as string;
break;
case AttributeTypeCode.Money:
newValue = value == null ? string.Empty : Convert.ToDecimal(value).ToString(CultureInfo.InvariantCulture);
break;
case AttributeTypeCode.Picklist:
newValue = value == null ? string.Empty : Convert.ToInt32(value).ToString(CultureInfo.InvariantCulture);
break;
case AttributeTypeCode.State:
newValue = value == null ? string.Empty : Convert.ToInt32(value).ToString(CultureInfo.InvariantCulture);
break;
case AttributeTypeCode.Status:
newValue = value == null ? string.Empty : Convert.ToInt32(value).ToString(CultureInfo.InvariantCulture);
break;
case AttributeTypeCode.String:
newValue = value as string;
break;
case AttributeTypeCode.Uniqueidentifier:
if (value is Guid)
{
var id = (Guid)value;
newValue = id.ToString();
}
break;
default:
ADXTrace.Instance.TraceWarning(TraceCategory.Application, string.Format("Attribute type '{0}' is unsupported.", attributeTypeCode));
break;
}
}
catch (Exception ex)
{
WebEventSource.Log.GenericWarningException(ex, string.Format("Attribute specified is expecting a {0}. The value provided is not valid.", attributeTypeCode));
}
return newValue;
}
internal static void DisplayMessage(Web.UI.WebControls.EntityForm sender, string message, string cssClass, bool hideForm)
{
if (sender == null || string.IsNullOrWhiteSpace(message))
{
return;
}
DisplayMessage(message, cssClass, hideForm, sender);
}
internal static void DisplayMessage(object sender, string message, string cssClass, bool hideForm)
{
var formView = (CrmEntityFormView)sender;
var container = formView.Parent;
DisplayMessage(message, cssClass, hideForm, container);
}
internal static void DisplayMessage(Control container, string message, string cssClass, bool hideForm)
{
if (container == null || string.IsNullOrWhiteSpace(message))
{
return;
}
DisplayMessage(message, cssClass, hideForm, container);
}
internal static void DisplayMessage(string message, string cssClass, bool hideForm, Control container)
{
var messagePanel = (Panel)container.FindControl("MessagePanel");
var formPanel = (Panel)container.FindControl("EntityFormPanel");
var messageLabel = (System.Web.UI.WebControls.Label)container.FindControl("MessageLabel");
if (messagePanel == null)
{
messagePanel = new Panel { ID = "MessagePanel", CssClass = "message alert" };
container.Controls.Add(messagePanel);
}
if (!string.IsNullOrWhiteSpace(cssClass))
{
messagePanel.CssClass = string.Format("{0} {1}", messagePanel.CssClass, cssClass);
}
if (formPanel != null)
{
formPanel.Visible = !hideForm;
}
if (messageLabel == null)
{
messageLabel = new System.Web.UI.WebControls.Label
{
ID = "MessageLabel",
Text = string.IsNullOrWhiteSpace(message) ? string.Empty : message
};
messagePanel.Controls.Add(messageLabel);
}
else
{
messageLabel.Text = string.IsNullOrWhiteSpace(message) ? string.Empty : message;
}
if (!string.IsNullOrWhiteSpace(cssClass))
{
messagePanel.CssClass = string.Format("{0} {1}", messagePanel.CssClass, cssClass);
}
messagePanel.Visible = true;
}
internal static void Associate(OrganizationServiceContext serviceContext, EntityReference related)
{
var targetEntityLogicalName = HttpContext.Current.Request["refentity"];
var targetEntityId = HttpContext.Current.Request["refid"];
var relationshipName = HttpContext.Current.Request["refrel"];
var relationshipRole = HttpContext.Current.Request["refrelrole"];
Guid targetId;
if (string.IsNullOrWhiteSpace(targetEntityLogicalName) || string.IsNullOrWhiteSpace(targetEntityId) ||
string.IsNullOrWhiteSpace(relationshipName) || related == null)
{
ADXTrace.Instance.TraceInfo(TraceCategory.Application, "Request did not contain parameters 'refentity', 'refid', 'refrel'");
return;
}
if (!Guid.TryParse(targetEntityId, out targetId))
{
ADXTrace.Instance.TraceError(TraceCategory.Application, "Request did not contain a valid guid 'refid'");
return;
}
try
{
var relationship = new Relationship(relationshipName);
if (!string.IsNullOrWhiteSpace(relationshipRole))
{
switch (relationshipRole)
{
case "Referenced":
relationship.PrimaryEntityRole = EntityRole.Referenced;
break;
case "Referencing":
relationship.PrimaryEntityRole = EntityRole.Referencing;
return;
break;
default:
ADXTrace.Instance.TraceError(TraceCategory.Application, "Relationship Primary Entity Role provided by parameter named 'refrelrole' is not valid.");
break;
}
}
var associateRequest = new AssociateRequest
{
Target = new EntityReference(targetEntityLogicalName, targetId),
Relationship = relationship,
RelatedEntities = new EntityReferenceCollection { related }
};
serviceContext.Execute(associateRequest);
}
catch (Exception ex)
{
ADXTrace.Instance.TraceError(TraceCategory.Application, ex.ToString());
}
}
internal static void AssociateEntity(OrganizationServiceContext context, Entity entityform, Guid sourceEntityId)
{
var setEntityReference = entityform.GetAttributeValue<bool?>("adx_setentityreference") ?? false;
if (!setEntityReference) return;
var targetEntityId = Guid.Empty;
var targetEntityPrimaryKey = string.Empty;
var sourceEntityName = entityform.GetAttributeValue<string>("adx_entityname");
var sourceEntityPrimaryKey = entityform.GetAttributeValue<string>("adx_primarykeyname");
var targetEntityName = entityform.GetAttributeValue<string>("adx_referenceentitylogicalname");
var relationshipName = entityform.GetAttributeValue<string>("adx_referenceentityrelationshipname") ?? string.Empty;
if (string.IsNullOrWhiteSpace(relationshipName))
{
ADXTrace.Instance.TraceInfo(TraceCategory.Application, "Entity Relationship Name not provided. Entity Association not required.");
return;
}
try
{
var referenceQueryStringName = entityform.GetAttributeValue<string>("adx_referencequerystringname") ?? string.Empty;
var referenceQueryStringValue = HttpContext.Current.Request[referenceQueryStringName];
var querystringIsPrimaryKey = entityform.GetAttributeValue<bool?>("adx_referencequerystringisprimarykey") ?? false;
if (!querystringIsPrimaryKey)
{
var referenceQueryAttributeName = entityform.GetAttributeValue<string>("adx_referencequeryattributelogicalname");
var entity =
context.CreateQuery(targetEntityName).FirstOrDefault(
o => o.GetAttributeValue<string>(referenceQueryAttributeName) == referenceQueryStringValue);
if (entity != null) { targetEntityId = entity.Id; }
}
else
{
Guid.TryParse(referenceQueryStringValue, out targetEntityId);
}
if (sourceEntityId == Guid.Empty || targetEntityId == Guid.Empty)
{
ADXTrace.Instance.TraceError(TraceCategory.Application, "Source and Target entity ids must not be null or empty.");
return;
}
// get the source entity
if (string.IsNullOrWhiteSpace(sourceEntityName))
{
ADXTrace.Instance.TraceError(TraceCategory.Application, "adx_entityform.adx_targetentitylogicalname must not be null.");
return;
}
if (string.IsNullOrWhiteSpace(sourceEntityPrimaryKey))
{
sourceEntityPrimaryKey = MetadataHelper.GetEntityPrimaryKeyAttributeLogicalName(context, sourceEntityName);
}
if (string.IsNullOrWhiteSpace(sourceEntityPrimaryKey))
{
ADXTrace.Instance.TraceError(TraceCategory.Application, "Failed to determine source entity primary key logical name.");
return;
}
var sourceEntity = context.CreateQuery(sourceEntityName).FirstOrDefault(o => o.GetAttributeValue<Guid>(sourceEntityPrimaryKey) == sourceEntityId);
if (sourceEntity == null)
{
ADXTrace.Instance.TraceError(TraceCategory.Application, "Source entity is null.");
return;
}
// Get the target entity
if (string.IsNullOrWhiteSpace(targetEntityName))
{
ADXTrace.Instance.TraceError(TraceCategory.Application, "Target entity name must not be null or empty.");
return;
}
if (string.IsNullOrWhiteSpace(targetEntityPrimaryKey))
{
targetEntityPrimaryKey = MetadataHelper.GetEntityPrimaryKeyAttributeLogicalName(context, targetEntityName);
}
if (string.IsNullOrWhiteSpace(targetEntityPrimaryKey))
{
ADXTrace.Instance.TraceError(TraceCategory.Application, "Failed to determine target entity primary key logical name.");
return;
}
var targetEntity = context.CreateQuery(targetEntityName).FirstOrDefault(o => o.GetAttributeValue<Guid>(targetEntityPrimaryKey) == targetEntityId);
if (targetEntity == null)
{
ADXTrace.Instance.TraceError(TraceCategory.Application, "Target entity is null.");
return;
}
context.AddLink(sourceEntity, relationshipName, targetEntity);
}
catch (Exception ex)
{
ADXTrace.Instance.TraceError(TraceCategory.Application, string.Format("{0}", ex.ToString()));
}
}
internal static void CalculateValueOpportunity()
{
if (string.IsNullOrEmpty(HttpContext.Current.Request["refid"])) return;
var targetEntityId = HttpContext.Current.Request["refid"];
var portal = PortalCrmConfigurationManager.CreatePortalContext();
var serviceContext = portal.ServiceContext;
var adapter = new CoreDataAdapter(portal, serviceContext);
Guid id;
if (!Guid.TryParse(targetEntityId, out id)) return;
if (string.IsNullOrEmpty(HttpContext.Current.Request["refentity"])) return;
var entityReference = new EntityReference(HttpContext.Current.Request["refentity"], id);
adapter.CalculateActualValueOfOpportunity(entityReference);
var entity =
serviceContext.CreateQuery(entityReference.LogicalName)
.FirstOrDefault(e => e.GetAttributeValue<Guid>("opportunityid") == entityReference.Id);
if (entity == null) return;
serviceContext.TryRemoveFromCache(entity);
serviceContext.UpdateObject(entity);
serviceContext.SaveChanges();
}
internal static dynamic TryConvertAttributeValue(OrganizationServiceContext context, string entityName, string attributeName, object value, Dictionary<string, AttributeTypeCode?> AttributeTypeCodeDictionary)
{
if (context == null || string.IsNullOrWhiteSpace(entityName) || string.IsNullOrWhiteSpace(attributeName)) return null;
if (AttributeTypeCodeDictionary == null || !AttributeTypeCodeDictionary.Any())
{
AttributeTypeCodeDictionary = MetadataHelper.BuildAttributeTypeCodeDictionary(context, entityName);
}
object newValue = null;
var attributeTypeCode = AttributeTypeCodeDictionary.FirstOrDefault(a => a.Key == attributeName).Value;
if (attributeTypeCode == null)
{
ADXTrace.Instance.TraceError(TraceCategory.Application, string.Format("Unable to recognize the attribute '{0}' specified.", attributeName));
return null;
}
try
{
switch (attributeTypeCode)
{
case AttributeTypeCode.BigInt:
newValue = value == null ? (object)null : Convert.ToInt64(value);
break;
case AttributeTypeCode.Boolean:
newValue = value == null ? (object)null : Convert.ToBoolean(value);
break;
case AttributeTypeCode.Customer:
if (value is EntityReference)
{
newValue = value as EntityReference;
}
else if (value is Guid)
{
var metadata = MetadataHelper.GetEntityMetadata(context, entityName);
var attribute = metadata.Attributes.FirstOrDefault(a => a.LogicalName == attributeName);
if (attribute != null)
{
var lookupAttribute = attribute as LookupAttributeMetadata;
if (lookupAttribute != null && lookupAttribute.Targets.Length == 1)
{
var lookupEntityType = lookupAttribute.Targets[0];
newValue = new EntityReference(lookupEntityType, (Guid)value);
}
}
}
break;
case AttributeTypeCode.DateTime:
newValue = value == null ? (object)null : Convert.ToDateTime(value).ToUniversalTime();
break;
case AttributeTypeCode.Decimal:
newValue = value == null ? (object)null : Convert.ToDecimal(value);
break;
case AttributeTypeCode.Double:
newValue = value == null ? (object)null : Convert.ToDouble(value);
break;
case AttributeTypeCode.Integer:
newValue = value == null ? (object)null : Convert.ToInt32(value);
break;
case AttributeTypeCode.Lookup:
if (value is EntityReference)
{
newValue = value as EntityReference;
}
else if (value is Guid)
{
var metadata = MetadataHelper.GetEntityMetadata(context, entityName);
var attribute = metadata.Attributes.FirstOrDefault(a => a.LogicalName == attributeName);
if (attribute != null)
{
var lookupAttribute = attribute as LookupAttributeMetadata;
if (lookupAttribute != null && lookupAttribute.Targets.Length == 1)
{
var lookupEntityType = lookupAttribute.Targets[0];
newValue = new EntityReference(lookupEntityType, (Guid)value);
}
}
}
break;
case AttributeTypeCode.Memo:
newValue = value as string;
break;
case AttributeTypeCode.Money:
newValue = value == null ? (object)null : Convert.ToDecimal(value);
break;
case AttributeTypeCode.Picklist:
var plMetadata = MetadataHelper.GetEntityMetadata(context, entityName);
var plAttribute = plMetadata.Attributes.FirstOrDefault(a => a.LogicalName == attributeName);
if (plAttribute != null)
{
var picklistAttribute = plAttribute as PicklistAttributeMetadata;
if (picklistAttribute != null)
{
int picklistInt;
OptionMetadata picklistValue;
if (int.TryParse(string.Empty + value, out picklistInt))
{
picklistValue = picklistAttribute.OptionSet.Options.FirstOrDefault(o => o.Value == picklistInt);
}
else
{
picklistValue = picklistAttribute.OptionSet.Options.FirstOrDefault(o => o.Label.GetLocalizedLabelString() == string.Empty + value);
}
if (picklistValue != null && picklistValue.Value.HasValue)
{
newValue = value == null ? null : new OptionSetValue(picklistValue.Value.Value);
}
}
}
break;
case AttributeTypeCode.State:
ADXTrace.Instance.TraceWarning(TraceCategory.Application, string.Format("Attribute '{0}' type '{1}' is unsupported. The state attribute is created automatically when the entity is created. The options available for this attribute are read-only.", attributeName, attributeTypeCode));
break;
case AttributeTypeCode.Status:
if (value == null)
{
return false;
}
var optionSetValue = new OptionSetValue(Convert.ToInt32(value));
newValue = optionSetValue;
break;
case AttributeTypeCode.String:
newValue = value as string;
break;
default:
ADXTrace.Instance.TraceWarning(TraceCategory.Application, string.Format("Attribute '{0}' type '{1}' is unsupported.", attributeName, attributeTypeCode));
break;
}
}
catch (Exception ex)
{
WebEventSource.Log.GenericWarningException(ex, string.Format("Attribute '{0}' specified is expecting a {1}. The value provided is not valid.", attributeName, attributeTypeCode));
}
return newValue;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// See the LICENSE file in the project root for more information.
//
// System.Net.HttpConnection
//
// Author:
// Gonzalo Paniagua Javier ([email protected])
//
// Copyright (c) 2005-2009 Novell, Inc. (http://www.novell.com)
// Copyright (c) 2012 Xamarin, Inc. (http://xamarin.com)
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System.IO;
using System.Net.Security;
using System.Net.Sockets;
using System.Security.Authentication;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Threading;
namespace System.Net
{
internal sealed class HttpConnection
{
private static AsyncCallback s_onreadCallback = new AsyncCallback(OnRead);
private const int BufferSize = 8192;
private Socket _socket;
private Stream _stream;
private HttpEndPointListener _epl;
private MemoryStream _memoryStream;
private byte[] _buffer;
private HttpListenerContext _context;
private StringBuilder _currentLine;
private ListenerPrefix _prefix;
private HttpRequestStream _requestStream;
private HttpResponseStream _responseStream;
private bool _chunked;
private int _reuses;
private bool _contextBound;
private bool _secure;
private X509Certificate _cert;
private int _timeout = 90000; // 90k ms for first request, 15k ms from then on
private Timer _timer;
private IPEndPoint _localEndPoint;
private HttpListener _lastListener;
private int[] _clientCertErrors;
private X509Certificate2 _clientCert;
private SslStream _sslStream;
private InputState _inputState = InputState.RequestLine;
private LineState _lineState = LineState.None;
private int _position;
public HttpConnection(Socket sock, HttpEndPointListener epl, bool secure, X509Certificate cert)
{
_socket = sock;
_epl = epl;
_secure = secure;
_cert = cert;
if (secure == false)
{
_stream = new NetworkStream(sock, false);
}
else
{
_sslStream = epl.Listener.CreateSslStream(new NetworkStream(sock, false), false, (t, c, ch, e) =>
{
if (c == null)
{
return true;
}
var c2 = c as X509Certificate2;
if (c2 == null)
{
c2 = new X509Certificate2(c.GetRawCertData());
}
_clientCert = c2;
_clientCertErrors = new int[] { (int)e };
return true;
});
_stream = _sslStream;
}
_timer = new Timer(OnTimeout, null, Timeout.Infinite, Timeout.Infinite);
if (_sslStream != null) {
_sslStream.AuthenticateAsServer (_cert, true, (SslProtocols)ServicePointManager.SecurityProtocol, false);
}
Init();
}
internal int[] ClientCertificateErrors
{
get { return _clientCertErrors; }
}
internal X509Certificate2 ClientCertificate
{
get { return _clientCert; }
}
internal SslStream SslStream
{
get { return _sslStream; }
}
private void Init()
{
_contextBound = false;
_requestStream = null;
_responseStream = null;
_prefix = null;
_chunked = false;
_memoryStream = new MemoryStream();
_position = 0;
_inputState = InputState.RequestLine;
_lineState = LineState.None;
_context = new HttpListenerContext(this);
}
public Stream ConnectedStream => _stream;
public bool IsClosed
{
get { return (_socket == null); }
}
public int Reuses
{
get { return _reuses; }
}
public IPEndPoint LocalEndPoint
{
get
{
if (_localEndPoint != null)
return _localEndPoint;
_localEndPoint = (IPEndPoint)_socket.LocalEndPoint;
return _localEndPoint;
}
}
public IPEndPoint RemoteEndPoint
{
get { return (IPEndPoint)_socket.RemoteEndPoint; }
}
public bool IsSecure
{
get { return _secure; }
}
public ListenerPrefix Prefix
{
get { return _prefix; }
set { _prefix = value; }
}
private void OnTimeout(object unused)
{
CloseSocket();
Unbind();
}
public void BeginReadRequest()
{
if (_buffer == null)
_buffer = new byte[BufferSize];
try
{
if (_reuses == 1)
_timeout = 15000;
_timer.Change(_timeout, Timeout.Infinite);
_stream.BeginRead(_buffer, 0, BufferSize, s_onreadCallback, this);
}
catch
{
_timer.Change(Timeout.Infinite, Timeout.Infinite);
CloseSocket();
Unbind();
}
}
public HttpRequestStream GetRequestStream(bool chunked, long contentlength)
{
if (_requestStream == null)
{
byte[] buffer = _memoryStream.GetBuffer();
int length = (int)_memoryStream.Length;
_memoryStream = null;
if (chunked)
{
_chunked = true;
_context.Response.SendChunked = true;
_requestStream = new ChunkedInputStream(_context, _stream, buffer, _position, length - _position);
}
else
{
_requestStream = new HttpRequestStream(_stream, buffer, _position, length - _position, contentlength);
}
}
return _requestStream;
}
public HttpResponseStream GetResponseStream()
{
if (_responseStream == null)
{
HttpListener listener = _context._listener;
if (listener == null)
return new HttpResponseStream(_stream, _context.Response, true);
_responseStream = new HttpResponseStream(_stream, _context.Response, listener.IgnoreWriteExceptions);
}
return _responseStream;
}
private static void OnRead(IAsyncResult ares)
{
HttpConnection cnc = (HttpConnection)ares.AsyncState;
cnc.OnReadInternal(ares);
}
private void OnReadInternal(IAsyncResult ares)
{
_timer.Change(Timeout.Infinite, Timeout.Infinite);
int nread = -1;
try
{
nread = _stream.EndRead(ares);
_memoryStream.Write(_buffer, 0, nread);
if (_memoryStream.Length > 32768)
{
SendError(HttpStatusDescription.Get(400), 400);
Close(true);
return;
}
}
catch
{
if (_memoryStream != null && _memoryStream.Length > 0)
SendError();
if (_socket != null)
{
CloseSocket();
Unbind();
}
return;
}
if (nread == 0)
{
CloseSocket();
Unbind();
return;
}
if (ProcessInput(_memoryStream))
{
if (!_context.HaveError)
_context.Request.FinishInitialization();
if (_context.HaveError)
{
SendError();
Close(true);
return;
}
if (!_epl.BindContext(_context))
{
const int NotFoundErrorCode = 404;
SendError(HttpStatusDescription.Get(NotFoundErrorCode), NotFoundErrorCode);
Close(true);
return;
}
HttpListener listener = _context._listener;
if (_lastListener != listener)
{
RemoveConnection();
listener.AddConnection(this);
_lastListener = listener;
}
_contextBound = true;
listener.RegisterContext(_context);
return;
}
_stream.BeginRead(_buffer, 0, BufferSize, s_onreadCallback, this);
}
private void RemoveConnection()
{
if (_lastListener == null)
_epl.RemoveConnection(this);
else
_lastListener.RemoveConnection(this);
}
private enum InputState
{
RequestLine,
Headers
}
private enum LineState
{
None,
CR,
LF
}
// true -> done processing
// false -> need more input
private bool ProcessInput(MemoryStream ms)
{
byte[] buffer = ms.GetBuffer();
int len = (int)ms.Length;
int used = 0;
string line;
while (true)
{
if (_context.HaveError)
return true;
if (_position >= len)
break;
try
{
line = ReadLine(buffer, _position, len - _position, ref used);
_position += used;
}
catch
{
_context.ErrorMessage = HttpStatusDescription.Get(400);
_context.ErrorStatus = 400;
return true;
}
if (line == null)
break;
if (line == "")
{
if (_inputState == InputState.RequestLine)
continue;
_currentLine = null;
ms = null;
return true;
}
if (_inputState == InputState.RequestLine)
{
_context.Request.SetRequestLine(line);
_inputState = InputState.Headers;
}
else
{
try
{
_context.Request.AddHeader(line);
}
catch (Exception e)
{
_context.ErrorMessage = e.Message;
_context.ErrorStatus = 400;
return true;
}
}
}
if (used == len)
{
ms.SetLength(0);
_position = 0;
}
return false;
}
private string ReadLine(byte[] buffer, int offset, int len, ref int used)
{
if (_currentLine == null)
_currentLine = new StringBuilder(128);
int last = offset + len;
used = 0;
for (int i = offset; i < last && _lineState != LineState.LF; i++)
{
used++;
byte b = buffer[i];
if (b == 13)
{
_lineState = LineState.CR;
}
else if (b == 10)
{
_lineState = LineState.LF;
}
else
{
_currentLine.Append((char)b);
}
}
string result = null;
if (_lineState == LineState.LF)
{
_lineState = LineState.None;
result = _currentLine.ToString();
_currentLine.Length = 0;
}
return result;
}
public void SendError(string msg, int status)
{
try
{
HttpListenerResponse response = _context.Response;
response.StatusCode = status;
response.ContentType = "text/html";
string description = HttpStatusDescription.Get(status);
string str;
if (msg != null)
str = string.Format("<h1>{0} ({1})</h1>", description, msg);
else
str = string.Format("<h1>{0}</h1>", description);
byte[] error = Encoding.Default.GetBytes(str);
response.Close(error, false);
}
catch
{
// response was already closed
}
}
public void SendError()
{
SendError(_context.ErrorMessage, _context.ErrorStatus);
}
private void Unbind()
{
if (_contextBound)
{
_epl.UnbindContext(_context);
_contextBound = false;
}
}
public void Close()
{
Close(false);
}
private void CloseSocket()
{
if (_socket == null)
return;
try
{
_socket.Close();
}
catch { }
finally
{
_socket = null;
}
RemoveConnection();
}
internal void Close(bool force)
{
if (_socket != null)
{
Stream st = GetResponseStream();
if (st != null)
st.Close();
_responseStream = null;
}
if (_socket != null)
{
force |= !_context.Request.KeepAlive;
if (!force)
force = (_context.Response.Headers[HttpKnownHeaderNames.Connection] == HttpHeaderStrings.Close);
if (!force && _context.Request.FlushInput())
{
if (_chunked && _context.Response.ForceCloseChunked == false)
{
// Don't close. Keep working.
_reuses++;
Unbind();
Init();
BeginReadRequest();
return;
}
_reuses++;
Unbind();
Init();
BeginReadRequest();
return;
}
Socket s = _socket;
_socket = null;
try
{
if (s != null)
s.Shutdown(SocketShutdown.Both);
}
catch
{
}
finally
{
if (s != null)
s.Close();
}
Unbind();
RemoveConnection();
return;
}
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
//------------------------------------------------------------------------------
using System.Data.Common;
using System.Runtime.InteropServices;
namespace System.Data.SqlTypes
{
/// <devdoc>
/// <para>
/// Represents an 8-bit unsigned integer to be stored in
/// or retrieved from a database.
/// </para>
/// </devdoc>
[StructLayout(LayoutKind.Sequential)]
public struct SqlByte : INullable, IComparable
{
private bool _fNotNull; // false if null
private byte _value;
private static readonly int s_iBitNotByteMax = ~0xff;
// constructor
// construct a Null
private SqlByte(bool fNull)
{
_fNotNull = false;
_value = 0;
}
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public SqlByte(byte value)
{
_value = value;
_fNotNull = true;
}
// INullable
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public bool IsNull
{
get { return !_fNotNull; }
}
// property: Value
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public byte Value
{
get
{
if (_fNotNull)
return _value;
else
throw new SqlNullValueException();
}
}
// Implicit conversion from byte to SqlByte
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public static implicit operator SqlByte(byte x)
{
return new SqlByte(x);
}
// Explicit conversion from SqlByte to byte. Throw exception if x is Null.
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public static explicit operator byte (SqlByte x)
{
return x.Value;
}
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public override String ToString()
{
return IsNull ? SQLResource.NullString : _value.ToString((IFormatProvider)null);
}
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public static SqlByte Parse(String s)
{
if (s == SQLResource.NullString)
return SqlByte.Null;
else
return new SqlByte(Byte.Parse(s, (IFormatProvider)null));
}
// Unary operators
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public static SqlByte operator ~(SqlByte x)
{
return x.IsNull ? Null : new SqlByte((byte)~x._value);
}
// Binary operators
// Arithmetic operators
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public static SqlByte operator +(SqlByte x, SqlByte y)
{
if (x.IsNull || y.IsNull)
return Null;
int iResult = (int)x._value + (int)y._value;
if ((iResult & s_iBitNotByteMax) != 0)
throw new OverflowException(SQLResource.ArithOverflowMessage);
else
return new SqlByte((byte)iResult);
}
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public static SqlByte operator -(SqlByte x, SqlByte y)
{
if (x.IsNull || y.IsNull)
return Null;
int iResult = (int)x._value - (int)y._value;
if ((iResult & s_iBitNotByteMax) != 0)
throw new OverflowException(SQLResource.ArithOverflowMessage);
else
return new SqlByte((byte)iResult);
}
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public static SqlByte operator *(SqlByte x, SqlByte y)
{
if (x.IsNull || y.IsNull)
return Null;
int iResult = (int)x._value * (int)y._value;
if ((iResult & s_iBitNotByteMax) != 0)
throw new OverflowException(SQLResource.ArithOverflowMessage);
else
return new SqlByte((byte)iResult);
}
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public static SqlByte operator /(SqlByte x, SqlByte y)
{
if (x.IsNull || y.IsNull)
return Null;
if (y._value != 0)
{
return new SqlByte((byte)(x._value / y._value));
}
else
throw new DivideByZeroException(SQLResource.DivideByZeroMessage);
}
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public static SqlByte operator %(SqlByte x, SqlByte y)
{
if (x.IsNull || y.IsNull)
return Null;
if (y._value != 0)
{
return new SqlByte((byte)(x._value % y._value));
}
else
throw new DivideByZeroException(SQLResource.DivideByZeroMessage);
}
// Bitwise operators
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public static SqlByte operator &(SqlByte x, SqlByte y)
{
return (x.IsNull || y.IsNull) ? Null : new SqlByte((byte)(x._value & y._value));
}
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public static SqlByte operator |(SqlByte x, SqlByte y)
{
return (x.IsNull || y.IsNull) ? Null : new SqlByte((byte)(x._value | y._value));
}
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public static SqlByte operator ^(SqlByte x, SqlByte y)
{
return (x.IsNull || y.IsNull) ? Null : new SqlByte((byte)(x._value ^ y._value));
}
// Implicit conversions
// Implicit conversion from SqlBoolean to SqlByte
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public static explicit operator SqlByte(SqlBoolean x)
{
return x.IsNull ? Null : new SqlByte((byte)(x.ByteValue));
}
// Explicit conversions
// Explicit conversion from SqlMoney to SqlByte
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public static explicit operator SqlByte(SqlMoney x)
{
return x.IsNull ? Null : new SqlByte(checked((byte)x.ToInt32()));
}
// Explicit conversion from SqlInt16 to SqlByte
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public static explicit operator SqlByte(SqlInt16 x)
{
if (x.IsNull)
return Null;
if (x.Value > (short)Byte.MaxValue || x.Value < (short)Byte.MinValue)
throw new OverflowException(SQLResource.ArithOverflowMessage);
return x.IsNull ? Null : new SqlByte((byte)(x.Value));
}
// Explicit conversion from SqlInt32 to SqlByte
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public static explicit operator SqlByte(SqlInt32 x)
{
if (x.IsNull)
return Null;
if (x.Value > (int)Byte.MaxValue || x.Value < (int)Byte.MinValue)
throw new OverflowException(SQLResource.ArithOverflowMessage);
return x.IsNull ? Null : new SqlByte((byte)(x.Value));
}
// Explicit conversion from SqlInt64 to SqlByte
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public static explicit operator SqlByte(SqlInt64 x)
{
if (x.IsNull)
return Null;
if (x.Value > (long)Byte.MaxValue || x.Value < (long)Byte.MinValue)
throw new OverflowException(SQLResource.ArithOverflowMessage);
return x.IsNull ? Null : new SqlByte((byte)(x.Value));
}
// Explicit conversion from SqlSingle to SqlByte
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public static explicit operator SqlByte(SqlSingle x)
{
if (x.IsNull)
return Null;
if (x.Value > (float)Byte.MaxValue || x.Value < (float)Byte.MinValue)
throw new OverflowException(SQLResource.ArithOverflowMessage);
return x.IsNull ? Null : new SqlByte((byte)(x.Value));
}
// Explicit conversion from SqlDouble to SqlByte
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public static explicit operator SqlByte(SqlDouble x)
{
if (x.IsNull)
return Null;
if (x.Value > (double)Byte.MaxValue || x.Value < (double)Byte.MinValue)
throw new OverflowException(SQLResource.ArithOverflowMessage);
return x.IsNull ? Null : new SqlByte((byte)(x.Value));
}
// Explicit conversion from SqlDecimal to SqlByte
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public static explicit operator SqlByte(SqlDecimal x)
{
return (SqlByte)(SqlInt32)x;
}
// Implicit conversion from SqlString to SqlByte
// Throws FormatException or OverflowException if necessary.
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public static explicit operator SqlByte(SqlString x)
{
return x.IsNull ? Null : new SqlByte(Byte.Parse(x.Value, (IFormatProvider)null));
}
// Overloading comparison operators
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public static SqlBoolean operator ==(SqlByte x, SqlByte y)
{
return (x.IsNull || y.IsNull) ? SqlBoolean.Null : new SqlBoolean(x._value == y._value);
}
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public static SqlBoolean operator !=(SqlByte x, SqlByte y)
{
return !(x == y);
}
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public static SqlBoolean operator <(SqlByte x, SqlByte y)
{
return (x.IsNull || y.IsNull) ? SqlBoolean.Null : new SqlBoolean(x._value < y._value);
}
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public static SqlBoolean operator >(SqlByte x, SqlByte y)
{
return (x.IsNull || y.IsNull) ? SqlBoolean.Null : new SqlBoolean(x._value > y._value);
}
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public static SqlBoolean operator <=(SqlByte x, SqlByte y)
{
return (x.IsNull || y.IsNull) ? SqlBoolean.Null : new SqlBoolean(x._value <= y._value);
}
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public static SqlBoolean operator >=(SqlByte x, SqlByte y)
{
return (x.IsNull || y.IsNull) ? SqlBoolean.Null : new SqlBoolean(x._value >= y._value);
}
//--------------------------------------------------
// Alternative methods for overloaded operators
//--------------------------------------------------
// Alternative method for operator ~
public static SqlByte OnesComplement(SqlByte x)
{
return ~x;
}
// Alternative method for operator +
public static SqlByte Add(SqlByte x, SqlByte y)
{
return x + y;
}
// Alternative method for operator -
public static SqlByte Subtract(SqlByte x, SqlByte y)
{
return x - y;
}
// Alternative method for operator *
public static SqlByte Multiply(SqlByte x, SqlByte y)
{
return x * y;
}
// Alternative method for operator /
public static SqlByte Divide(SqlByte x, SqlByte y)
{
return x / y;
}
// Alternative method for operator %
public static SqlByte Mod(SqlByte x, SqlByte y)
{
return x % y;
}
public static SqlByte Modulus(SqlByte x, SqlByte y)
{
return x % y;
}
// Alternative method for operator &
public static SqlByte BitwiseAnd(SqlByte x, SqlByte y)
{
return x & y;
}
// Alternative method for operator |
public static SqlByte BitwiseOr(SqlByte x, SqlByte y)
{
return x | y;
}
// Alternative method for operator ^
public static SqlByte Xor(SqlByte x, SqlByte y)
{
return x ^ y;
}
// Alternative method for operator ==
public static SqlBoolean Equals(SqlByte x, SqlByte y)
{
return (x == y);
}
// Alternative method for operator !=
public static SqlBoolean NotEquals(SqlByte x, SqlByte y)
{
return (x != y);
}
// Alternative method for operator <
public static SqlBoolean LessThan(SqlByte x, SqlByte y)
{
return (x < y);
}
// Alternative method for operator >
public static SqlBoolean GreaterThan(SqlByte x, SqlByte y)
{
return (x > y);
}
// Alternative method for operator <=
public static SqlBoolean LessThanOrEqual(SqlByte x, SqlByte y)
{
return (x <= y);
}
// Alternative method for operator >=
public static SqlBoolean GreaterThanOrEqual(SqlByte x, SqlByte y)
{
return (x >= y);
}
// Alternative method for conversions.
public SqlBoolean ToSqlBoolean()
{
return (SqlBoolean)this;
}
public SqlDouble ToSqlDouble()
{
return (SqlDouble)this;
}
public SqlInt16 ToSqlInt16()
{
return (SqlInt16)this;
}
public SqlInt32 ToSqlInt32()
{
return (SqlInt32)this;
}
public SqlInt64 ToSqlInt64()
{
return (SqlInt64)this;
}
public SqlMoney ToSqlMoney()
{
return (SqlMoney)this;
}
public SqlDecimal ToSqlDecimal()
{
return (SqlDecimal)this;
}
public SqlSingle ToSqlSingle()
{
return (SqlSingle)this;
}
public SqlString ToSqlString()
{
return (SqlString)this;
}
// IComparable
// Compares this object to another object, returning an integer that
// indicates the relationship.
// Returns a value less than zero if this < object, zero if this = object,
// or a value greater than zero if this > object.
// null is considered to be less than any instance.
// If object is not of same type, this method throws an ArgumentException.
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public int CompareTo(Object value)
{
if (value is SqlByte)
{
SqlByte i = (SqlByte)value;
return CompareTo(i);
}
throw ADP.WrongType(value.GetType(), typeof(SqlByte));
}
public int CompareTo(SqlByte value)
{
// If both Null, consider them equal.
// Otherwise, Null is less than anything.
if (IsNull)
return value.IsNull ? 0 : -1;
else if (value.IsNull)
return 1;
if (this < value) return -1;
if (this > value) return 1;
return 0;
}
// Compares this instance with a specified object
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public override bool Equals(Object value)
{
if (!(value is SqlByte))
{
return false;
}
SqlByte i = (SqlByte)value;
if (i.IsNull || IsNull)
return (i.IsNull && IsNull);
else
return (this == i).Value;
}
// For hashing purpose
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public override int GetHashCode()
{
return IsNull ? 0 : Value.GetHashCode();
}
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public static readonly SqlByte Null = new SqlByte(true);
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public static readonly SqlByte Zero = new SqlByte(0);
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public static readonly SqlByte MinValue = new SqlByte(Byte.MinValue);
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public static readonly SqlByte MaxValue = new SqlByte(Byte.MaxValue);
} // SqlByte
} // namespace System
| |
// Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
using gagvr = Google.Ads.GoogleAds.V9.Resources;
using gax = Google.Api.Gax;
using gaxgrpc = Google.Api.Gax.Grpc;
using gaxgrpccore = Google.Api.Gax.Grpc.GrpcCore;
using proto = Google.Protobuf;
using grpccore = Grpc.Core;
using grpcinter = Grpc.Core.Interceptors;
using sys = System;
using scg = System.Collections.Generic;
using sco = System.Collections.ObjectModel;
using st = System.Threading;
using stt = System.Threading.Tasks;
namespace Google.Ads.GoogleAds.V9.Services
{
/// <summary>Settings for <see cref="DynamicSearchAdsSearchTermViewServiceClient"/> instances.</summary>
public sealed partial class DynamicSearchAdsSearchTermViewServiceSettings : gaxgrpc::ServiceSettingsBase
{
/// <summary>
/// Get a new instance of the default <see cref="DynamicSearchAdsSearchTermViewServiceSettings"/>.
/// </summary>
/// <returns>
/// A new instance of the default <see cref="DynamicSearchAdsSearchTermViewServiceSettings"/>.
/// </returns>
public static DynamicSearchAdsSearchTermViewServiceSettings GetDefault() =>
new DynamicSearchAdsSearchTermViewServiceSettings();
/// <summary>
/// Constructs a new <see cref="DynamicSearchAdsSearchTermViewServiceSettings"/> object with default settings.
/// </summary>
public DynamicSearchAdsSearchTermViewServiceSettings()
{
}
private DynamicSearchAdsSearchTermViewServiceSettings(DynamicSearchAdsSearchTermViewServiceSettings existing) : base(existing)
{
gax::GaxPreconditions.CheckNotNull(existing, nameof(existing));
GetDynamicSearchAdsSearchTermViewSettings = existing.GetDynamicSearchAdsSearchTermViewSettings;
OnCopy(existing);
}
partial void OnCopy(DynamicSearchAdsSearchTermViewServiceSettings existing);
/// <summary>
/// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to
/// <c>DynamicSearchAdsSearchTermViewServiceClient.GetDynamicSearchAdsSearchTermView</c> and
/// <c>DynamicSearchAdsSearchTermViewServiceClient.GetDynamicSearchAdsSearchTermViewAsync</c>.
/// </summary>
/// <remarks>
/// <list type="bullet">
/// <item><description>Initial retry delay: 5000 milliseconds.</description></item>
/// <item><description>Retry delay multiplier: 1.3</description></item>
/// <item><description>Retry maximum delay: 60000 milliseconds.</description></item>
/// <item><description>Maximum attempts: Unlimited</description></item>
/// <item>
/// <description>
/// Retriable status codes: <see cref="grpccore::StatusCode.Unavailable"/>,
/// <see cref="grpccore::StatusCode.DeadlineExceeded"/>.
/// </description>
/// </item>
/// <item><description>Timeout: 3600 seconds.</description></item>
/// </list>
/// </remarks>
public gaxgrpc::CallSettings GetDynamicSearchAdsSearchTermViewSettings { get; set; } = gaxgrpc::CallSettingsExtensions.WithRetry(gaxgrpc::CallSettings.FromExpiration(gax::Expiration.FromTimeout(sys::TimeSpan.FromMilliseconds(3600000))), gaxgrpc::RetrySettings.FromExponentialBackoff(maxAttempts: 2147483647, initialBackoff: sys::TimeSpan.FromMilliseconds(5000), maxBackoff: sys::TimeSpan.FromMilliseconds(60000), backoffMultiplier: 1.3, retryFilter: gaxgrpc::RetrySettings.FilterForStatusCodes(grpccore::StatusCode.Unavailable, grpccore::StatusCode.DeadlineExceeded)));
/// <summary>Creates a deep clone of this object, with all the same property values.</summary>
/// <returns>A deep clone of this <see cref="DynamicSearchAdsSearchTermViewServiceSettings"/> object.</returns>
public DynamicSearchAdsSearchTermViewServiceSettings Clone() =>
new DynamicSearchAdsSearchTermViewServiceSettings(this);
}
/// <summary>
/// Builder class for <see cref="DynamicSearchAdsSearchTermViewServiceClient"/> to provide simple configuration of
/// credentials, endpoint etc.
/// </summary>
internal sealed partial class DynamicSearchAdsSearchTermViewServiceClientBuilder : gaxgrpc::ClientBuilderBase<DynamicSearchAdsSearchTermViewServiceClient>
{
/// <summary>The settings to use for RPCs, or <c>null</c> for the default settings.</summary>
public DynamicSearchAdsSearchTermViewServiceSettings Settings { get; set; }
/// <summary>Creates a new builder with default settings.</summary>
public DynamicSearchAdsSearchTermViewServiceClientBuilder()
{
UseJwtAccessWithScopes = DynamicSearchAdsSearchTermViewServiceClient.UseJwtAccessWithScopes;
}
partial void InterceptBuild(ref DynamicSearchAdsSearchTermViewServiceClient client);
partial void InterceptBuildAsync(st::CancellationToken cancellationToken, ref stt::Task<DynamicSearchAdsSearchTermViewServiceClient> task);
/// <summary>Builds the resulting client.</summary>
public override DynamicSearchAdsSearchTermViewServiceClient Build()
{
DynamicSearchAdsSearchTermViewServiceClient client = null;
InterceptBuild(ref client);
return client ?? BuildImpl();
}
/// <summary>Builds the resulting client asynchronously.</summary>
public override stt::Task<DynamicSearchAdsSearchTermViewServiceClient> BuildAsync(st::CancellationToken cancellationToken = default)
{
stt::Task<DynamicSearchAdsSearchTermViewServiceClient> task = null;
InterceptBuildAsync(cancellationToken, ref task);
return task ?? BuildAsyncImpl(cancellationToken);
}
private DynamicSearchAdsSearchTermViewServiceClient BuildImpl()
{
Validate();
grpccore::CallInvoker callInvoker = CreateCallInvoker();
return DynamicSearchAdsSearchTermViewServiceClient.Create(callInvoker, Settings);
}
private async stt::Task<DynamicSearchAdsSearchTermViewServiceClient> BuildAsyncImpl(st::CancellationToken cancellationToken)
{
Validate();
grpccore::CallInvoker callInvoker = await CreateCallInvokerAsync(cancellationToken).ConfigureAwait(false);
return DynamicSearchAdsSearchTermViewServiceClient.Create(callInvoker, Settings);
}
/// <summary>Returns the endpoint for this builder type, used if no endpoint is otherwise specified.</summary>
protected override string GetDefaultEndpoint() => DynamicSearchAdsSearchTermViewServiceClient.DefaultEndpoint;
/// <summary>
/// Returns the default scopes for this builder type, used if no scopes are otherwise specified.
/// </summary>
protected override scg::IReadOnlyList<string> GetDefaultScopes() =>
DynamicSearchAdsSearchTermViewServiceClient.DefaultScopes;
/// <summary>Returns the channel pool to use when no other options are specified.</summary>
protected override gaxgrpc::ChannelPool GetChannelPool() => DynamicSearchAdsSearchTermViewServiceClient.ChannelPool;
/// <summary>Returns the default <see cref="gaxgrpc::GrpcAdapter"/>to use if not otherwise specified.</summary>
protected override gaxgrpc::GrpcAdapter DefaultGrpcAdapter => gaxgrpccore::GrpcCoreAdapter.Instance;
}
/// <summary>DynamicSearchAdsSearchTermViewService client wrapper, for convenient use.</summary>
/// <remarks>
/// Service to fetch dynamic search ads views.
/// </remarks>
public abstract partial class DynamicSearchAdsSearchTermViewServiceClient
{
/// <summary>
/// The default endpoint for the DynamicSearchAdsSearchTermViewService service, which is a host of
/// "googleads.googleapis.com" and a port of 443.
/// </summary>
public static string DefaultEndpoint { get; } = "googleads.googleapis.com:443";
/// <summary>The default DynamicSearchAdsSearchTermViewService scopes.</summary>
/// <remarks>
/// The default DynamicSearchAdsSearchTermViewService scopes are:
/// <list type="bullet"><item><description>https://www.googleapis.com/auth/adwords</description></item></list>
/// </remarks>
public static scg::IReadOnlyList<string> DefaultScopes { get; } = new sco::ReadOnlyCollection<string>(new string[]
{
"https://www.googleapis.com/auth/adwords",
});
internal static gaxgrpc::ChannelPool ChannelPool { get; } = new gaxgrpc::ChannelPool(DefaultScopes, UseJwtAccessWithScopes);
internal static bool UseJwtAccessWithScopes
{
get
{
bool useJwtAccessWithScopes = true;
MaybeUseJwtAccessWithScopes(ref useJwtAccessWithScopes);
return useJwtAccessWithScopes;
}
}
static partial void MaybeUseJwtAccessWithScopes(ref bool useJwtAccessWithScopes);
/// <summary>
/// Asynchronously creates a <see cref="DynamicSearchAdsSearchTermViewServiceClient"/> using the default
/// credentials, endpoint and settings. To specify custom credentials or other settings, use
/// <see cref="DynamicSearchAdsSearchTermViewServiceClientBuilder"/>.
/// </summary>
/// <param name="cancellationToken">
/// The <see cref="st::CancellationToken"/> to use while creating the client.
/// </param>
/// <returns>
/// The task representing the created <see cref="DynamicSearchAdsSearchTermViewServiceClient"/>.
/// </returns>
public static stt::Task<DynamicSearchAdsSearchTermViewServiceClient> CreateAsync(st::CancellationToken cancellationToken = default) =>
new DynamicSearchAdsSearchTermViewServiceClientBuilder().BuildAsync(cancellationToken);
/// <summary>
/// Synchronously creates a <see cref="DynamicSearchAdsSearchTermViewServiceClient"/> using the default
/// credentials, endpoint and settings. To specify custom credentials or other settings, use
/// <see cref="DynamicSearchAdsSearchTermViewServiceClientBuilder"/>.
/// </summary>
/// <returns>The created <see cref="DynamicSearchAdsSearchTermViewServiceClient"/>.</returns>
public static DynamicSearchAdsSearchTermViewServiceClient Create() =>
new DynamicSearchAdsSearchTermViewServiceClientBuilder().Build();
/// <summary>
/// Creates a <see cref="DynamicSearchAdsSearchTermViewServiceClient"/> which uses the specified call invoker
/// for remote operations.
/// </summary>
/// <param name="callInvoker">
/// The <see cref="grpccore::CallInvoker"/> for remote operations. Must not be null.
/// </param>
/// <param name="settings">Optional <see cref="DynamicSearchAdsSearchTermViewServiceSettings"/>.</param>
/// <returns>The created <see cref="DynamicSearchAdsSearchTermViewServiceClient"/>.</returns>
internal static DynamicSearchAdsSearchTermViewServiceClient Create(grpccore::CallInvoker callInvoker, DynamicSearchAdsSearchTermViewServiceSettings settings = null)
{
gax::GaxPreconditions.CheckNotNull(callInvoker, nameof(callInvoker));
grpcinter::Interceptor interceptor = settings?.Interceptor;
if (interceptor != null)
{
callInvoker = grpcinter::CallInvokerExtensions.Intercept(callInvoker, interceptor);
}
DynamicSearchAdsSearchTermViewService.DynamicSearchAdsSearchTermViewServiceClient grpcClient = new DynamicSearchAdsSearchTermViewService.DynamicSearchAdsSearchTermViewServiceClient(callInvoker);
return new DynamicSearchAdsSearchTermViewServiceClientImpl(grpcClient, settings);
}
/// <summary>
/// Shuts down any channels automatically created by <see cref="Create()"/> and
/// <see cref="CreateAsync(st::CancellationToken)"/>. Channels which weren't automatically created are not
/// affected.
/// </summary>
/// <remarks>
/// After calling this method, further calls to <see cref="Create()"/> and
/// <see cref="CreateAsync(st::CancellationToken)"/> will create new channels, which could in turn be shut down
/// by another call to this method.
/// </remarks>
/// <returns>A task representing the asynchronous shutdown operation.</returns>
public static stt::Task ShutdownDefaultChannelsAsync() => ChannelPool.ShutdownChannelsAsync();
/// <summary>The underlying gRPC DynamicSearchAdsSearchTermViewService client</summary>
public virtual DynamicSearchAdsSearchTermViewService.DynamicSearchAdsSearchTermViewServiceClient GrpcClient => throw new sys::NotImplementedException();
/// <summary>
/// Returns the requested dynamic search ads search term view in full detail.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual gagvr::DynamicSearchAdsSearchTermView GetDynamicSearchAdsSearchTermView(GetDynamicSearchAdsSearchTermViewRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Returns the requested dynamic search ads search term view in full detail.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<gagvr::DynamicSearchAdsSearchTermView> GetDynamicSearchAdsSearchTermViewAsync(GetDynamicSearchAdsSearchTermViewRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Returns the requested dynamic search ads search term view in full detail.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<gagvr::DynamicSearchAdsSearchTermView> GetDynamicSearchAdsSearchTermViewAsync(GetDynamicSearchAdsSearchTermViewRequest request, st::CancellationToken cancellationToken) =>
GetDynamicSearchAdsSearchTermViewAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
/// <summary>
/// Returns the requested dynamic search ads search term view in full detail.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="resourceName">
/// Required. The resource name of the dynamic search ads search term view to fetch.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual gagvr::DynamicSearchAdsSearchTermView GetDynamicSearchAdsSearchTermView(string resourceName, gaxgrpc::CallSettings callSettings = null) =>
GetDynamicSearchAdsSearchTermView(new GetDynamicSearchAdsSearchTermViewRequest
{
ResourceName = gax::GaxPreconditions.CheckNotNullOrEmpty(resourceName, nameof(resourceName)),
}, callSettings);
/// <summary>
/// Returns the requested dynamic search ads search term view in full detail.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="resourceName">
/// Required. The resource name of the dynamic search ads search term view to fetch.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<gagvr::DynamicSearchAdsSearchTermView> GetDynamicSearchAdsSearchTermViewAsync(string resourceName, gaxgrpc::CallSettings callSettings = null) =>
GetDynamicSearchAdsSearchTermViewAsync(new GetDynamicSearchAdsSearchTermViewRequest
{
ResourceName = gax::GaxPreconditions.CheckNotNullOrEmpty(resourceName, nameof(resourceName)),
}, callSettings);
/// <summary>
/// Returns the requested dynamic search ads search term view in full detail.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="resourceName">
/// Required. The resource name of the dynamic search ads search term view to fetch.
/// </param>
/// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<gagvr::DynamicSearchAdsSearchTermView> GetDynamicSearchAdsSearchTermViewAsync(string resourceName, st::CancellationToken cancellationToken) =>
GetDynamicSearchAdsSearchTermViewAsync(resourceName, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
/// <summary>
/// Returns the requested dynamic search ads search term view in full detail.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="resourceName">
/// Required. The resource name of the dynamic search ads search term view to fetch.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual gagvr::DynamicSearchAdsSearchTermView GetDynamicSearchAdsSearchTermView(gagvr::DynamicSearchAdsSearchTermViewName resourceName, gaxgrpc::CallSettings callSettings = null) =>
GetDynamicSearchAdsSearchTermView(new GetDynamicSearchAdsSearchTermViewRequest
{
ResourceNameAsDynamicSearchAdsSearchTermViewName = gax::GaxPreconditions.CheckNotNull(resourceName, nameof(resourceName)),
}, callSettings);
/// <summary>
/// Returns the requested dynamic search ads search term view in full detail.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="resourceName">
/// Required. The resource name of the dynamic search ads search term view to fetch.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<gagvr::DynamicSearchAdsSearchTermView> GetDynamicSearchAdsSearchTermViewAsync(gagvr::DynamicSearchAdsSearchTermViewName resourceName, gaxgrpc::CallSettings callSettings = null) =>
GetDynamicSearchAdsSearchTermViewAsync(new GetDynamicSearchAdsSearchTermViewRequest
{
ResourceNameAsDynamicSearchAdsSearchTermViewName = gax::GaxPreconditions.CheckNotNull(resourceName, nameof(resourceName)),
}, callSettings);
/// <summary>
/// Returns the requested dynamic search ads search term view in full detail.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="resourceName">
/// Required. The resource name of the dynamic search ads search term view to fetch.
/// </param>
/// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<gagvr::DynamicSearchAdsSearchTermView> GetDynamicSearchAdsSearchTermViewAsync(gagvr::DynamicSearchAdsSearchTermViewName resourceName, st::CancellationToken cancellationToken) =>
GetDynamicSearchAdsSearchTermViewAsync(resourceName, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
}
/// <summary>DynamicSearchAdsSearchTermViewService client wrapper implementation, for convenient use.</summary>
/// <remarks>
/// Service to fetch dynamic search ads views.
/// </remarks>
public sealed partial class DynamicSearchAdsSearchTermViewServiceClientImpl : DynamicSearchAdsSearchTermViewServiceClient
{
private readonly gaxgrpc::ApiCall<GetDynamicSearchAdsSearchTermViewRequest, gagvr::DynamicSearchAdsSearchTermView> _callGetDynamicSearchAdsSearchTermView;
/// <summary>
/// Constructs a client wrapper for the DynamicSearchAdsSearchTermViewService service, with the specified gRPC
/// client and settings.
/// </summary>
/// <param name="grpcClient">The underlying gRPC client.</param>
/// <param name="settings">
/// The base <see cref="DynamicSearchAdsSearchTermViewServiceSettings"/> used within this client.
/// </param>
public DynamicSearchAdsSearchTermViewServiceClientImpl(DynamicSearchAdsSearchTermViewService.DynamicSearchAdsSearchTermViewServiceClient grpcClient, DynamicSearchAdsSearchTermViewServiceSettings settings)
{
GrpcClient = grpcClient;
DynamicSearchAdsSearchTermViewServiceSettings effectiveSettings = settings ?? DynamicSearchAdsSearchTermViewServiceSettings.GetDefault();
gaxgrpc::ClientHelper clientHelper = new gaxgrpc::ClientHelper(effectiveSettings);
_callGetDynamicSearchAdsSearchTermView = clientHelper.BuildApiCall<GetDynamicSearchAdsSearchTermViewRequest, gagvr::DynamicSearchAdsSearchTermView>(grpcClient.GetDynamicSearchAdsSearchTermViewAsync, grpcClient.GetDynamicSearchAdsSearchTermView, effectiveSettings.GetDynamicSearchAdsSearchTermViewSettings).WithGoogleRequestParam("resource_name", request => request.ResourceName);
Modify_ApiCall(ref _callGetDynamicSearchAdsSearchTermView);
Modify_GetDynamicSearchAdsSearchTermViewApiCall(ref _callGetDynamicSearchAdsSearchTermView);
OnConstruction(grpcClient, effectiveSettings, clientHelper);
}
partial void Modify_ApiCall<TRequest, TResponse>(ref gaxgrpc::ApiCall<TRequest, TResponse> call) where TRequest : class, proto::IMessage<TRequest> where TResponse : class, proto::IMessage<TResponse>;
partial void Modify_GetDynamicSearchAdsSearchTermViewApiCall(ref gaxgrpc::ApiCall<GetDynamicSearchAdsSearchTermViewRequest, gagvr::DynamicSearchAdsSearchTermView> call);
partial void OnConstruction(DynamicSearchAdsSearchTermViewService.DynamicSearchAdsSearchTermViewServiceClient grpcClient, DynamicSearchAdsSearchTermViewServiceSettings effectiveSettings, gaxgrpc::ClientHelper clientHelper);
/// <summary>The underlying gRPC DynamicSearchAdsSearchTermViewService client</summary>
public override DynamicSearchAdsSearchTermViewService.DynamicSearchAdsSearchTermViewServiceClient GrpcClient { get; }
partial void Modify_GetDynamicSearchAdsSearchTermViewRequest(ref GetDynamicSearchAdsSearchTermViewRequest request, ref gaxgrpc::CallSettings settings);
/// <summary>
/// Returns the requested dynamic search ads search term view in full detail.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public override gagvr::DynamicSearchAdsSearchTermView GetDynamicSearchAdsSearchTermView(GetDynamicSearchAdsSearchTermViewRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_GetDynamicSearchAdsSearchTermViewRequest(ref request, ref callSettings);
return _callGetDynamicSearchAdsSearchTermView.Sync(request, callSettings);
}
/// <summary>
/// Returns the requested dynamic search ads search term view in full detail.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public override stt::Task<gagvr::DynamicSearchAdsSearchTermView> GetDynamicSearchAdsSearchTermViewAsync(GetDynamicSearchAdsSearchTermViewRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_GetDynamicSearchAdsSearchTermViewRequest(ref request, ref callSettings);
return _callGetDynamicSearchAdsSearchTermView.Async(request, callSettings);
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using Microsoft.PowerShell.Commands;
using System.Collections;
using System.Collections.ObjectModel;
using System.IO;
using System.Linq;
using System.Management.Automation.Internal;
using System.Text;
namespace System.Management.Automation
{
using Language;
/// <summary>
/// The parameter binder for native commands.
/// </summary>
internal class NativeCommandParameterBinder : ParameterBinderBase
{
#region ctor
/// <summary>
/// Constructs a NativeCommandParameterBinder.
/// </summary>
/// <param name="command">
/// The NativeCommand to bind to.
/// </param>
/// <exception cref="ArgumentNullException">
/// <paramref name="command"/>.Context is null
/// </exception>
internal NativeCommandParameterBinder(
NativeCommand command) : base(command.MyInvocation, command.Context, command)
{
_nativeCommand = command;
}
#endregion ctor
#region internal members
#region Parameter binding
/// <summary>
/// Binds a parameter for a native command (application).
/// </summary>
/// <param name="name">
/// The name of the parameter to bind the value to. For applications
/// this just becomes another parameter...
/// </param>
/// <param name="value">
/// The value to bind to the parameter. It should be assumed by
/// derived classes that the proper type coercion has already taken
/// place and that any prerequisite metadata has been satisfied.
/// </param>
/// <param name="parameterMetadata"></param>
internal override void BindParameter(string name, object value, CompiledCommandParameter parameterMetadata)
{
Diagnostics.Assert(false, "Unreachable code");
throw new NotSupportedException();
}
internal override object GetDefaultParameterValue(string name)
{
return null;
}
internal void BindParameters(Collection<CommandParameterInternal> parameters)
{
bool sawVerbatimArgumentMarker = false;
bool first = true;
foreach (CommandParameterInternal parameter in parameters)
{
if (!first)
{
_arguments.Append(' ');
}
first = false;
if (parameter.ParameterNameSpecified)
{
Diagnostics.Assert(parameter.ParameterText.IndexOf(' ') == -1, "Parameters cannot have whitespace");
PossiblyGlobArg(parameter.ParameterText, usedQuotes: false);
if (parameter.SpaceAfterParameter)
{
_arguments.Append(' ');
}
}
if (parameter.ArgumentSpecified)
{
// If this is the verbatim argument marker, we don't pass it on to the native command.
// We do need to remember it though - we'll expand environment variables in subsequent args.
object argValue = parameter.ArgumentValue;
if (string.Equals("--%", argValue as string, StringComparison.OrdinalIgnoreCase))
{
sawVerbatimArgumentMarker = true;
continue;
}
if (argValue != AutomationNull.Value && argValue != UnboundParameter.Value)
{
// ArrayLiteralAst is used to reconstruct the correct argument, e.g.
// windbg -k com:port=\\devbox\pipe\debug,pipe,resets=0,reconnect
// The parser produced an array of strings but marked the parameter so we
// can properly reconstruct the correct command line.
bool usedQuotes = false;
ArrayLiteralAst arrayLiteralAst = null;
switch (parameter?.ArgumentAst)
{
case StringConstantExpressionAst sce:
usedQuotes = sce.StringConstantType != StringConstantType.BareWord;
break;
case ExpandableStringExpressionAst ese:
usedQuotes = ese.StringConstantType != StringConstantType.BareWord;
break;
case ArrayLiteralAst ala:
arrayLiteralAst = ala;
break;
}
appendOneNativeArgument(Context, argValue,
arrayLiteralAst, sawVerbatimArgumentMarker, usedQuotes);
}
}
}
}
#endregion Parameter binding
/// <summary>
/// Gets the command arguments in string form.
/// </summary>
internal string Arguments
{
get
{
return _arguments.ToString();
}
}
private readonly StringBuilder _arguments = new StringBuilder();
#endregion internal members
#region private members
/// <summary>
/// Stringize a non-IEnum argument to a native command, adding quotes
/// and trailing spaces as appropriate. An array gets added as multiple arguments
/// each of which will be stringized.
/// </summary>
/// <param name="context">Execution context instance.</param>
/// <param name="obj">The object to append.</param>
/// <param name="argArrayAst">If the argument was an array literal, the Ast, otherwise null.</param>
/// <param name="sawVerbatimArgumentMarker">True if the argument occurs after --%.</param>
/// <param name="usedQuotes">True if the argument was a quoted string (single or double).</param>
private void appendOneNativeArgument(ExecutionContext context, object obj, ArrayLiteralAst argArrayAst, bool sawVerbatimArgumentMarker, bool usedQuotes)
{
IEnumerator list = LanguagePrimitives.GetEnumerator(obj);
Diagnostics.Assert(argArrayAst == null
|| obj is object[] && ((object[])obj).Length == argArrayAst.Elements.Count,
"array argument and ArrayLiteralAst differ in number of elements");
int currentElement = -1;
string separator = string.Empty;
do
{
string arg;
if (list == null)
{
arg = PSObject.ToStringParser(context, obj);
}
else
{
if (!ParserOps.MoveNext(context, null, list))
{
break;
}
arg = PSObject.ToStringParser(context, ParserOps.Current(null, list));
currentElement += 1;
if (currentElement != 0)
{
separator = GetEnumerableArgSeparator(argArrayAst, currentElement);
}
}
if (!string.IsNullOrEmpty(arg))
{
_arguments.Append(separator);
if (sawVerbatimArgumentMarker)
{
arg = Environment.ExpandEnvironmentVariables(arg);
_arguments.Append(arg);
}
else
{
// We need to add quotes if the argument has unquoted spaces. The
// quotes could appear anywhere inside the string, not just at the start,
// e.g.
// $a = 'a"b c"d'
// echoargs $a 'a"b c"d' a"b c"d
//
// The above should see 3 identical arguments in argv (the command line will
// actually have quotes in different places, but the Win32 command line=>argv parser
// erases those differences.
//
// We need to check quotes that the win32 argument parser checks which is currently
// just the normal double quotes, no other special quotes. Also note that mismatched
// quotes are supported
if (NeedQuotes(arg))
{
_arguments.Append('"');
// need to escape all trailing backslashes so the native command receives it correctly
// according to http://www.daviddeley.com/autohotkey/parameters/parameters.htm#WINCRULESDOC
_arguments.Append(arg);
for (int i = arg.Length-1; i >= 0 && arg[i] == '\\'; i--)
{
_arguments.Append('\\');
}
_arguments.Append('"');
}
else
{
PossiblyGlobArg(arg, usedQuotes);
}
}
}
} while (list != null);
}
/// <summary>
/// On Windows, just append <paramref name="arg"/>.
/// On Unix, do globbing as appropriate, otherwise just append <paramref name="arg"/>.
/// </summary>
/// <param name="arg">The argument that possibly needs expansion.</param>
/// <param name="usedQuotes">True if the argument was a quoted string (single or double).</param>
private void PossiblyGlobArg(string arg, bool usedQuotes)
{
var argExpanded = false;
#if UNIX
// On UNIX systems, we expand arguments containing wildcard expressions against
// the file system just like bash, etc.
if (!usedQuotes && WildcardPattern.ContainsWildcardCharacters(arg))
{
// See if the current working directory is a filesystem provider location
// We won't do the expansion if it isn't since native commands can only access the file system.
var cwdinfo = Context.EngineSessionState.CurrentLocation;
// If it's a filesystem location then expand the wildcards
if (cwdinfo.Provider.Name.Equals(FileSystemProvider.ProviderName, StringComparison.OrdinalIgnoreCase))
{
// On UNIX, paths starting with ~ or absolute paths are not normalized
bool normalizePath = arg.Length == 0 || !(arg[0] == '~' || arg[0] == '/');
// See if there are any matching paths otherwise just add the pattern as the argument
Collection<PSObject> paths = null;
try
{
paths = Context.EngineSessionState.InvokeProvider.ChildItem.Get(arg, false);
}
catch
{
// Fallthrough will append the pattern unchanged.
}
// Expand paths, but only from the file system.
if (paths?.Count > 0 && paths.All(p => p.BaseObject is FileSystemInfo))
{
var sep = string.Empty;
foreach (var path in paths)
{
_arguments.Append(sep);
sep = " ";
var expandedPath = (path.BaseObject as FileSystemInfo).FullName;
if (normalizePath)
{
expandedPath =
Context.SessionState.Path.NormalizeRelativePath(expandedPath, cwdinfo.ProviderPath);
}
// If the path contains spaces, then add quotes around it.
if (NeedQuotes(expandedPath))
{
_arguments.Append("\"");
_arguments.Append(expandedPath);
_arguments.Append("\"");
}
else
{
_arguments.Append(expandedPath);
}
argExpanded = true;
}
}
}
}
else if (!usedQuotes)
{
// Even if there are no wildcards, we still need to possibly
// expand ~ into the filesystem provider home directory path
ProviderInfo fileSystemProvider = Context.EngineSessionState.GetSingleProvider(FileSystemProvider.ProviderName);
string home = fileSystemProvider.Home;
if (string.Equals(arg, "~"))
{
_arguments.Append(home);
argExpanded = true;
}
else if (arg.StartsWith("~/", StringComparison.OrdinalIgnoreCase))
{
var replacementString = home + arg.Substring(1);
_arguments.Append(replacementString);
argExpanded = true;
}
}
#endif // UNIX
if (!argExpanded)
{
_arguments.Append(arg);
}
}
/// <summary>
/// Check to see if the string contains spaces and therefore must be quoted.
/// </summary>
/// <param name="stringToCheck">The string to check for spaces.</param>
internal static bool NeedQuotes(string stringToCheck)
{
bool needQuotes = false, followingBackslash = false;
int quoteCount = 0;
for (int i = 0; i < stringToCheck.Length; i++)
{
if (stringToCheck[i] == '"' && !followingBackslash)
{
quoteCount += 1;
}
else if (char.IsWhiteSpace(stringToCheck[i]) && (quoteCount % 2 == 0))
{
needQuotes = true;
}
followingBackslash = stringToCheck[i] == '\\';
}
return needQuotes;
}
private static string GetEnumerableArgSeparator(ArrayLiteralAst arrayLiteralAst, int index)
{
if (arrayLiteralAst == null) return " ";
// index points to the *next* element, so we're looking for space between
// it and the previous element.
var next = arrayLiteralAst.Elements[index];
var prev = arrayLiteralAst.Elements[index - 1];
var arrayExtent = arrayLiteralAst.Extent;
var afterPrev = prev.Extent.EndOffset;
var beforeNext = next.Extent.StartOffset - 1;
if (afterPrev == beforeNext) return ",";
var arrayText = arrayExtent.Text;
afterPrev -= arrayExtent.StartOffset;
beforeNext -= arrayExtent.StartOffset;
if (arrayText[afterPrev] == ',') return ", ";
if (arrayText[beforeNext] == ',') return " ,";
return " , ";
}
/// <summary>
/// The native command to bind to.
/// </summary>
private NativeCommand _nativeCommand;
#endregion private members
}
}
| |
/*
* Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
/*
* Do not modify this file. This file is generated from the rds-2014-10-31.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
using System.IO;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
namespace Amazon.RDS.Model
{
/// <summary>
/// Contains the result of a successful invocation of the following actions:
///
/// <ul> <li> <a>CreateDBCluster</a> </li> <li> <a>DeleteDBCluster</a> </li> <li> <a>FailoverDBCluster</a>
/// </li> <li> <a>ModifyDBCluster</a> </li> <li> <a>RestoreDBClusterFromSnapshot</a> </li>
/// </ul>
/// <para>
/// This data type is used as a response element in the <a>DescribeDBClusters</a> action.
/// </para>
/// </summary>
public partial class DBCluster
{
private int? _allocatedStorage;
private List<string> _availabilityZones = new List<string>();
private int? _backupRetentionPeriod;
private string _characterSetName;
private string _databaseName;
private string _dbClusterIdentifier;
private List<DBClusterMember> _dbClusterMembers = new List<DBClusterMember>();
private List<DBClusterOptionGroupStatus> _dbClusterOptionGroupMemberships = new List<DBClusterOptionGroupStatus>();
private string _dbClusterParameterGroup;
private string _dbSubnetGroup;
private DateTime? _earliestRestorableTime;
private string _endpoint;
private string _engine;
private string _engineVersion;
private DateTime? _latestRestorableTime;
private string _masterUsername;
private string _percentProgress;
private int? _port;
private string _preferredBackupWindow;
private string _preferredMaintenanceWindow;
private string _status;
private List<VpcSecurityGroupMembership> _vpcSecurityGroups = new List<VpcSecurityGroupMembership>();
/// <summary>
/// Gets and sets the property AllocatedStorage.
/// <para>
/// Specifies the allocated storage size in gigabytes (GB).
/// </para>
/// </summary>
public int AllocatedStorage
{
get { return this._allocatedStorage.GetValueOrDefault(); }
set { this._allocatedStorage = value; }
}
// Check to see if AllocatedStorage property is set
internal bool IsSetAllocatedStorage()
{
return this._allocatedStorage.HasValue;
}
/// <summary>
/// Gets and sets the property AvailabilityZones.
/// <para>
/// Provides the list of EC2 Availability Zones that instances in the DB cluster can be
/// created in.
/// </para>
/// </summary>
public List<string> AvailabilityZones
{
get { return this._availabilityZones; }
set { this._availabilityZones = value; }
}
// Check to see if AvailabilityZones property is set
internal bool IsSetAvailabilityZones()
{
return this._availabilityZones != null && this._availabilityZones.Count > 0;
}
/// <summary>
/// Gets and sets the property BackupRetentionPeriod.
/// <para>
/// Specifies the number of days for which automatic DB snapshots are retained.
/// </para>
/// </summary>
public int BackupRetentionPeriod
{
get { return this._backupRetentionPeriod.GetValueOrDefault(); }
set { this._backupRetentionPeriod = value; }
}
// Check to see if BackupRetentionPeriod property is set
internal bool IsSetBackupRetentionPeriod()
{
return this._backupRetentionPeriod.HasValue;
}
/// <summary>
/// Gets and sets the property CharacterSetName.
/// <para>
/// If present, specifies the name of the character set that this cluster is associated
/// with.
/// </para>
/// </summary>
public string CharacterSetName
{
get { return this._characterSetName; }
set { this._characterSetName = value; }
}
// Check to see if CharacterSetName property is set
internal bool IsSetCharacterSetName()
{
return this._characterSetName != null;
}
/// <summary>
/// Gets and sets the property DatabaseName.
/// <para>
/// Contains the name of the initial database of this DB cluster that was provided at
/// create time, if one was specified when the DB cluster was created. This same name
/// is returned for the life of the DB cluster.
/// </para>
/// </summary>
public string DatabaseName
{
get { return this._databaseName; }
set { this._databaseName = value; }
}
// Check to see if DatabaseName property is set
internal bool IsSetDatabaseName()
{
return this._databaseName != null;
}
/// <summary>
/// Gets and sets the property DBClusterIdentifier.
/// <para>
/// Contains a user-supplied DB cluster identifier. This identifier is the unique key
/// that identifies a DB cluster.
/// </para>
/// </summary>
public string DBClusterIdentifier
{
get { return this._dbClusterIdentifier; }
set { this._dbClusterIdentifier = value; }
}
// Check to see if DBClusterIdentifier property is set
internal bool IsSetDBClusterIdentifier()
{
return this._dbClusterIdentifier != null;
}
/// <summary>
/// Gets and sets the property DBClusterMembers.
/// <para>
/// Provides the list of instances that make up the DB cluster.
/// </para>
/// </summary>
public List<DBClusterMember> DBClusterMembers
{
get { return this._dbClusterMembers; }
set { this._dbClusterMembers = value; }
}
// Check to see if DBClusterMembers property is set
internal bool IsSetDBClusterMembers()
{
return this._dbClusterMembers != null && this._dbClusterMembers.Count > 0;
}
/// <summary>
/// Gets and sets the property DBClusterOptionGroupMemberships.
/// <para>
/// Provides the list of option group memberships for this DB cluster.
/// </para>
/// </summary>
public List<DBClusterOptionGroupStatus> DBClusterOptionGroupMemberships
{
get { return this._dbClusterOptionGroupMemberships; }
set { this._dbClusterOptionGroupMemberships = value; }
}
// Check to see if DBClusterOptionGroupMemberships property is set
internal bool IsSetDBClusterOptionGroupMemberships()
{
return this._dbClusterOptionGroupMemberships != null && this._dbClusterOptionGroupMemberships.Count > 0;
}
/// <summary>
/// Gets and sets the property DBClusterParameterGroup.
/// <para>
/// Specifies the name of the DB cluster parameter group for the DB cluster.
/// </para>
/// </summary>
public string DBClusterParameterGroup
{
get { return this._dbClusterParameterGroup; }
set { this._dbClusterParameterGroup = value; }
}
// Check to see if DBClusterParameterGroup property is set
internal bool IsSetDBClusterParameterGroup()
{
return this._dbClusterParameterGroup != null;
}
/// <summary>
/// Gets and sets the property DBSubnetGroup.
/// <para>
/// Specifies information on the subnet group associated with the DB cluster, including
/// the name, description, and subnets in the subnet group.
/// </para>
/// </summary>
public string DBSubnetGroup
{
get { return this._dbSubnetGroup; }
set { this._dbSubnetGroup = value; }
}
// Check to see if DBSubnetGroup property is set
internal bool IsSetDBSubnetGroup()
{
return this._dbSubnetGroup != null;
}
/// <summary>
/// Gets and sets the property EarliestRestorableTime.
/// <para>
/// Specifies the earliest time to which a database can be restored with point-in-time
/// restore.
/// </para>
/// </summary>
public DateTime EarliestRestorableTime
{
get { return this._earliestRestorableTime.GetValueOrDefault(); }
set { this._earliestRestorableTime = value; }
}
// Check to see if EarliestRestorableTime property is set
internal bool IsSetEarliestRestorableTime()
{
return this._earliestRestorableTime.HasValue;
}
/// <summary>
/// Gets and sets the property Endpoint.
/// <para>
/// Specifies the connection endpoint for the primary instance of the DB cluster.
/// </para>
/// </summary>
public string Endpoint
{
get { return this._endpoint; }
set { this._endpoint = value; }
}
// Check to see if Endpoint property is set
internal bool IsSetEndpoint()
{
return this._endpoint != null;
}
/// <summary>
/// Gets and sets the property Engine.
/// <para>
/// Provides the name of the database engine to be used for this DB cluster.
/// </para>
/// </summary>
public string Engine
{
get { return this._engine; }
set { this._engine = value; }
}
// Check to see if Engine property is set
internal bool IsSetEngine()
{
return this._engine != null;
}
/// <summary>
/// Gets and sets the property EngineVersion.
/// <para>
/// Indicates the database engine version.
/// </para>
/// </summary>
public string EngineVersion
{
get { return this._engineVersion; }
set { this._engineVersion = value; }
}
// Check to see if EngineVersion property is set
internal bool IsSetEngineVersion()
{
return this._engineVersion != null;
}
/// <summary>
/// Gets and sets the property LatestRestorableTime.
/// <para>
/// Specifies the latest time to which a database can be restored with point-in-time restore.
///
/// </para>
/// </summary>
public DateTime LatestRestorableTime
{
get { return this._latestRestorableTime.GetValueOrDefault(); }
set { this._latestRestorableTime = value; }
}
// Check to see if LatestRestorableTime property is set
internal bool IsSetLatestRestorableTime()
{
return this._latestRestorableTime.HasValue;
}
/// <summary>
/// Gets and sets the property MasterUsername.
/// <para>
/// Contains the master username for the DB cluster.
/// </para>
/// </summary>
public string MasterUsername
{
get { return this._masterUsername; }
set { this._masterUsername = value; }
}
// Check to see if MasterUsername property is set
internal bool IsSetMasterUsername()
{
return this._masterUsername != null;
}
/// <summary>
/// Gets and sets the property PercentProgress.
/// <para>
/// Specifies the progress of the operation as a percentage.
/// </para>
/// </summary>
public string PercentProgress
{
get { return this._percentProgress; }
set { this._percentProgress = value; }
}
// Check to see if PercentProgress property is set
internal bool IsSetPercentProgress()
{
return this._percentProgress != null;
}
/// <summary>
/// Gets and sets the property Port.
/// <para>
/// Specifies the port that the database engine is listening on.
/// </para>
/// </summary>
public int Port
{
get { return this._port.GetValueOrDefault(); }
set { this._port = value; }
}
// Check to see if Port property is set
internal bool IsSetPort()
{
return this._port.HasValue;
}
/// <summary>
/// Gets and sets the property PreferredBackupWindow.
/// <para>
/// Specifies the daily time range during which automated backups are created if automated
/// backups are enabled, as determined by the <code>BackupRetentionPeriod</code>.
/// </para>
/// </summary>
public string PreferredBackupWindow
{
get { return this._preferredBackupWindow; }
set { this._preferredBackupWindow = value; }
}
// Check to see if PreferredBackupWindow property is set
internal bool IsSetPreferredBackupWindow()
{
return this._preferredBackupWindow != null;
}
/// <summary>
/// Gets and sets the property PreferredMaintenanceWindow.
/// <para>
/// Specifies the weekly time range during which system maintenance can occur, in Universal
/// Coordinated Time (UTC).
/// </para>
/// </summary>
public string PreferredMaintenanceWindow
{
get { return this._preferredMaintenanceWindow; }
set { this._preferredMaintenanceWindow = value; }
}
// Check to see if PreferredMaintenanceWindow property is set
internal bool IsSetPreferredMaintenanceWindow()
{
return this._preferredMaintenanceWindow != null;
}
/// <summary>
/// Gets and sets the property Status.
/// <para>
/// Specifies the current state of this DB cluster.
/// </para>
/// </summary>
public string Status
{
get { return this._status; }
set { this._status = value; }
}
// Check to see if Status property is set
internal bool IsSetStatus()
{
return this._status != null;
}
/// <summary>
/// Gets and sets the property VpcSecurityGroups.
/// <para>
/// Provides a list of VPC security groups that the DB cluster belongs to.
/// </para>
/// </summary>
public List<VpcSecurityGroupMembership> VpcSecurityGroups
{
get { return this._vpcSecurityGroups; }
set { this._vpcSecurityGroups = value; }
}
// Check to see if VpcSecurityGroups property is set
internal bool IsSetVpcSecurityGroups()
{
return this._vpcSecurityGroups != null && this._vpcSecurityGroups.Count > 0;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using Xunit;
namespace Flatbox.RegularExpressions.Tests
{
public class RegexMatchTests
{
public static IEnumerable<object[]> Match_Basic_TestData()
{
// Testing octal sequence matches: "\\060(\\061)?\\061"
// Octal \061 is ASCII 49 ('1')
yield return new object[] { @"\060(\061)?\061", "011", RegexOptions.None, 0, 3, true, "011" };
// Testing hexadecimal sequence matches: "(\\x30\\x31\\x32)"
// Hex \x31 is ASCII 49 ('1')
yield return new object[] { @"(\x30\x31\x32)", "012", RegexOptions.None, 0, 3, true, "012" };
// Testing control character escapes???: "2", "(\u0032)"
yield return new object[] { "(\u0034)", "4", RegexOptions.None, 0, 1, true, "4", };
// Using *, +, ?, {}: Actual - "a+\\.?b*\\.?c{2}"
yield return new object[] { @"a+\.?b*\.+c{2}", "ab.cc", RegexOptions.None, 0, 5, true, "ab.cc" };
// Using [a-z], \s, \w: Actual - "([a-zA-Z]+)\\s(\\w+)"
yield return new object[] { @"([a-zA-Z]+)\s(\w+)", "David Bau", RegexOptions.None, 0, 9, true, "David Bau" };
// \\S, \\d, \\D, \\W: Actual - "(\\S+):\\W(\\d+)\\s(\\D+)"
yield return new object[] { @"(\S+):\W(\d+)\s(\D+)", "Price: 5 dollars", RegexOptions.None, 0, 16, true, "Price: 5 dollars" };
// \\S, \\d, \\D, \\W: Actual - "[^0-9]+(\\d+)"
yield return new object[] { @"[^0-9]+(\d+)", "Price: 30 dollars", RegexOptions.None, 0, 17, true, "Price: 30" };
// Zero-width negative lookahead assertion: Actual - "abc(?!XXX)\\w+"
yield return new object[] { @"abc(?!XXX)\w+", "abcXXXdef", RegexOptions.None, 0, 9, false, string.Empty };
// Zero-width positive lookbehind assertion: Actual - "(\\w){6}(?<=XXX)def"
yield return new object[] { @"(\w){6}(?<=XXX)def", "abcXXXdef", RegexOptions.None, 0, 9, true, "abcXXXdef" };
// Zero-width negative lookbehind assertion: Actual - "(\\w){6}(?<!XXX)def"
yield return new object[] { @"(\w){6}(?<!XXX)def", "XXXabcdef", RegexOptions.None, 0, 9, true, "XXXabcdef" };
// Nonbacktracking subexpression: Actual - "[^0-9]+(?>[0-9]+)3"
// The last 3 causes the match to fail, since the non backtracking subexpression does not give up the last digit it matched
// for it to be a success. For a correct match, remove the last character, '3' from the pattern
yield return new object[] { "[^0-9]+(?>[0-9]+)3", "abc123", RegexOptions.None, 0, 6, false, string.Empty };
// Using beginning/end of string chars \A, \Z: Actual - "\\Aaaa\\w+zzz\\Z"
yield return new object[] { @"\Aaaa\w+zzz\Z", "aaaasdfajsdlfjzzz", RegexOptions.None, 0, 17, true, "aaaasdfajsdlfjzzz" };
// Using beginning/end of string chars \A, \Z: Actual - "\\Aaaa\\w+zzz\\Z"
yield return new object[] { @"\Aaaa\w+zzz\Z", "aaaasdfajsdlfjzzza", RegexOptions.None, 0, 18, false, string.Empty };
// Using beginning/end of string chars \A, \Z: Actual - "\\Aaaa\\w+zzz\\Z"
yield return new object[] { @"\A(line2\n)line3\Z", "line2\nline3\n", RegexOptions.Multiline, 0, 12, true, "line2\nline3" };
// Using beginning/end of string chars ^: Actual - "^b"
yield return new object[] { "^b", "ab", RegexOptions.None, 0, 2, false, string.Empty };
// Actual - "(?<char>\\w)\\<char>"
yield return new object[] { @"(?<char>\w)\<char>", "aa", RegexOptions.None, 0, 2, true, "aa" };
// Actual - "(?<43>\\w)\\43"
yield return new object[] { @"(?<43>\w)\43", "aa", RegexOptions.None, 0, 2, true, "aa" };
// Actual - "abc(?(1)111|222)"
yield return new object[] { "(abbc)(?(1)111|222)", "abbc222", RegexOptions.None, 0, 7, false, string.Empty };
// "x" option. Removes unescaped whitespace from the pattern: Actual - " ([^/]+) ","x"
yield return new object[] { " ((.)+) ", "abc", RegexOptions.IgnorePatternWhitespace, 0, 3, true, "abc" };
// "x" option. Removes unescaped whitespace from the pattern. : Actual - "\x20([^/]+)\x20","x"
yield return new object[] { "\x20([^/]+)\x20\x20\x20\x20\x20\x20\x20", " abc ", RegexOptions.IgnorePatternWhitespace, 0, 10, true, " abc " };
// Turning on case insensitive option in mid-pattern : Actual - "aaa(?i:match this)bbb"
if ("i".ToUpper() == "I")
{
yield return new object[] { "aaa(?i:match this)bbb", "aaaMaTcH ThIsbbb", RegexOptions.None, 0, 16, true, "aaaMaTcH ThIsbbb" };
}
// Turning off case insensitive option in mid-pattern : Actual - "aaa(?-i:match this)bbb", "i"
yield return new object[] { "aaa(?-i:match this)bbb", "AaAmatch thisBBb", RegexOptions.IgnoreCase, 0, 16, true, "AaAmatch thisBBb" };
// Turning on/off all the options at once : Actual - "aaa(?imnsx-imnsx:match this)bbb", "i"
yield return new object[] { "aaa(?-i:match this)bbb", "AaAmatcH thisBBb", RegexOptions.IgnoreCase, 0, 16, false, string.Empty };
// Actual - "aaa(?#ignore this completely)bbb"
yield return new object[] { "aaa(?#ignore this completely)bbb", "aaabbb", RegexOptions.None, 0, 6, true, "aaabbb" };
// Trying empty string: Actual "[a-z0-9]+", ""
yield return new object[] { "[a-z0-9]+", "", RegexOptions.None, 0, 0, false, string.Empty };
// Numbering pattern slots: "(?<1>\\d{3})(?<2>\\d{3})(?<3>\\d{4})"
yield return new object[] { @"(?<1>\d{3})(?<2>\d{3})(?<3>\d{4})", "8885551111", RegexOptions.None, 0, 10, true, "8885551111" };
yield return new object[] { @"(?<1>\d{3})(?<2>\d{3})(?<3>\d{4})", "Invalid string", RegexOptions.None, 0, 14, false, string.Empty };
// Not naming pattern slots at all: "^(cat|chat)"
yield return new object[] { "^(cat|chat)", "cats are bad", RegexOptions.None, 0, 12, true, "cat" };
yield return new object[] { "abc", "abc", RegexOptions.None, 0, 3, true, "abc" };
yield return new object[] { "abc", "aBc", RegexOptions.None, 0, 3, false, string.Empty };
yield return new object[] { "abc", "aBc", RegexOptions.IgnoreCase, 0, 3, true, "aBc" };
// Using *, +, ?, {}: Actual - "a+\\.?b*\\.?c{2}"
yield return new object[] { @"a+\.?b*\.+c{2}", "ab.cc", RegexOptions.None, 0, 5, true, "ab.cc" };
// RightToLeft
yield return new object[] { @"\s+\d+", "sdf 12sad", RegexOptions.RightToLeft, 0, 9, true, " 12" };
yield return new object[] { @"\s+\d+", " asdf12 ", RegexOptions.RightToLeft, 0, 6, false, string.Empty };
yield return new object[] { "aaa", "aaabbb", RegexOptions.None, 3, 3, false, string.Empty };
yield return new object[] { @"foo\d+", "0123456789foo4567890foo ", RegexOptions.RightToLeft, 10, 3, false, string.Empty };
yield return new object[] { @"foo\d+", "0123456789foo4567890foo ", RegexOptions.RightToLeft, 11, 21, false, string.Empty };
// IgnoreCase
yield return new object[] { "AAA", "aaabbb", RegexOptions.IgnoreCase, 0, 6, true, "aaa" };
yield return new object[] { @"\p{Lu}", "1bc", RegexOptions.IgnoreCase, 0, 3, true, "b" };
yield return new object[] { @"\p{Ll}", "1bc", RegexOptions.IgnoreCase, 0, 3, true, "b" };
yield return new object[] { @"\p{Lt}", "1bc", RegexOptions.IgnoreCase, 0, 3, true, "b" };
yield return new object[] { @"\p{Lo}", "1bc", RegexOptions.IgnoreCase, 0, 3, false, string.Empty };
// "\D+"
yield return new object[] { @"\D+", "12321", RegexOptions.None, 0, 5, false, string.Empty };
// Groups
yield return new object[] { "(?<first_name>\\S+)\\s(?<last_name>\\S+)", "David Bau", RegexOptions.None, 0, 9, true, "David Bau" };
// "^b"
yield return new object[] { "^b", "abc", RegexOptions.None, 0, 3, false, string.Empty };
// RightToLeft
yield return new object[] { @"foo\d+", "0123456789foo4567890foo ", RegexOptions.RightToLeft, 0, 32, true, "foo4567890" };
yield return new object[] { @"foo\d+", "0123456789foo4567890foo ", RegexOptions.RightToLeft, 10, 22, true, "foo4567890" };
yield return new object[] { @"foo\d+", "0123456789foo4567890foo ", RegexOptions.RightToLeft, 10, 4, true, "foo4" };
// Trim leading and trailing whitespace
yield return new object[] { @"\s*(.*?)\s*$", " Hello World ", RegexOptions.None, 0, 13, true, " Hello World " };
// < in group
yield return new object[] { @"(?<cat>cat)\w+(?<dog-0>dog)", "cat_Hello_World_dog", RegexOptions.None, 0, 19, false, string.Empty };
// Atomic Zero-Width Assertions \A \Z \z \G \b \B
yield return new object[] { @"\A(cat)\s+(dog)", "cat \n\n\ncat dog", RegexOptions.None, 0, 20, false, string.Empty };
yield return new object[] { @"\A(cat)\s+(dog)", "cat \n\n\ncat dog", RegexOptions.Multiline, 0, 20, false, string.Empty };
yield return new object[] { @"\A(cat)\s+(dog)", "cat \n\n\ncat dog", RegexOptions.ECMAScript, 0, 20, false, string.Empty };
yield return new object[] { @"(cat)\s+(dog)\Z", "cat dog\n\n\ncat", RegexOptions.None, 0, 15, false, string.Empty };
yield return new object[] { @"(cat)\s+(dog)\Z", "cat dog\n\n\ncat ", RegexOptions.Multiline, 0, 20, false, string.Empty };
yield return new object[] { @"(cat)\s+(dog)\Z", "cat dog\n\n\ncat ", RegexOptions.ECMAScript, 0, 20, false, string.Empty };
yield return new object[] { @"(cat)\s+(dog)\z", "cat dog\n\n\ncat", RegexOptions.None, 0, 15, false, string.Empty };
yield return new object[] { @"(cat)\s+(dog)\z", "cat dog\n\n\ncat ", RegexOptions.Multiline, 0, 20, false, string.Empty };
yield return new object[] { @"(cat)\s+(dog)\z", "cat dog\n\n\ncat ", RegexOptions.ECMAScript, 0, 20, false, string.Empty };
yield return new object[] { @"(cat)\s+(dog)\z", "cat \n\n\n dog\n", RegexOptions.None, 0, 16, false, string.Empty };
yield return new object[] { @"(cat)\s+(dog)\z", "cat \n\n\n dog\n", RegexOptions.Multiline, 0, 16, false, string.Empty };
yield return new object[] { @"(cat)\s+(dog)\z", "cat \n\n\n dog\n", RegexOptions.ECMAScript, 0, 16, false, string.Empty };
yield return new object[] { @"\b@cat", "123START123;@catEND", RegexOptions.None, 0, 19, false, string.Empty };
yield return new object[] { @"\b<cat", "123START123'<catEND", RegexOptions.None, 0, 19, false, string.Empty };
yield return new object[] { @"\b,cat", "satwe,,,START',catEND", RegexOptions.None, 0, 21, false, string.Empty };
yield return new object[] { @"\b\[cat", "`12START123'[catEND", RegexOptions.None, 0, 19, false, string.Empty };
yield return new object[] { @"\B@cat", "123START123@catEND", RegexOptions.None, 0, 18, false, string.Empty };
yield return new object[] { @"\B<cat", "123START123<catEND", RegexOptions.None, 0, 18, false, string.Empty };
yield return new object[] { @"\B,cat", "satwe,,,START,catEND", RegexOptions.None, 0, 20, false, string.Empty };
yield return new object[] { @"\B\[cat", "`12START123[catEND", RegexOptions.None, 0, 18, false, string.Empty };
// Lazy operator Backtracking
yield return new object[] { @"http://([a-zA-z0-9\-]*\.?)*?(:[0-9]*)??/", "http://www.msn.com", RegexOptions.IgnoreCase, 0, 18, false, string.Empty };
// Grouping Constructs Invalid Regular Expressions
yield return new object[] { "(?!)", "(?!)cat", RegexOptions.None, 0, 7, false, string.Empty };
yield return new object[] { "(?<!)", "(?<!)cat", RegexOptions.None, 0, 8, false, string.Empty };
// Alternation construct
yield return new object[] { "(?(cat)|dog)", "cat", RegexOptions.None, 0, 3, true, string.Empty };
yield return new object[] { "(?(cat)|dog)", "catdog", RegexOptions.None, 0, 6, true, string.Empty };
yield return new object[] { "(?(cat)dog1|dog2)", "catdog1", RegexOptions.None, 0, 7, false, string.Empty };
yield return new object[] { "(?(cat)dog1|dog2)", "catdog2", RegexOptions.None, 0, 7, true, "dog2" };
yield return new object[] { "(?(cat)dog1|dog2)", "catdog1dog2", RegexOptions.None, 0, 11, true, "dog2" };
yield return new object[] { "(?(dog2))", "dog2", RegexOptions.None, 0, 4, true, string.Empty };
yield return new object[] { "(?(cat)|dog)", "oof", RegexOptions.None, 0, 3, false, string.Empty };
yield return new object[] { "(?(a:b))", "a", RegexOptions.None, 0, 1, true, string.Empty };
yield return new object[] { "(?(a:))", "a", RegexOptions.None, 0, 1, true, string.Empty };
// No Negation
yield return new object[] { "[abcd-[abcd]]+", "abcxyzABCXYZ`!@#$%^&*()_-+= \t\n", RegexOptions.None, 0, 30, false, string.Empty };
yield return new object[] { "[1234-[1234]]+", "abcxyzABCXYZ`!@#$%^&*()_-+= \t\n", RegexOptions.None, 0, 30, false, string.Empty };
// All Negation
yield return new object[] { "[^abcd-[^abcd]]+", "abcxyzABCXYZ`!@#$%^&*()_-+= \t\n", RegexOptions.None, 0, 30, false, string.Empty };
yield return new object[] { "[^1234-[^1234]]+", "abcxyzABCXYZ`!@#$%^&*()_-+= \t\n", RegexOptions.None, 0, 30, false, string.Empty };
// No Negation
yield return new object[] { "[a-z-[a-z]]+", "abcxyzABCXYZ`!@#$%^&*()_-+= \t\n", RegexOptions.None, 0, 30, false, string.Empty };
yield return new object[] { "[0-9-[0-9]]+", "abcxyzABCXYZ`!@#$%^&*()_-+= \t\n", RegexOptions.None, 0, 30, false, string.Empty };
// All Negation
yield return new object[] { "[^a-z-[^a-z]]+", "abcxyzABCXYZ`!@#$%^&*()_-+= \t\n", RegexOptions.None, 0, 30, false, string.Empty };
yield return new object[] { "[^0-9-[^0-9]]+", "abcxyzABCXYZ`!@#$%^&*()_-+= \t\n", RegexOptions.None, 0, 30, false, string.Empty };
// No Negation
yield return new object[] { @"[\w-[\w]]+", "abcxyzABCXYZ`!@#$%^&*()_-+= \t\n", RegexOptions.None, 0, 30, false, string.Empty };
yield return new object[] { @"[\W-[\W]]+", "abcxyzABCXYZ`!@#$%^&*()_-+= \t\n", RegexOptions.None, 0, 30, false, string.Empty };
yield return new object[] { @"[\s-[\s]]+", "abcxyzABCXYZ`!@#$%^&*()_-+= \t\n", RegexOptions.None, 0, 30, false, string.Empty };
yield return new object[] { @"[\S-[\S]]+", "abcxyzABCXYZ`!@#$%^&*()_-+= \t\n", RegexOptions.None, 0, 30, false, string.Empty };
yield return new object[] { @"[\d-[\d]]+", "abcxyzABCXYZ`!@#$%^&*()_-+= \t\n", RegexOptions.None, 0, 30, false, string.Empty };
yield return new object[] { @"[\D-[\D]]+", "abcxyzABCXYZ`!@#$%^&*()_-+= \t\n", RegexOptions.None, 0, 30, false, string.Empty };
// All Negation
yield return new object[] { @"[^\w-[^\w]]+", "abcxyzABCXYZ`!@#$%^&*()_-+= \t\n", RegexOptions.None, 0, 30, false, string.Empty };
yield return new object[] { @"[^\W-[^\W]]+", "abcxyzABCXYZ`!@#$%^&*()_-+= \t\n", RegexOptions.None, 0, 30, false, string.Empty };
yield return new object[] { @"[^\s-[^\s]]+", "abcxyzABCXYZ`!@#$%^&*()_-+= \t\n", RegexOptions.None, 0, 30, false, string.Empty };
yield return new object[] { @"[^\S-[^\S]]+", "abcxyzABCXYZ`!@#$%^&*()_-+= \t\n", RegexOptions.None, 0, 30, false, string.Empty };
yield return new object[] { @"[^\d-[^\d]]+", "abcxyzABCXYZ`!@#$%^&*()_-+= \t\n", RegexOptions.None, 0, 30, false, string.Empty };
yield return new object[] { @"[^\D-[^\D]]+", "abcxyzABCXYZ`!@#$%^&*()_-+= \t\n", RegexOptions.None, 0, 30, false, string.Empty };
// MixedNegation
yield return new object[] { @"[^\w-[\W]]+", "abcxyzABCXYZ`!@#$%^&*()_-+= \t\n", RegexOptions.None, 0, 30, false, string.Empty };
yield return new object[] { @"[\w-[^\W]]+", "abcxyzABCXYZ`!@#$%^&*()_-+= \t\n", RegexOptions.None, 0, 30, false, string.Empty };
yield return new object[] { @"[^\s-[\S]]+", "abcxyzABCXYZ`!@#$%^&*()_-+= \t\n", RegexOptions.None, 0, 30, false, string.Empty };
yield return new object[] { @"[\s-[^\S]]+", "abcxyzABCXYZ`!@#$%^&*()_-+= \t\n", RegexOptions.None, 0, 30, false, string.Empty };
yield return new object[] { @"[^\d-[\D]]+", "abcxyzABCXYZ`!@#$%^&*()_-+= \t\n", RegexOptions.None, 0, 30, false, string.Empty };
yield return new object[] { @"[\d-[^\D]]+", "abcxyzABCXYZ`!@#$%^&*()_-+= \t\n", RegexOptions.None, 0, 30, false, string.Empty };
// No Negation
yield return new object[] { @"[\p{Ll}-[\p{Ll}]]+", "abcxyzABCXYZ`!@#$%^&*()_-+= \t\n", RegexOptions.None, 0, 30, false, string.Empty };
yield return new object[] { @"[\P{Ll}-[\P{Ll}]]+", "abcxyzABCXYZ`!@#$%^&*()_-+= \t\n", RegexOptions.None, 0, 30, false, string.Empty };
yield return new object[] { @"[\p{Lu}-[\p{Lu}]]+", "abcxyzABCXYZ`!@#$%^&*()_-+= \t\n", RegexOptions.None, 0, 30, false, string.Empty };
yield return new object[] { @"[\P{Lu}-[\P{Lu}]]+", "abcxyzABCXYZ`!@#$%^&*()_-+= \t\n", RegexOptions.None, 0, 30, false, string.Empty };
yield return new object[] { @"[\p{Nd}-[\p{Nd}]]+", "abcxyzABCXYZ`!@#$%^&*()_-+= \t\n", RegexOptions.None, 0, 30, false, string.Empty };
yield return new object[] { @"[\P{Nd}-[\P{Nd}]]+", "abcxyzABCXYZ`!@#$%^&*()_-+= \t\n", RegexOptions.None, 0, 30, false, string.Empty };
// All Negation
yield return new object[] { @"[^\p{Ll}-[^\p{Ll}]]+", "abcxyzABCXYZ`!@#$%^&*()_-+= \t\n", RegexOptions.None, 0, 30, false, string.Empty };
yield return new object[] { @"[^\P{Ll}-[^\P{Ll}]]+", "abcxyzABCXYZ`!@#$%^&*()_-+= \t\n", RegexOptions.None, 0, 30, false, string.Empty };
yield return new object[] { @"[^\p{Lu}-[^\p{Lu}]]+", "abcxyzABCXYZ`!@#$%^&*()_-+= \t\n", RegexOptions.None, 0, 30, false, string.Empty };
yield return new object[] { @"[^\P{Lu}-[^\P{Lu}]]+", "abcxyzABCXYZ`!@#$%^&*()_-+= \t\n", RegexOptions.None, 0, 30, false, string.Empty };
yield return new object[] { @"[^\p{Nd}-[^\p{Nd}]]+", "abcxyzABCXYZ`!@#$%^&*()_-+= \t\n", RegexOptions.None, 0, 30, false, string.Empty };
yield return new object[] { @"[^\P{Nd}-[^\P{Nd}]]+", "abcxyzABCXYZ`!@#$%^&*()_-+= \t\n", RegexOptions.None, 0, 30, false, string.Empty };
// MixedNegation
yield return new object[] { @"[^\p{Ll}-[\P{Ll}]]+", "abcxyzABCXYZ`!@#$%^&*()_-+= \t\n", RegexOptions.None, 0, 30, false, string.Empty };
yield return new object[] { @"[\p{Ll}-[^\P{Ll}]]+", "abcxyzABCXYZ`!@#$%^&*()_-+= \t\n", RegexOptions.None, 0, 30, false, string.Empty };
yield return new object[] { @"[^\p{Lu}-[\P{Lu}]]+", "abcxyzABCXYZ`!@#$%^&*()_-+= \t\n", RegexOptions.None, 0, 30, false, string.Empty };
yield return new object[] { @"[\p{Lu}-[^\P{Lu}]]+", "abcxyzABCXYZ`!@#$%^&*()_-+= \t\n", RegexOptions.None, 0, 30, false, string.Empty };
yield return new object[] { @"[^\p{Nd}-[\P{Nd}]]+", "abcxyzABCXYZ`!@#$%^&*()_-+= \t\n", RegexOptions.None, 0, 30, false, string.Empty };
yield return new object[] { @"[\p{Nd}-[^\P{Nd}]]+", "abcxyzABCXYZ`!@#$%^&*()_-+= \t\n", RegexOptions.None, 0, 30, false, string.Empty };
// Character Class Substraction
yield return new object[] { @"[ab\-\[cd-[-[]]]]", "[]]", RegexOptions.None, 0, 3, false, string.Empty };
yield return new object[] { @"[ab\-\[cd-[-[]]]]", "-]]", RegexOptions.None, 0, 3, false, string.Empty };
yield return new object[] { @"[ab\-\[cd-[-[]]]]", "`]]", RegexOptions.None, 0, 3, false, string.Empty };
yield return new object[] { @"[ab\-\[cd-[-[]]]]", "e]]", RegexOptions.None, 0, 3, false, string.Empty };
yield return new object[] { @"[ab\-\[cd-[[]]]]", "']]", RegexOptions.None, 0, 3, false, string.Empty };
yield return new object[] { @"[ab\-\[cd-[[]]]]", "e]]", RegexOptions.None, 0, 3, false, string.Empty };
yield return new object[] { @"[a-[a-f]]", "abcdefghijklmnopqrstuvwxyz", RegexOptions.None, 0, 26, false, string.Empty };
}
[Theory]
[MemberData(nameof(Match_Basic_TestData))]
public void Match(string pattern, string input, RegexOptions options, int beginning, int length, bool expectedSuccess, string expectedValue)
{
bool isDefaultStart = RegexHelpers.IsDefaultStart(input, options, beginning);
bool isDefaultCount = RegexHelpers.IsDefaultCount(input, options, length);
if (options == RegexOptions.None)
{
if (isDefaultStart && isDefaultCount)
{
// Use Match(string) or Match(string, string)
VerifyMatch(new Regex(pattern).Match(input), expectedSuccess, expectedValue);
VerifyMatch(Regex.Match(input, pattern), expectedSuccess, expectedValue);
Assert.Equal(expectedSuccess, new Regex(pattern).IsMatch(input));
Assert.Equal(expectedSuccess, Regex.IsMatch(input, pattern));
}
if (beginning + length == input.Length)
{
// Use Match(string, int)
VerifyMatch(new Regex(pattern).Match(input, beginning), expectedSuccess, expectedValue);
Assert.Equal(expectedSuccess, new Regex(pattern).IsMatch(input, beginning));
}
// Use Match(string, int, int)
VerifyMatch(new Regex(pattern).Match(input, beginning, length), expectedSuccess, expectedValue);
}
if (isDefaultStart && isDefaultCount)
{
// Use Match(string) or Match(string, string, RegexOptions)
VerifyMatch(new Regex(pattern, options).Match(input), expectedSuccess, expectedValue);
VerifyMatch(Regex.Match(input, pattern, options), expectedSuccess, expectedValue);
Assert.Equal(expectedSuccess, Regex.IsMatch(input, pattern, options));
}
if (beginning + length == input.Length && (options & RegexOptions.RightToLeft) == 0)
{
// Use Match(string, int)
VerifyMatch(new Regex(pattern, options).Match(input, beginning), expectedSuccess, expectedValue);
}
// Use Match(string, int, int)
VerifyMatch(new Regex(pattern, options).Match(input, beginning, length), expectedSuccess, expectedValue);
}
public static void VerifyMatch(Match match, bool expectedSuccess, string expectedValue)
{
Assert.Equal(expectedSuccess, match.Success);
Assert.Equal(expectedValue, match.Value);
// Groups can never be empty
Assert.True(match.Groups.Count >= 1);
Assert.Equal(expectedSuccess, match.Groups[0].Success);
Assert.Equal(expectedValue, match.Groups[0].Value);
}
[Fact]
public void Match_Timeout()
{
Regex regex = new Regex(@"\p{Lu}", RegexOptions.IgnoreCase, TimeSpan.FromHours(1));
Match match = regex.Match("abc");
Assert.True(match.Success);
Assert.Equal("a", match.Value);
}
[Fact]
public void Match_Timeout_Throws()
{
const string Pattern = @"^([0-9a-zA-Z]([-.\w]*[0-9a-zA-Z])*@(([0-9a-zA-Z])+([-\w]*[0-9a-zA-Z])*\.)+[a-zA-Z]{2,9})$";
string input = new string('a', 50) + "@a.a";
AppDomain.CurrentDomain.SetData(RegexHelpers.DefaultMatchTimeout_ConfigKeyName, TimeSpan.FromMilliseconds(100));
Assert.Throws<RegexMatchTimeoutException>(() => new Regex(Pattern).Match(input));
}
public static IEnumerable<object[]> Match_Advanced_TestData()
{
// \B special character escape: ".*\\B(SUCCESS)\\B.*"
yield return new object[]
{
@".*\B(SUCCESS)\B.*", "adfadsfSUCCESSadsfadsf", RegexOptions.None, 0, 22,
new CaptureData[]
{
new CaptureData("adfadsfSUCCESSadsfadsf", 0, 22),
new CaptureData("SUCCESS", 7, 7)
}
};
// Using |, (), ^, $, .: Actual - "^aaa(bb.+)(d|c)$"
yield return new object[]
{
"^aaa(bb.+)(d|c)$", "aaabb.cc", RegexOptions.None, 0, 8,
new CaptureData[]
{
new CaptureData("aaabb.cc", 0, 8),
new CaptureData("bb.c", 3, 4),
new CaptureData("c", 7, 1)
}
};
// Using greedy quantifiers: Actual - "(a+)(b*)(c?)"
yield return new object[]
{
"(a+)(b*)(c?)", "aaabbbccc", RegexOptions.None, 0, 9,
new CaptureData[]
{
new CaptureData("aaabbbc", 0, 7),
new CaptureData("aaa", 0, 3),
new CaptureData("bbb", 3, 3),
new CaptureData("c", 6, 1)
}
};
// Using lazy quantifiers: Actual - "(d+?)(e*?)(f??)"
// Interesting match from this pattern and input. If needed to go to the end of the string change the ? to + in the last lazy quantifier
yield return new object[]
{
"(d+?)(e*?)(f??)", "dddeeefff", RegexOptions.None, 0, 9,
new CaptureData[]
{
new CaptureData("d", 0, 1),
new CaptureData("d", 0, 1),
new CaptureData(string.Empty, 1, 0),
new CaptureData(string.Empty, 1, 0)
}
};
// Noncapturing group : Actual - "(a+)(?:b*)(ccc)"
yield return new object[]
{
"(a+)(?:b*)(ccc)", "aaabbbccc", RegexOptions.None, 0, 9,
new CaptureData[]
{
new CaptureData("aaabbbccc", 0, 9),
new CaptureData("aaa", 0, 3),
new CaptureData("ccc", 6, 3),
}
};
// Zero-width positive lookahead assertion: Actual - "abc(?=XXX)\\w+"
yield return new object[]
{
@"abc(?=XXX)\w+", "abcXXXdef", RegexOptions.None, 0, 9,
new CaptureData[]
{
new CaptureData("abcXXXdef", 0, 9)
}
};
// Backreferences : Actual - "(\\w)\\1"
yield return new object[]
{
@"(\w)\1", "aa", RegexOptions.None, 0, 2,
new CaptureData[]
{
new CaptureData("aa", 0, 2),
new CaptureData("a", 0, 1),
}
};
// Alternation constructs: Actual - "(111|aaa)"
yield return new object[]
{
"(111|aaa)", "aaa", RegexOptions.None, 0, 3,
new CaptureData[]
{
new CaptureData("aaa", 0, 3),
new CaptureData("aaa", 0, 3)
}
};
// Actual - "(?<1>\\d+)abc(?(1)222|111)"
yield return new object[]
{
@"(?<MyDigits>\d+)abc(?(MyDigits)222|111)", "111abc222", RegexOptions.None, 0, 9,
new CaptureData[]
{
new CaptureData("111abc222", 0, 9),
new CaptureData("111", 0, 3)
}
};
// Using "n" Regex option. Only explicitly named groups should be captured: Actual - "([0-9]*)\\s(?<s>[a-z_A-Z]+)", "n"
yield return new object[]
{
@"([0-9]*)\s(?<s>[a-z_A-Z]+)", "200 dollars", RegexOptions.ExplicitCapture, 0, 11,
new CaptureData[]
{
new CaptureData("200 dollars", 0, 11),
new CaptureData("dollars", 4, 7)
}
};
// Single line mode "s". Includes new line character: Actual - "([^/]+)","s"
yield return new object[]
{
"(.*)", "abc\nsfc", RegexOptions.Singleline, 0, 7,
new CaptureData[]
{
new CaptureData("abc\nsfc", 0, 7),
new CaptureData("abc\nsfc", 0, 7),
}
};
// "([0-9]+(\\.[0-9]+){3})"
yield return new object[]
{
@"([0-9]+(\.[0-9]+){3})", "209.25.0.111", RegexOptions.None, 0, 12,
new CaptureData[]
{
new CaptureData("209.25.0.111", 0, 12),
new CaptureData("209.25.0.111", 0, 12),
new CaptureData(".111", 8, 4, new CaptureData[]
{
new CaptureData(".25", 3, 3),
new CaptureData(".0", 6, 2),
new CaptureData(".111", 8, 4),
}),
}
};
// Groups and captures
yield return new object[]
{
@"(?<A1>a*)(?<A2>b*)(?<A3>c*)", "aaabbccccccccccaaaabc", RegexOptions.None, 0, 21,
new CaptureData[]
{
new CaptureData("aaabbcccccccccc", 0, 15),
new CaptureData("aaa", 0, 3),
new CaptureData("bb", 3, 2),
new CaptureData("cccccccccc", 5, 10)
}
};
yield return new object[]
{
@"(?<A1>A*)(?<A2>B*)(?<A3>C*)", "aaabbccccccccccaaaabc", RegexOptions.IgnoreCase, 0, 21,
new CaptureData[]
{
new CaptureData("aaabbcccccccccc", 0, 15),
new CaptureData("aaa", 0, 3),
new CaptureData("bb", 3, 2),
new CaptureData("cccccccccc", 5, 10)
}
};
// Using |, (), ^, $, .: Actual - "^aaa(bb.+)(d|c)$"
yield return new object[]
{
"^aaa(bb.+)(d|c)$", "aaabb.cc", RegexOptions.None, 0, 8,
new CaptureData[]
{
new CaptureData("aaabb.cc", 0, 8),
new CaptureData("bb.c", 3, 4),
new CaptureData("c", 7, 1)
}
};
// Actual - ".*\\b(\\w+)\\b"
yield return new object[]
{
@".*\b(\w+)\b", "XSP_TEST_FAILURE SUCCESS", RegexOptions.None, 0, 24,
new CaptureData[]
{
new CaptureData("XSP_TEST_FAILURE SUCCESS", 0, 24),
new CaptureData("SUCCESS", 17, 7)
}
};
// Mutliline
yield return new object[]
{
"(line2$\n)line3", "line1\nline2\nline3\n\nline4", RegexOptions.Multiline, 0, 24,
new CaptureData[]
{
new CaptureData("line2\nline3", 6, 11),
new CaptureData("line2\n", 6, 6)
}
};
// Mutliline
yield return new object[]
{
"(line2\n^)line3", "line1\nline2\nline3\n\nline4", RegexOptions.Multiline, 0, 24,
new CaptureData[]
{
new CaptureData("line2\nline3", 6, 11),
new CaptureData("line2\n", 6, 6)
}
};
// Mutliline
yield return new object[]
{
"(line3\n$\n)line4", "line1\nline2\nline3\n\nline4", RegexOptions.Multiline, 0, 24,
new CaptureData[]
{
new CaptureData("line3\n\nline4", 12, 12),
new CaptureData("line3\n\n", 12, 7)
}
};
// Mutliline
yield return new object[]
{
"(line3\n^\n)line4", "line1\nline2\nline3\n\nline4", RegexOptions.Multiline, 0, 24,
new CaptureData[]
{
new CaptureData("line3\n\nline4", 12, 12),
new CaptureData("line3\n\n", 12, 7)
}
};
// Mutliline
yield return new object[]
{
"(line2$\n^)line3", "line1\nline2\nline3\n\nline4", RegexOptions.Multiline, 0, 24,
new CaptureData[]
{
new CaptureData("line2\nline3", 6, 11),
new CaptureData("line2\n", 6, 6)
}
};
// RightToLeft
yield return new object[]
{
"aaa", "aaabbb", RegexOptions.RightToLeft, 3, 3,
new CaptureData[]
{
new CaptureData("aaa", 0, 3)
}
};
}
[Theory]
[MemberData(nameof(Match_Advanced_TestData))]
public void Match(string pattern, string input, RegexOptions options, int beginning, int length, CaptureData[] expected)
{
bool isDefaultStart = RegexHelpers.IsDefaultStart(input, options, beginning);
bool isDefaultCount = RegexHelpers.IsDefaultStart(input, options, length);
if (options == RegexOptions.None)
{
if (isDefaultStart && isDefaultCount)
{
// Use Match(string) or Match(string, string)
VerifyMatch(new Regex(pattern).Match(input), true, expected);
VerifyMatch(Regex.Match(input, pattern), true, expected);
Assert.True(new Regex(pattern).IsMatch(input));
Assert.True(Regex.IsMatch(input, pattern));
}
if (beginning + length == input.Length)
{
// Use Match(string, int)
VerifyMatch(new Regex(pattern).Match(input, beginning), true, expected);
Assert.True(new Regex(pattern).IsMatch(input, beginning));
}
else
{
// Use Match(string, int, int)
VerifyMatch(new Regex(pattern).Match(input, beginning, length), true, expected);
}
}
if (isDefaultStart && isDefaultCount)
{
// Use Match(string) or Match(string, string, RegexOptions)
VerifyMatch(new Regex(pattern, options).Match(input), true, expected);
VerifyMatch(Regex.Match(input, pattern, options), true, expected);
Assert.True(Regex.IsMatch(input, pattern, options));
}
if (beginning + length == input.Length)
{
// Use Match(string, int)
VerifyMatch(new Regex(pattern, options).Match(input, beginning), true, expected);
}
if ((options & RegexOptions.RightToLeft) == 0)
{
// Use Match(string, int, int)
VerifyMatch(new Regex(pattern, options).Match(input, beginning, length), true, expected);
}
}
public static void VerifyMatch(Match match, bool expectedSuccess, CaptureData[] expected)
{
Assert.Equal(expectedSuccess, match.Success);
Assert.Equal(expected[0].Value, match.Value);
Assert.Equal(expected[0].Index, match.Index);
Assert.Equal(expected[0].Length, match.Length);
Assert.Equal(1, match.Captures.Count);
Assert.Equal(expected[0].Value, match.Captures[0].Value);
Assert.Equal(expected[0].Index, match.Captures[0].Index);
Assert.Equal(expected[0].Length, match.Captures[0].Length);
Assert.Equal(expected.Length, match.Groups.Count);
for (int i = 0; i < match.Groups.Count; i++)
{
Assert.Equal(expectedSuccess, match.Groups[i].Success);
Assert.Equal(expected[i].Value, match.Groups[i].Value);
Assert.Equal(expected[i].Index, match.Groups[i].Index);
Assert.Equal(expected[i].Length, match.Groups[i].Length);
Assert.Equal(expected[i].Captures.Length, match.Groups[i].Captures.Count);
for (int j = 0; j < match.Groups[i].Captures.Count; j++)
{
Assert.Equal(expected[i].Captures[j].Value, match.Groups[i].Captures[j].Value);
Assert.Equal(expected[i].Captures[j].Index, match.Groups[i].Captures[j].Index);
Assert.Equal(expected[i].Captures[j].Length, match.Groups[i].Captures[j].Length);
}
}
}
[Theory]
[InlineData(@"(?<1>\d{1,2})/(?<2>\d{1,2})/(?<3>\d{2,4})\s(?<time>\S+)", "08/10/99 16:00", "${time}", "16:00")]
[InlineData(@"(?<1>\d{1,2})/(?<2>\d{1,2})/(?<3>\d{2,4})\s(?<time>\S+)", "08/10/99 16:00", "${1}", "08")]
[InlineData(@"(?<1>\d{1,2})/(?<2>\d{1,2})/(?<3>\d{2,4})\s(?<time>\S+)", "08/10/99 16:00", "${2}", "10")]
[InlineData(@"(?<1>\d{1,2})/(?<2>\d{1,2})/(?<3>\d{2,4})\s(?<time>\S+)", "08/10/99 16:00", "${3}", "99")]
[InlineData("abc", "abc", "abc", "abc")]
public void Result(string pattern, string input, string replacement, string expected)
{
Assert.Equal(expected, new Regex(pattern).Match(input).Result(replacement));
}
[Fact]
public void Result_Invalid()
{
Match match = Regex.Match("foo", "foo");
AssertExtensions.Throws<ArgumentNullException>("replacement", () => match.Result(null));
Assert.Throws<NotSupportedException>(() => RegularExpressions.Match.Empty.Result("any"));
}
[Fact]
public void Match_SpecialUnicodeCharacters_enUS()
{
CultureInfo.CurrentCulture = new CultureInfo("en-US");
Match("\u0131", "\u0049", RegexOptions.IgnoreCase, 0, 1, false, string.Empty);
Match("\u0131", "\u0069", RegexOptions.IgnoreCase, 0, 1, false, string.Empty);
}
[Fact]
public void Match_SpecialUnicodeCharacters_Invariant()
{
CultureInfo.CurrentCulture = CultureInfo.InvariantCulture;
Match("\u0131", "\u0049", RegexOptions.IgnoreCase, 0, 1, false, string.Empty);
Match("\u0131", "\u0069", RegexOptions.IgnoreCase, 0, 1, false, string.Empty);
Match("\u0130", "\u0049", RegexOptions.IgnoreCase, 0, 1, false, string.Empty);
Match("\u0130", "\u0069", RegexOptions.IgnoreCase, 0, 1, false, string.Empty);
}
[Fact]
public void Match_Invalid()
{
// Input is null
AssertExtensions.Throws<ArgumentNullException>("input", () => Regex.Match(null, "pattern"));
AssertExtensions.Throws<ArgumentNullException>("input", () => Regex.Match(null, "pattern", RegexOptions.None));
AssertExtensions.Throws<ArgumentNullException>("input", () => Regex.Match(null, "pattern", RegexOptions.None, TimeSpan.FromSeconds(1)));
AssertExtensions.Throws<ArgumentNullException>("input", () => new Regex("pattern").Match(null));
AssertExtensions.Throws<ArgumentNullException>("input", () => new Regex("pattern").Match(null, 0));
AssertExtensions.Throws<ArgumentNullException>("input", () => new Regex("pattern").Match(null, 0, 0));
// Pattern is null
AssertExtensions.Throws<ArgumentNullException>("pattern", () => Regex.Match("input", null));
AssertExtensions.Throws<ArgumentNullException>("pattern", () => Regex.Match("input", null, RegexOptions.None));
AssertExtensions.Throws<ArgumentNullException>("pattern", () => Regex.Match("input", null, RegexOptions.None, TimeSpan.FromSeconds(1)));
// Start is invalid
Assert.Throws<ArgumentOutOfRangeException>(() => new Regex("pattern").Match("input", -1));
Assert.Throws<ArgumentOutOfRangeException>(() => new Regex("pattern").Match("input", -1, 0));
Assert.Throws<ArgumentOutOfRangeException>(() => new Regex("pattern").Match("input", 6));
Assert.Throws<ArgumentOutOfRangeException>(() => new Regex("pattern").Match("input", 6, 0));
// Length is invalid
AssertExtensions.Throws<ArgumentOutOfRangeException>("length", () => new Regex("pattern").Match("input", 0, -1));
AssertExtensions.Throws<ArgumentOutOfRangeException>("length", () => new Regex("pattern").Match("input", 0, 6));
}
[Theory]
[InlineData(")")]
[InlineData("())")]
[InlineData("[a-z-[aeiuo]")]
[InlineData("[a-z-[aeiuo")]
[InlineData("[a-z-[b]")]
[InlineData("[a-z-[b")]
[InlineData("[b-a]")]
[InlineData(@"[a-c]{2,1}")]
[InlineData(@"\d{2147483648}")]
[InlineData("[a-z-[b][")]
[InlineData(@"\")]
[InlineData("(?()|||||)")]
public void Match_InvalidPattern(string pattern)
{
AssertExtensions.Throws<ArgumentException>(null, () => Regex.Match("input", pattern));
}
[Fact]
public void IsMatch_Invalid()
{
// Input is null
AssertExtensions.Throws<ArgumentNullException>("input", () => Regex.IsMatch(null, "pattern"));
AssertExtensions.Throws<ArgumentNullException>("input", () => Regex.IsMatch(null, "pattern", RegexOptions.None));
AssertExtensions.Throws<ArgumentNullException>("input", () => Regex.IsMatch(null, "pattern", RegexOptions.None, TimeSpan.FromSeconds(1)));
AssertExtensions.Throws<ArgumentNullException>("input", () => new Regex("pattern").IsMatch(null));
AssertExtensions.Throws<ArgumentNullException>("input", () => new Regex("pattern").IsMatch(null, 0));
// Pattern is null
AssertExtensions.Throws<ArgumentNullException>("pattern", () => Regex.IsMatch("input", null));
AssertExtensions.Throws<ArgumentNullException>("pattern", () => Regex.IsMatch("input", null, RegexOptions.None));
AssertExtensions.Throws<ArgumentNullException>("pattern", () => Regex.IsMatch("input", null, RegexOptions.None, TimeSpan.FromSeconds(1)));
// Start is invalid
Assert.Throws<ArgumentOutOfRangeException>(() => new Regex("pattern").IsMatch("input", -1));
Assert.Throws<ArgumentOutOfRangeException>(() => new Regex("pattern").IsMatch("input", 6));
}
}
}
| |
//
// Copyright (C) 2012-2014 DataStax Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Threading;
namespace Cassandra
{
/// <summary>
/// Helper class to build <link>Cluster</link> instances.
/// </summary>
public class Builder : IInitializer
{
private readonly List<IPEndPoint> _addresses = new List<IPEndPoint>();
private PoolingOptions _poolingOptions;
private SocketOptions _socketOptions = new SocketOptions();
private IAuthInfoProvider _authInfoProvider;
private IAuthProvider _authProvider = NoneAuthProvider.Instance;
private CompressionType _compression = CompressionType.NoCompression;
private IFrameCompressor _customCompressor;
private string _defaultKeyspace;
private ILoadBalancingPolicy _loadBalancingPolicy;
private int _port = ProtocolOptions.DefaultPort;
private int _queryAbortTimeout = Timeout.Infinite;
private QueryOptions _queryOptions = new QueryOptions();
private IReconnectionPolicy _reconnectionPolicy;
private IRetryPolicy _retryPolicy;
private SSLOptions _sslOptions;
private bool _withoutRowSetBuffering;
private IAddressTranslator _addressTranslator = new DefaultAddressTranslator();
/// <summary>
/// The pooling options used by this builder.
/// </summary>
///
/// <returns>the pooling options that will be used by this builder. You can use
/// the returned object to define the initial pooling options for the built
/// cluster.</returns>
public PoolingOptions PoolingOptions
{
get { return _poolingOptions; }
}
/// <summary>
/// The socket options used by this builder.
/// </summary>
///
/// <returns>the socket options that will be used by this builder. You can use
/// the returned object to define the initial socket options for the built
/// cluster.</returns>
public SocketOptions SocketOptions
{
get { return _socketOptions; }
}
public ICollection<IPEndPoint> ContactPoints
{
get { return _addresses; }
}
/// <summary>
/// The configuration that will be used for the new cluster. <p> You <b>should
/// not</b> modify this object directly as change made to the returned object may
/// not be used by the cluster build. Instead, you should use the other methods
/// of this <c>Builder</c></p>.
/// </summary>
///
/// <returns>the configuration to use for the new cluster.</returns>
public Configuration GetConfiguration()
{
var policies = new Policies(
_loadBalancingPolicy ?? Policies.DefaultLoadBalancingPolicy,
_reconnectionPolicy ?? Policies.DefaultReconnectionPolicy,
_retryPolicy ?? Policies.DefaultRetryPolicy
);
return new Configuration(policies,
new ProtocolOptions(_port, _sslOptions).SetCompression(_compression).SetCustomCompressor(_customCompressor),
_poolingOptions,
_socketOptions,
new ClientOptions(_withoutRowSetBuffering, _queryAbortTimeout, _defaultKeyspace),
_authProvider,
_authInfoProvider,
_queryOptions,
_addressTranslator
);
}
/// <summary>
/// The port to use to connect to all Cassandra hosts. If not set through this
/// method, the default port (9042) will be used instead.
/// </summary>
/// <param name="port"> the port to set. </param>
/// <returns>this Builder</returns>
public Builder WithPort(int port)
{
_port = port;
foreach (var addr in _addresses)
{
addr.Port = port;
}
return this;
}
/// <summary>
/// Sets the QueryOptions to use for the newly created Cluster.
///
/// If no query options are set through this method, default query
/// options will be used.
/// </summary>
/// <param name="options">the QueryOptions to use.</param>
/// <returns>this Builder.</returns>
public Builder WithQueryOptions(QueryOptions options)
{
_queryOptions = options;
return this;
}
/// <summary>
/// Sets the compression to use for the transport.
/// </summary>
/// <param name="compression"> the compression to set </param>
/// <returns>this Builder <see>ProtocolOptions.Compression</see></returns>
public Builder WithCompression(CompressionType compression)
{
_compression = compression;
return this;
}
/// <summary>
/// Sets a custom compressor to be used for the compression type.
/// If specified, the compression type is mandatory.
/// If not specified the driver default compressor will be use for the compression type.
/// </summary>
/// <param name="compressor">Implementation of IFrameCompressor</param>
public Builder WithCustomCompressor(IFrameCompressor compressor)
{
_customCompressor = compressor;
return this;
}
/// <summary>
/// Adds a contact point. Contact points are addresses of Cassandra nodes that
/// the driver uses to discover the cluster topology. Only one contact point is
/// required (the driver will retrieve the address of the other nodes
/// automatically), but it is usually a good idea to provide more than one
/// contact point, as if that unique contact point is not available, the driver
/// won't be able to initialize itself correctly.
/// </summary>
/// <remarks>
/// However, this can be useful if the Cassandra nodes are behind a router and
/// are not accessed directly. Note that if you are in this situation
/// (Cassandra nodes are behind a router, not directly accessible), you almost
/// surely want to provide a specific <c>IAddressTranslator</c>
/// (through <link>Builder.WithAddressTranslater</link>) to translate actual
/// Cassandra node addresses to the addresses the driver should use, otherwise
/// the driver will not be able to auto-detect new nodes (and will generally not
/// function optimally).
/// </remarks>
/// <param name="address">the address of the node to connect to</param>
/// <returns>this Builder</returns>
public Builder AddContactPoint(string address)
{
AddContactPoints(Utils.ResolveHostByName(address));
return this;
}
/// <summary>
/// Add contact point. See <see cref="Builder.AddContactPoint(string)"/> for more details
/// on contact points.
/// </summary>
/// <param name="address"> address of the node to add as contact point</param>
/// <returns>this Builder</returns>
public Builder AddContactPoint(IPAddress address)
{
AddContactPoint(new IPEndPoint(address, _port));
return this;
}
/// <summary>
/// Add contact point. See <see cref="Builder.AddContactPoint(string)"/> for more details
/// on contact points.
/// </summary>
/// <param name="address"> address of the node to add as contact point</param>
/// <returns>this Builder</returns>
public Builder AddContactPoint(IPEndPoint address)
{
_addresses.Add(address);
return this;
}
/// <summary>
/// Add contact points. See <see cref="Builder.AddContactPoint(string)"/> for more details
/// on contact points.
/// </summary>
/// <param name="addresses"> addresses of the nodes to add as contact point</param>
/// <returns>this Builder </returns>
public Builder AddContactPoints(params string[] addresses)
{
AddContactPoints(addresses.AsEnumerable());
return this;
}
/// <summary>
/// Add contact points. See <link>Builder.AddContactPoint</link> for more details
/// on contact points.
/// </summary>
/// <param name="addresses"> addresses of the nodes to add as contact point</param>
/// <returns>this Builder</returns>
public Builder AddContactPoints(IEnumerable<string> addresses)
{
AddContactPoints(addresses.SelectMany(Utils.ResolveHostByName));
return this;
}
/// <summary>
/// Add contact points. See <link>Builder.AddContactPoint</link> for more details
/// on contact points.
/// </summary>
/// <param name="addresses"> addresses of the nodes to add as contact point</param>
/// <returns>this Builder</returns>
public Builder AddContactPoints(params IPAddress[] addresses)
{
AddContactPoints(addresses.AsEnumerable());
return this;
}
/// <summary>
/// Add contact points. See <link>Builder.AddContactPoint</link> for more details
/// on contact points.
/// </summary>
/// <param name="addresses"> addresses of the nodes to add as contact point</param>
/// <returns>this Builder</returns>
public Builder AddContactPoints(IEnumerable<IPAddress> addresses)
{
AddContactPoints(addresses.Select(p => new IPEndPoint(p, _port)));
return this;
}
/// <summary>
/// Add contact points. See <link>Builder.AddContactPoint</link> for more details
/// on contact points.
/// </summary>
/// <param name="addresses"> addresses of the nodes to add as contact point
/// </param>
///
/// <returns>this Builder</returns>
public Builder AddContactPoints(params IPEndPoint[] addresses)
{
AddContactPoints(addresses.AsEnumerable());
return this;
}
/// <summary>
/// Add contact points. See <link>Builder.AddContactPoint</link> for more details
/// on contact points.
/// </summary>
/// <param name="addresses"> addresses of the nodes to add as contact point
/// </param>
///
/// <returns>this Builder</returns>
public Builder AddContactPoints(IEnumerable<IPEndPoint> addresses)
{
_addresses.AddRange(addresses);
return this;
}
/// <summary>
/// Configure the load balancing policy to use for the new cluster. <p> If no
/// load balancing policy is set through this method,
/// <link>Policies.DefaultLoadBalancingPolicy</link> will be used instead.</p>
/// </summary>
/// <param name="policy"> the load balancing policy to use </param>
///
/// <returns>this Builder</returns>
public Builder WithLoadBalancingPolicy(ILoadBalancingPolicy policy)
{
_loadBalancingPolicy = policy;
return this;
}
/// <summary>
/// Configure the reconnection policy to use for the new cluster. <p> If no
/// reconnection policy is set through this method,
/// <link>Policies.DefaultReconnectionPolicy</link> will be used instead.</p>
/// </summary>
/// <param name="policy"> the reconnection policy to use </param>
///
/// <returns>this Builder</returns>
public Builder WithReconnectionPolicy(IReconnectionPolicy policy)
{
_reconnectionPolicy = policy;
return this;
}
/// <summary>
/// Configure the retry policy to use for the new cluster. <p> If no retry policy
/// is set through this method, <link>Policies.DefaultRetryPolicy</link> will
/// be used instead.</p>
/// </summary>
/// <param name="policy"> the retry policy to use </param>
///
/// <returns>this Builder</returns>
public Builder WithRetryPolicy(IRetryPolicy policy)
{
_retryPolicy = policy;
return this;
}
/// <summary>
/// Configure the cluster by applying settings from ConnectionString.
/// </summary>
/// <param name="connectionString"> the ConnectionString to use </param>
///
/// <returns>this Builder</returns>
public Builder WithConnectionString(string connectionString)
{
var cnb = new CassandraConnectionStringBuilder(connectionString);
return cnb.ApplyToBuilder(this);
}
/// <summary>
/// Uses the provided credentials when connecting to Cassandra hosts. <p> This
/// should be used if the Cassandra cluster has been configured to use the
/// <c>PasswordAuthenticator</c>. If the the default <c>*
/// AllowAllAuthenticator</c> is used instead, using this method has no effect.</p>
/// </summary>
/// <param name="username"> the user name to use to login to Cassandra hosts.</param>
/// <param name="password"> the password corresponding to </param>
/// <returns>this Builder</returns>
public Builder WithCredentials(String username, String password)
{
_authInfoProvider = new SimpleAuthInfoProvider().Add("username", username).Add("password", password);
_authProvider = new PlainTextAuthProvider(username, password);
return this;
}
/// <summary>
/// Use the specified AuthProvider when connecting to Cassandra hosts. <p> Use
/// this method when a custom authentication scheme is in place. You shouldn't
/// call both this method and {@code withCredentials}' on the same
/// <c>Builder</c> instance as one will supersede the other</p>
/// </summary>
/// <param name="authProvider"> the <link>AuthProvider"></link> to use to login to Cassandra hosts.</param>
/// <returns>this Builder</returns>
public Builder WithAuthProvider(IAuthProvider authProvider)
{
_authProvider = authProvider;
return this;
}
/// <summary>
/// Disables row set buffering for the created cluster (row set buffering is enabled by
/// default otherwise).
/// </summary>
///
/// <returns>this builder</returns>
public Builder WithoutRowSetBuffering()
{
_withoutRowSetBuffering = true;
return this;
}
/// <summary>
/// Sets the timeout for a single query within created cluster.
/// After the expiry of the timeout, query will be aborted.
/// Default timeout value is set to <c>Infinity</c>
/// </summary>
/// <param name="queryAbortTimeout">Timeout specified in milliseconds.</param>
/// <returns>this builder</returns>
public Builder WithQueryTimeout(int queryAbortTimeout)
{
_queryAbortTimeout = queryAbortTimeout;
return this;
}
/// <summary>
/// Sets default keyspace name for the created cluster.
/// </summary>
/// <param name="defaultKeyspace">Default keyspace name.</param>
/// <returns>this builder</returns>
public Builder WithDefaultKeyspace(string defaultKeyspace)
{
_defaultKeyspace = defaultKeyspace;
return this;
}
/// <summary>
/// Configures the socket options that are going to be used to create the connections to the hosts.
/// </summary>
public Builder WithSocketOptions(SocketOptions value)
{
_socketOptions = value;
return this;
}
public Builder WithPoolingOptions(PoolingOptions value)
{
_poolingOptions = value;
return this;
}
/// <summary>
/// Enables the use of SSL for the created Cluster. Calling this method will use default SSL options.
/// </summary>
/// <remarks>
/// If SSL is enabled, the driver will not connect to any
/// Cassandra nodes that doesn't have SSL enabled and it is strongly
/// advised to enable SSL on every Cassandra node if you plan on using
/// SSL in the driver. Note that SSL certificate common name(CN) on Cassandra node must match Cassandra node hostname.
/// </remarks>
/// <returns>this builder</returns>
public Builder WithSSL()
{
_sslOptions = new SSLOptions();
return this;
}
/// <summary>
/// Enables the use of SSL for the created Cluster using the provided options.
/// </summary>
/// <remarks>
/// If SSL is enabled, the driver will not connect to any
/// Cassandra nodes that doesn't have SSL enabled and it is strongly
/// advised to enable SSL on every Cassandra node if you plan on using
/// SSL in the driver. Note that SSL certificate common name(CN) on Cassandra node must match Cassandra node hostname.
/// </remarks>
/// <param name="sslOptions">SSL options to use.</param>
/// <returns>this builder</returns>
public Builder WithSSL(SSLOptions sslOptions)
{
_sslOptions = sslOptions;
return this;
}
/// <summary>
/// Configures the address translater to use for the new cluster.
/// </summary>
/// <remarks>
/// See <c>IAddressTranslater</c> for more detail on address translation,
/// but the default tanslater, <c>DefaultAddressTranslator</c>, should be
/// correct in most cases. If unsure, stick to the default.
/// </remarks>
/// <param name="addressTranslator">the translater to use.</param>
/// <returns>this Builder</returns>
public Builder WithAddressTranslator(IAddressTranslator addressTranslator)
{
_addressTranslator = addressTranslator;
return this;
}
/// <summary>
/// Build the cluster with the configured set of initial contact points and
/// policies. This is a shorthand for <c>Cluster.buildFrom(this)</c>.
/// </summary>
///
/// <returns>the newly build Cluster instance. </returns>
public Cluster Build()
{
return Cluster.BuildFrom(this);
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq.Expressions;
using Microsoft.AspNetCore.Mvc.ModelBinding;
using Microsoft.AspNetCore.Mvc.ViewFeatures;
using Microsoft.AspNetCore.Testing;
using Xunit;
namespace Microsoft.AspNetCore.Mvc.Rendering
{
public class HtmlHelperHiddenTest
{
public static TheoryData<object, string> HiddenWithAttributesData
{
get
{
var expected1 = @"<input baz=""HtmlEncode[[BazValue]]"" id=""HtmlEncode[[Property1]]"" " +
@"name=""HtmlEncode[[Property1]]"" type=""HtmlEncode[[hidden]]"" " +
@"value=""HtmlEncode[[ModelStateValue]]"" />";
var expected2 = @"<input foo-baz=""HtmlEncode[[BazValue]]"" id=""HtmlEncode[[Property1]]"" " +
@"name=""HtmlEncode[[Property1]]"" type=""HtmlEncode[[hidden]]"" " +
@"value=""HtmlEncode[[ModelStateValue]]"" />";
var htmlAttributes1 = new Dictionary<string, object>
{
{ "baz", "BazValue" },
{ "name", "-expression-" }, // overridden
};
var htmlAttributes2 = new
{
baz = "BazValue",
name = "-expression-", // overridden
};
var data = new TheoryData<object, string>
{
{ htmlAttributes1, expected1 },
{ htmlAttributes2, expected1 },
{ new Dictionary<string, object> { { "foo-baz", "BazValue" } }, expected2 },
{ new { foo_baz = "BazValue" }, expected2 }
};
return data;
}
}
[Fact]
public void HiddenWithByteArrayValue_GeneratesBase64EncodedValue()
{
// Arrange
var expected = @"<input id=""HtmlEncode[[ProductName]]"" name=""HtmlEncode[[ProductName]]"" type=""HtmlEncode[[hidden]]"" value=""HtmlEncode[[Fys1]]"" />";
var helper = DefaultTemplatesUtilities.GetHtmlHelper();
// Act
var result = helper.Hidden("ProductName", new byte[] { 23, 43, 53 }, htmlAttributes: null);
// Assert
Assert.Equal(expected, HtmlContentUtilities.HtmlContentToString(result));
}
[Theory]
[MemberData(nameof(HiddenWithAttributesData))]
public void HiddenWithArgumentValueAndAttributes_UsesArgumentValue(object attributes, string expected)
{
// Arrange
var helper = DefaultTemplatesUtilities.GetHtmlHelper(GetViewDataWithModelStateAndModelAndViewDataValues());
helper.ViewData.Model.Property1 = "should-not-be-used";
// Act
var result = helper.Hidden("Property1", "test", attributes);
// Assert
Assert.Equal(expected, HtmlContentUtilities.HtmlContentToString(result));
}
[Fact]
public void HiddenNotInTemplate_GetsValueFromPropertyOfViewDataEntry()
{
// Arrange
var expected = @"<input id=""HtmlEncode[[Prefix_Property1]]"" name=""HtmlEncode[[Prefix.Property1]]"" " +
@"type=""HtmlEncode[[hidden]]"" value=""HtmlEncode[[contained-view-data-value]]"" />";
var helper = DefaultTemplatesUtilities.GetHtmlHelper(GetViewDataWithNonNullModel());
helper.ViewData.Model.Property1 = "model-property1-value";
helper.ViewData["Prefix"] = new HiddenModel { Property1 = "contained-view-data-value" };
// Act
var html = helper.Hidden("Prefix.Property1", value: null, htmlAttributes: null);
// Assert
Assert.Equal(expected, HtmlContentUtilities.HtmlContentToString(html));
}
[Fact]
public void HiddenInTemplate_GetsValueFromPropertyOfViewDataEntry()
{
// Arrange
var expected = @"<input id=""HtmlEncode[[Prefix_Property1]]"" name=""HtmlEncode[[Prefix.Property1]]"" " +
@"type=""HtmlEncode[[hidden]]"" value=""HtmlEncode[[contained-view-data-value]]"" />";
var helper = DefaultTemplatesUtilities.GetHtmlHelper(GetViewDataWithNonNullModel());
helper.ViewData.TemplateInfo.HtmlFieldPrefix = "Prefix";
helper.ViewData.Model.Property1 = "model-property1-value";
helper.ViewData["Prefix"] = new HiddenModel { Property1 = "contained-view-data-value" };
// Act
var html = helper.Hidden("Property1", value: null, htmlAttributes: null);
// Assert
Assert.Equal(expected, HtmlContentUtilities.HtmlContentToString(html));
}
[Fact]
public void HiddenNotInTemplate_GetsValueFromViewDataEntry_EvenIfNull()
{
// Arrange
var expected = @"<input id=""HtmlEncode[[Property1]]"" name=""HtmlEncode[[Property1]]"" " +
@"type=""HtmlEncode[[hidden]]"" value="""" />";
var helper = DefaultTemplatesUtilities.GetHtmlHelper(GetViewDataWithNonNullModel());
helper.ViewData.Model.Property1 = "model-property1-value";
helper.ViewData["Property1"] = null;
// Act
var html = helper.Hidden("Property1", value: null, htmlAttributes: null);
// Assert
Assert.Equal(expected, HtmlContentUtilities.HtmlContentToString(html));
}
[Fact]
public void HiddenInTemplate_GetsValueFromViewDataEntry_EvenIfNull()
{
// Arrange
var expected = @"<input id=""HtmlEncode[[Prefix_Property1]]"" name=""HtmlEncode[[Prefix.Property1]]"" " +
@"type=""HtmlEncode[[hidden]]"" value="""" />";
var helper = DefaultTemplatesUtilities.GetHtmlHelper(GetViewDataWithNonNullModel());
helper.ViewData.TemplateInfo.HtmlFieldPrefix = "Prefix";
helper.ViewData.Model.Property1 = "model-property1-value";
helper.ViewData["Prefix.Property1"] = null;
// Act
var html = helper.Hidden("Property1", value: null, htmlAttributes: null);
// Assert
Assert.Equal(expected, HtmlContentUtilities.HtmlContentToString(html));
}
[Fact]
public void HiddenOverridesValueFromAttributesWithArgumentValue()
{
// Arrange
var expected = @"<input id=""HtmlEncode[[Property1]]"" name=""HtmlEncode[[Property1]]"" type=""HtmlEncode[[hidden]]"" value=""HtmlEncode[[explicit-value]]"" />";
var attributes = new { value = "attribute-value" };
var helper = DefaultTemplatesUtilities.GetHtmlHelper(GetViewDataWithNullModelAndNonNullViewData());
helper.ViewData.Clear();
// Act
var result = helper.Hidden("Property1", "explicit-value", attributes);
// Assert
Assert.Equal(expected, HtmlContentUtilities.HtmlContentToString(result));
}
[Fact]
public void HiddenWithArgumentValueAndNullModel_UsesArgumentValue()
{
// Arrange
var expected = @"<input id=""HtmlEncode[[Property1]]"" key=""HtmlEncode[[value]]"" name=""HtmlEncode[[Property1]]"" type=""HtmlEncode[[hidden]]"" " +
@"value=""HtmlEncode[[test]]"" />";
var attributes = new { key = "value" };
var helper = DefaultTemplatesUtilities.GetHtmlHelper(GetViewDataWithNullModelAndNonNullViewData());
// Act
var result = helper.Hidden("Property1", "test", attributes);
// Assert
Assert.Equal(expected, HtmlContentUtilities.HtmlContentToString(result));
}
[Fact]
public void HiddenWithNonNullValue_GeneratesExpectedValue()
{
// Arrange
var expected = @"<input data-key=""HtmlEncode[[value]]"" id=""HtmlEncode[[Property1]]"" name=""HtmlEncode[[Property1]]"" type=""HtmlEncode[[hidden]]"" " +
@"value=""HtmlEncode[[test]]"" />";
var attributes = new Dictionary<string, object> { { "data-key", "value" } };
var helper = DefaultTemplatesUtilities.GetHtmlHelper(GetViewDataWithNullModelAndNonNullViewData());
// Act
var result = helper.Hidden("Property1", "test", attributes);
// Assert
Assert.Equal(expected, HtmlContentUtilities.HtmlContentToString(result));
}
[Fact]
public void HiddenUsesValuesFromModelState_OverExplicitSpecifiedValueAndPropertyValue()
{
// Arrange
var expected = @"<input id=""HtmlEncode[[Property1]]"" name=""HtmlEncode[[Property1]]"" type=""HtmlEncode[[hidden]]"" value=""HtmlEncode[[ModelStateValue]]"" />";
var helper = DefaultTemplatesUtilities.GetHtmlHelper(GetViewDataWithModelStateAndModelAndViewDataValues());
helper.ViewData.Model.Property1 = "test-value";
// Act
var result = helper.Hidden("Property1", value: "explicit-value", htmlAttributes: new { value = "attribute-value" });
// Assert
Assert.Equal(expected, HtmlContentUtilities.HtmlContentToString(result));
}
[Fact]
public void HiddenUsesExplicitValue_IfModelStateDoesNotHaveProperty()
{
// Arrange
var expected = @"<input id=""HtmlEncode[[Property1]]"" name=""HtmlEncode[[Property1]]"" type=""HtmlEncode[[hidden]]"" value=""HtmlEncode[[explicit-value]]"" />";
var helper = DefaultTemplatesUtilities.GetHtmlHelper(GetViewDataWithModelStateAndModelAndViewDataValues());
helper.ViewData.ModelState.Clear();
helper.ViewData.Model.Property1 = "property-value";
// Act
var result = helper.Hidden("Property1", value: "explicit-value", htmlAttributes: new { value = "attribute-value" });
// Assert
Assert.Equal(expected, HtmlContentUtilities.HtmlContentToString(result));
}
[Fact]
public void HiddenUsesValueFromViewData_IfModelStateDoesNotHavePropertyAndExplicitValueIsNull()
{
// Arrange
var expected = @"<input id=""HtmlEncode[[Property1]]"" name=""HtmlEncode[[Property1]]"" type=""HtmlEncode[[hidden]]"" value=""HtmlEncode[[view-data-val]]"" />";
var helper = DefaultTemplatesUtilities.GetHtmlHelper(GetViewDataWithModelStateAndModelAndViewDataValues());
helper.ViewData.ModelState.Clear();
helper.ViewData.Model.Property1 = "property-value";
// Act
var result = helper.Hidden("Property1", value: null, htmlAttributes: new { value = "attribute-value" });
// Assert
Assert.Equal(expected, HtmlContentUtilities.HtmlContentToString(result));
}
[Fact]
public void HiddenNotInTemplate_GetsModelValue_IfModelStateAndViewDataEmpty()
{
// Arrange
var expected = @"<input id=""HtmlEncode[[Property1]]"" name=""HtmlEncode[[Property1]]"" type=""HtmlEncode[[hidden]]"" value=""HtmlEncode[[property-value]]"" />";
var helper = DefaultTemplatesUtilities.GetHtmlHelper(GetViewDataWithNonNullModel());
helper.ViewData.Model.Property1 = "property-value";
// Act
var result = helper.Hidden("Property1", value: null, htmlAttributes: new { value = "attribute-value" });
// Assert
Assert.Equal(expected, HtmlContentUtilities.HtmlContentToString(result));
}
[Fact]
public void HiddenInTemplate_GetsModelValue_IfModelStateAndViewDataEmpty()
{
// Arrange
var expected = @"<input id=""HtmlEncode[[Prefix_Property1]]"" name=""HtmlEncode[[Prefix.Property1]]"" " +
@"type=""HtmlEncode[[hidden]]"" value=""HtmlEncode[[property-value]]"" />";
var helper = DefaultTemplatesUtilities.GetHtmlHelper(GetViewDataWithNonNullModel());
helper.ViewData.TemplateInfo.HtmlFieldPrefix = "Prefix";
helper.ViewData.Model.Property1 = "property-value";
// Act
var html = helper.Hidden("Property1", value: null, htmlAttributes: new { value = "attribute-value" });
// Assert
Assert.Equal(expected, HtmlContentUtilities.HtmlContentToString(html));
}
[Fact]
public void HiddenNotInTemplate_DoesNotUseAttributeValue()
{
// Arrange
var expected = @"<input id=""HtmlEncode[[Property1]]"" name=""HtmlEncode[[Property1]]"" type=""HtmlEncode[[hidden]]"" value="""" />";
var helper = DefaultTemplatesUtilities.GetHtmlHelper(GetViewDataWithNonNullModel());
// Act
var result = helper.Hidden("Property1", value: null, htmlAttributes: new { value = "attribute-value" });
// Assert
Assert.Equal(expected, HtmlContentUtilities.HtmlContentToString(result));
}
[Fact]
public void HiddenInTemplate_DoesNotUseAttributeValue()
{
// Arrange
var expected = @"<input id=""HtmlEncode[[Prefix_Property1]]"" name=""HtmlEncode[[Prefix.Property1]]"" " +
@"type=""HtmlEncode[[hidden]]"" value="""" />";
var helper = DefaultTemplatesUtilities.GetHtmlHelper(GetViewDataWithNonNullModel());
helper.ViewData.TemplateInfo.HtmlFieldPrefix = "Prefix";
// Act
var html = helper.Hidden("Property1", value: null, htmlAttributes: new { value = "attribute-value" });
// Assert
Assert.Equal(expected, HtmlContentUtilities.HtmlContentToString(html));
}
[Fact]
public void HiddenNotInTemplate_GetsEmptyValue_IfPropertyIsNotFound()
{
// Arrange
var expected = @"<input baz=""HtmlEncode[[BazValue]]"" id=""HtmlEncode[[keyNotFound]]"" name=""HtmlEncode[[keyNotFound]]"" type=""HtmlEncode[[hidden]]"" " +
@"value="""" />";
var helper = DefaultTemplatesUtilities.GetHtmlHelper(GetViewDataWithModelStateAndModelAndViewDataValues());
var attributes = new Dictionary<string, object> { { "baz", "BazValue" } };
// Act
var result = helper.Hidden("keyNotFound", value: null, htmlAttributes: attributes);
// Assert
Assert.Equal(expected, HtmlContentUtilities.HtmlContentToString(result));
}
[Fact]
public void HiddenInTemplate_GetsEmptyValue_IfPropertyIsNotFound()
{
// Arrange
var expected = @"<input id=""HtmlEncode[[Prefix_keyNotFound]]"" name=""HtmlEncode[[Prefix.keyNotFound]]"" " +
@"type=""HtmlEncode[[hidden]]"" value="""" />";
var helper = DefaultTemplatesUtilities.GetHtmlHelper(GetViewDataWithModelStateAndModelAndViewDataValues());
helper.ViewData.TemplateInfo.HtmlFieldPrefix = "Prefix";
// Act
var html = helper.Hidden("keyNotFound", value: null, htmlAttributes: null);
// Assert
Assert.Equal(expected, HtmlContentUtilities.HtmlContentToString(html));
}
[Fact]
public void HiddenInTemplate_WithExplicitValue_GeneratesExpectedValue()
{
// Arrange
var expected = @"<input id=""HtmlEncode[[MyPrefix_Property1]]"" name=""HtmlEncode[[MyPrefix.Property1]]"" type=""HtmlEncode[[hidden]]"" " +
@"value=""HtmlEncode[[PropValue]]"" />";
var helper = DefaultTemplatesUtilities.GetHtmlHelper(GetViewDataWithModelStateAndModelAndViewDataValues());
helper.ViewContext.ViewData.TemplateInfo.HtmlFieldPrefix = "MyPrefix";
// Act
var result = helper.Hidden("Property1", "PropValue", htmlAttributes: null);
// Assert
Assert.Equal(expected, HtmlContentUtilities.HtmlContentToString(result));
}
[Fact]
public void HiddenInTemplate_WithExplicitValueAndEmptyName_GeneratesExpectedValue()
{
// Arrange
var expected = @"<input id=""HtmlEncode[[MyPrefix]]"" name=""HtmlEncode[[MyPrefix]]"" type=""HtmlEncode[[hidden]]"" value=""HtmlEncode[[fooValue]]"" />";
var helper = DefaultTemplatesUtilities.GetHtmlHelper(GetViewDataWithModelStateAndModelAndViewDataValues());
helper.ViewContext.ViewData.TemplateInfo.HtmlFieldPrefix = "MyPrefix";
// Act
var result = helper.Hidden(string.Empty, "fooValue", htmlAttributes: null);
// Assert
Assert.Equal(expected, HtmlContentUtilities.HtmlContentToString(result));
}
[Fact]
public void HiddenInTemplate_UsesPrefixName_ToLookupPropertyValueInModelState()
{
// Arrange
var expected = @"<input id=""HtmlEncode[[MyPrefix$Property1]]"" name=""HtmlEncode[[MyPrefix.Property1]]"" type=""HtmlEncode[[hidden]]"" " +
@"value=""HtmlEncode[[modelstate-with-prefix]]"" />";
var helper = DefaultTemplatesUtilities.GetHtmlHelper(
GetViewDataWithModelStateAndModelAndViewDataValues(),
idAttributeDotReplacement: "$");
helper.ViewContext.ViewData.TemplateInfo.HtmlFieldPrefix = "MyPrefix";
helper.ViewData.ModelState.Clear();
helper.ViewData.ModelState.SetModelValue(
"Property1",
"modelstate-without-prefix",
"modelstate-without-prefix");
helper.ViewData.ModelState.SetModelValue(
"MyPrefix.Property1",
"modelstate-with-prefix",
"modelstate-with-prefix");
helper.ViewData.ModelState.SetModelValue(
"MyPrefix$Property1",
"modelstate-with-iddotreplacement",
"modelstate-with-iddotreplacement");
// Act
var result = helper.Hidden("Property1", "explicit-value", htmlAttributes: null);
// Assert
Assert.Equal(expected, HtmlContentUtilities.HtmlContentToString(result));
}
[Fact]
public void HiddenInTemplate_UsesPrefixNameToLookupPropertyValueInViewData()
{
// Arrange
var expected = @"<input id=""HtmlEncode[[MyPrefix$Property1]]"" name=""HtmlEncode[[MyPrefix.Property1]]"" type=""HtmlEncode[[hidden]]"" " +
@"value=""HtmlEncode[[vdd-with-prefix]]"" />";
var helper = DefaultTemplatesUtilities.GetHtmlHelper(
GetViewDataWithModelStateAndModelAndViewDataValues(),
idAttributeDotReplacement: "$");
helper.ViewContext.ViewData.TemplateInfo.HtmlFieldPrefix = "MyPrefix";
helper.ViewData.ModelState.Clear();
helper.ViewData.Clear();
helper.ViewData.Add("Property1", "vdd-without-prefix");
helper.ViewData.Add("MyPrefix.Property1", "vdd-with-prefix");
helper.ViewData.Add("MyPrefix$Property1", "vdd-with-iddotreplacement");
// Act
var result = helper.Hidden("Property1", value: null, htmlAttributes: null);
// Assert
Assert.Equal(expected, HtmlContentUtilities.HtmlContentToString(result));
}
[Fact]
public void HiddenWithEmptyNameAndPrefixThrows()
{
// Arrange
var helper = DefaultTemplatesUtilities.GetHtmlHelper("model-value");
var attributes = new Dictionary<string, object>
{
{ "class", "some-class"}
};
var expected = "The name of an HTML field cannot be null or empty. Instead use methods " +
"Microsoft.AspNetCore.Mvc.Rendering.IHtmlHelper.Editor or Microsoft.AspNetCore.Mvc.Rendering." +
"IHtmlHelper`1.EditorFor with a non-empty htmlFieldName argument value.";
// Act and Assert
ExceptionAssert.ThrowsArgument(
() => helper.Hidden(expression: string.Empty, value: null, htmlAttributes: attributes),
"expression",
expected);
}
[Fact]
public void HiddenWithEmptyNameAndPrefix_DoesNotThrow_WithNameAttribute()
{
// Arrange
var expected = @"<input class=""HtmlEncode[[some-class]]"" name=""HtmlEncode[[-expression-]]"" " +
@"type=""HtmlEncode[[hidden]]"" value=""HtmlEncode[[model-value]]"" />";
var helper = DefaultTemplatesUtilities.GetHtmlHelper("model-value");
var attributes = new Dictionary<string, object>
{
{ "class", "some-class"},
{ "name", "-expression-" },
};
// Act
var result = helper.Hidden(expression: string.Empty, value: null, htmlAttributes: attributes);
// Assert
Assert.Equal(expected, HtmlContentUtilities.HtmlContentToString(result));
}
[Fact]
public void HiddenWithViewDataErrors_GeneratesExpectedValue()
{
// Arrange
var expected = @"<input baz=""HtmlEncode[[BazValue]]"" class=""HtmlEncode[[some-class input-validation-error]]"" id=""HtmlEncode[[Property1]]""" +
@" name=""HtmlEncode[[Property1]]"" type=""HtmlEncode[[hidden]]"" value=""HtmlEncode[[ModelStateValue]]"" />";
var helper = DefaultTemplatesUtilities.GetHtmlHelper(GetViewDataWithErrors());
var attributes = new Dictionary<string, object>
{
{ "baz", "BazValue" },
{ "class", "some-class"}
};
// Act
var result = helper.Hidden("Property1", value: null, htmlAttributes: attributes);
// Assert
Assert.Equal(expected, HtmlContentUtilities.HtmlContentToString(result));
}
[Fact]
public void HiddenGeneratesUnobtrusiveValidation()
{
// Arrange
var requiredMessage = new RequiredAttribute().FormatErrorMessage("Property2");
var expected =
$@"<input data-val=""HtmlEncode[[true]]"" data-val-required=""HtmlEncode[[{requiredMessage}]]"" " +
@"id=""HtmlEncode[[Property2]]"" name=""HtmlEncode[[Property2]]"" type=""HtmlEncode[[hidden]]"" value="""" />";
var helper = DefaultTemplatesUtilities.GetHtmlHelper(GetViewDataWithModelStateAndModelAndViewDataValues());
// Act
var result = helper.Hidden("Property2", value: null, htmlAttributes: null);
// Assert
Assert.Equal(expected, HtmlContentUtilities.HtmlContentToString(result));
}
public static IEnumerable<object[]> HiddenWithComplexExpressions_UsesValueFromViewDataData
{
get
{
yield return new object[]
{
"Property3[height]",
@"<input data-test=""HtmlEncode[[val]]"" id=""HtmlEncode[[Property3_height_]]"" name=""HtmlEncode[[Property3[height]]]"" type=""HtmlEncode[[hidden]]"" " +
@"value=""HtmlEncode[[Prop3Value]]"" />",
};
yield return new object[]
{
"Property4.Property5",
@"<input data-test=""HtmlEncode[[val]]"" id=""HtmlEncode[[Property4_Property5]]"" name=""HtmlEncode[[Property4.Property5]]"" " +
@"type=""HtmlEncode[[hidden]]"" value=""HtmlEncode[[Prop5Value]]"" />",
};
yield return new object[]
{
"Property4.Property6[0]",
@"<input data-test=""HtmlEncode[[val]]"" id=""HtmlEncode[[Property4_Property6_0_]]"" name=""HtmlEncode[[Property4.Property6[0]]]"" " +
@"type=""HtmlEncode[[hidden]]"" value=""HtmlEncode[[Prop6Value]]"" />",
};
}
}
[Theory]
[MemberData(nameof(HiddenWithComplexExpressions_UsesValueFromViewDataData))]
public void HiddenWithComplexExpressions_UsesValueFromViewData(string expression, string expected)
{
// Arrange
var viewData = GetViewDataWithModelStateAndModelAndViewDataValues();
viewData["Property3[height]"] = "Prop3Value";
viewData["Property4.Property5"] = "Prop5Value";
viewData["Property4.Property6[0]"] = "Prop6Value";
var helper = DefaultTemplatesUtilities.GetHtmlHelper(viewData);
var attributes = new Dictionary<string, object> { { "data-test", "val" } };
// Act
var result = helper.Hidden(expression, value: null, htmlAttributes: attributes);
// Assert
Assert.Equal(expected, HtmlContentUtilities.HtmlContentToString(result));
}
public static IEnumerable<object[]> HiddenWithComplexExpressions_UsesIdDotSeparatorData
{
get
{
yield return new object[]
{
"Property4.Property5",
@"<input data-test=""HtmlEncode[[val]]"" id=""HtmlEncode[[Property4$$Property5]]"" name=""HtmlEncode[[Property4.Property5]]"" " +
@"type=""HtmlEncode[[hidden]]"" value=""HtmlEncode[[Prop5Value]]"" />",
};
yield return new object[]
{
"Property4.Property6[0]",
@"<input data-test=""HtmlEncode[[val]]"" id=""HtmlEncode[[Property4$$Property6$$0$$]]"" name=""HtmlEncode[[Property4.Property6[0]]]"" " +
@"type=""HtmlEncode[[hidden]]"" value=""HtmlEncode[[Prop6Value]]"" />",
};
}
}
[Theory]
[MemberData(nameof(HiddenWithComplexExpressions_UsesIdDotSeparatorData))]
public void HiddenWithComplexExpressions_UsesIdDotSeparator(string expression, string expected)
{
// Arrange
var viewData = GetViewDataWithModelStateAndModelAndViewDataValues();
viewData["Property3[height]"] = "Prop3Value";
viewData["Property4.Property5"] = "Prop5Value";
viewData["Property4.Property6[0]"] = "Prop6Value";
var helper = DefaultTemplatesUtilities.GetHtmlHelper(viewData, idAttributeDotReplacement: "$$");
var attributes = new Dictionary<string, object> { { "data-test", "val" } };
// Act
var result = helper.Hidden(expression, value: null, htmlAttributes: attributes);
// Assert
Assert.Equal(expected, HtmlContentUtilities.HtmlContentToString(result));
}
[Fact]
public void HiddenForWithByteArrayValue_GeneratesBase64EncodedValue()
{
// Arrange
var expected = @"<input id=""HtmlEncode[[Bytes]]"" name=""HtmlEncode[[Bytes]]"" type=""HtmlEncode[[hidden]]"" value=""HtmlEncode[[Fys1]]"" />";
var helper = DefaultTemplatesUtilities.GetHtmlHelper(GetViewDataWithModelStateAndModelAndViewDataValues());
helper.ViewData.Model.Bytes = new byte[] { 23, 43, 53 };
// Act
var result = helper.HiddenFor(m => m.Bytes, htmlAttributes: null);
// Assert
Assert.Equal(expected, HtmlContentUtilities.HtmlContentToString(result));
}
[Theory]
[MemberData(nameof(HiddenWithAttributesData))]
public void HiddenForWithAttributes_GeneratesExpectedValue(object htmlAttributes, string expected)
{
// Arrange
var helper = DefaultTemplatesUtilities.GetHtmlHelper(GetViewDataWithModelStateAndModelAndViewDataValues());
helper.ViewData.Model.Property1 = "test";
// Act
var result = helper.HiddenFor(m => m.Property1, htmlAttributes);
// Assert
Assert.Equal(expected, HtmlContentUtilities.HtmlContentToString(result));
}
[Fact]
public void HiddenFor_UsesModelStateValueOverPropertyValue()
{
// Arrange
var expected = @"<input id=""HtmlEncode[[Property1]]"" name=""HtmlEncode[[Property1]]"" type=""HtmlEncode[[hidden]]"" value=""HtmlEncode[[ModelStateValue]]"" />";
var helper = DefaultTemplatesUtilities.GetHtmlHelper(GetViewDataWithModelStateAndModelAndViewDataValues());
helper.ViewData.Model.Property1 = "DefaultValue";
// Act
var result = helper.HiddenFor(m => m.Property1, htmlAttributes: null);
// Assert
Assert.Equal(expected, HtmlContentUtilities.HtmlContentToString(result));
}
[Fact]
public void HiddenFor_UsesPropertyValueIfModelStateDoesNotHaveKey()
{
// Arrange
var expected = @"<input id=""HtmlEncode[[Property1]]"" name=""HtmlEncode[[Property1]]"" type=""HtmlEncode[[hidden]]"" value=""HtmlEncode[[PropertyValue]]"" />";
var helper = DefaultTemplatesUtilities.GetHtmlHelper(GetViewDataWithModelStateAndModelAndViewDataValues());
helper.ViewData.ModelState.Clear();
helper.ViewData.Model.Property1 = "PropertyValue";
// Act
var result = helper.HiddenFor(m => m.Property1, htmlAttributes: null);
// Assert
Assert.Equal(expected, HtmlContentUtilities.HtmlContentToString(result));
}
[Fact]
public void HiddenForDoesNotUseValueFromViewDataDictionary_IfModelStateAndPropertyValueIsNull()
{
// Arrange
var expected = @"<input id=""HtmlEncode[[Property1]]"" name=""HtmlEncode[[Property1]]"" type=""HtmlEncode[[hidden]]"" value="""" />";
var helper = DefaultTemplatesUtilities.GetHtmlHelper(GetViewDataWithModelStateAndModelAndViewDataValues());
helper.ViewData.Model.Property1 = null;
helper.ViewData.ModelState.Clear();
// Act
var result = helper.HiddenFor(m => m.Property1, htmlAttributes: null);
// Assert
Assert.Equal(expected, HtmlContentUtilities.HtmlContentToString(result));
}
[Fact]
public void HiddenForWithAttributesDictionaryAndNullModel_GeneratesExpectedValue()
{
// Arrange
var expected = @"<input id=""HtmlEncode[[Property1]]"" key=""HtmlEncode[[value]]"" name=""HtmlEncode[[Property1]]"" type=""HtmlEncode[[hidden]]"" value="""" />";
var helper = DefaultTemplatesUtilities.GetHtmlHelper(GetViewDataWithNullModelAndNonNullViewData());
var attributes = new Dictionary<string, object> { { "key", "value" } };
// Act
var result = helper.HiddenFor(m => m.Property1, attributes);
// Assert
Assert.Equal(expected, HtmlContentUtilities.HtmlContentToString(result));
}
// This test ensures that specifying a the prefix does not affect the expression result.
[Fact]
public void HiddenForInTemplate_GeneratesExpectedValue()
{
// Arrange
var expected = @"<input id=""HtmlEncode[[MyPrefix_Property1]]"" name=""HtmlEncode[[MyPrefix.Property1]]"" type=""HtmlEncode[[hidden]]"" " +
@"value=""HtmlEncode[[propValue]]"" />";
var helper = DefaultTemplatesUtilities.GetHtmlHelper(GetViewDataWithModelStateAndModelAndViewDataValues());
helper.ViewData.Model.Property1 = "propValue";
helper.ViewContext.ViewData.TemplateInfo.HtmlFieldPrefix = "MyPrefix";
// Act
var result = helper.HiddenFor(m => m.Property1, htmlAttributes: null);
// Assert
Assert.Equal(expected, HtmlContentUtilities.HtmlContentToString(result));
}
[Fact]
public void HiddenForInTemplate_UsesPrefixWhenLookingUpModelStateValues()
{
// Arrange
var expected = @"<input id=""HtmlEncode[[MyPrefix$Property1]]"" name=""HtmlEncode[[MyPrefix.Property1]]"" type=""HtmlEncode[[hidden]]"" " +
@"value=""HtmlEncode[[modelstate-with-prefix]]"" />";
var helper = DefaultTemplatesUtilities.GetHtmlHelper(
GetViewDataWithModelStateAndModelAndViewDataValues(),
"$");
helper.ViewData.Model.Property1 = "propValue";
helper.ViewContext.ViewData.TemplateInfo.HtmlFieldPrefix = "MyPrefix";
helper.ViewData.ModelState.Clear();
helper.ViewData.ModelState.SetModelValue(
"Property1",
"modelstate-without-prefix",
"modelstate-without-prefix");
helper.ViewData.ModelState.SetModelValue(
"MyPrefix.Property1",
"modelstate-with-prefix",
"modelstate-with-prefix");
helper.ViewData.ModelState.SetModelValue(
"MyPrefix$Property1",
"modelstate-with-iddotreplacement",
"modelstate-with-iddotreplacement");
// Act
var result = helper.HiddenFor(m => m.Property1, htmlAttributes: null);
// Assert
Assert.Equal(expected, HtmlContentUtilities.HtmlContentToString(result));
}
[Fact]
public void HiddenForWithViewDataErrors_GeneratesExpectedValue()
{
// Arrange
var expected = @"<input baz=""HtmlEncode[[BazValue]]"" class=""HtmlEncode[[some-class input-validation-error]]"" id=""HtmlEncode[[Property1]]"" " +
@"name=""HtmlEncode[[Property1]]"" type=""HtmlEncode[[hidden]]"" value=""HtmlEncode[[ModelStateValue]]"" />";
var helper = DefaultTemplatesUtilities.GetHtmlHelper(GetViewDataWithErrors());
var attributes = new Dictionary<string, object>
{
{ "baz", "BazValue" },
{ "class", "some-class"}
};
// Act
var result = helper.HiddenFor(m => m.Property1, attributes);
// Assert
Assert.Equal(expected, HtmlContentUtilities.HtmlContentToString(result));
}
[Fact]
public void HiddenFor_GeneratesUnobtrusiveValidationAttributes()
{
// Arrange
var requiredMessage = ValidationAttributeUtil.GetRequiredErrorMessage("Property2");
var expected =
$@"<input data-val=""HtmlEncode[[true]]"" data-val-required=""HtmlEncode[[{requiredMessage}]]"" " +
@"id=""HtmlEncode[[Property2]]"" name=""HtmlEncode[[Property2]]"" type=""HtmlEncode[[hidden]]"" value="""" />";
var helper = DefaultTemplatesUtilities.GetHtmlHelper(GetViewDataWithErrors());
// Act
var result = helper.HiddenFor(m => m.Property2, htmlAttributes: null);
// Assert
Assert.Equal(expected, HtmlContentUtilities.HtmlContentToString(result));
}
public static TheoryData HiddenFor_UsesPropertyValueIfModelStateDoesNotContainValueData
{
get
{
var localModel = new HiddenModel();
localModel.Property4.Property5 = "local-value";
return new TheoryData<Expression<Func<HiddenModel, string>>, string>
{
{
model => model.Property3["key"],
@"<input data-val=""HtmlEncode[[true]]"" id=""HtmlEncode[[Property3_key_]]"" name=""HtmlEncode[[Property3[key]]]"" " +
@"type=""HtmlEncode[[hidden]]"" value=""HtmlEncode[[ModelProp3Val]]"" />"
},
{
model => model.Property4.Property5,
@"<input data-val=""HtmlEncode[[true]]"" id=""HtmlEncode[[Property4_Property5]]"" name=""HtmlEncode[[Property4.Property5]]"" " +
@"type=""HtmlEncode[[hidden]]"" value=""HtmlEncode[[ModelProp5Val]]"" />"
},
{
model => model.Property4.Property6[0],
@"<input data-val=""HtmlEncode[[true]]"" id=""HtmlEncode[[Property4_Property6_0_]]"" name=""HtmlEncode[[Property4.Property6[0]]]"" " +
@"type=""HtmlEncode[[hidden]]"" value=""HtmlEncode[[ModelProp6Val]]"" />"
},
{
model => localModel.Property4.Property5,
@"<input data-val=""HtmlEncode[[true]]"" id=""HtmlEncode[[localModel_Property4_Property5]]"" " +
@"name=""HtmlEncode[[localModel.Property4.Property5]]"" type=""HtmlEncode[[hidden]]"" value=""HtmlEncode[[local-value]]"" />"
}
};
}
}
[Theory]
[MemberData(nameof(HiddenFor_UsesPropertyValueIfModelStateDoesNotContainValueData))]
public void HiddenFor_UsesPropertyValueIfModelStateDoesNotContainValue(
Expression<Func<HiddenModel, string>> expression,
string expected)
{
// Arrange
var viewData = GetViewDataWithModelStateAndModelAndViewDataValues();
viewData["Property3[key]"] = "Prop3Val";
viewData["Property4.Property5"] = "Prop4Val";
viewData["Property4.Property6[0]"] = "Prop6Val";
viewData.Model.Property3["key"] = "ModelProp3Val";
viewData.Model.Property4.Property5 = "ModelProp5Val";
viewData.Model.Property4.Property6.Add("ModelProp6Val");
var helper = DefaultTemplatesUtilities.GetHtmlHelper(viewData);
var attributes = new Dictionary<string, object>
{
{ "data-val", "true" },
{ "value", "attr-val" }
};
// Act
var result = helper.HiddenFor(expression, attributes);
// Assert
Assert.Equal(expected, HtmlContentUtilities.HtmlContentToString(result));
}
public static TheoryData HiddenFor_UsesModelStateValueForComplexExpressionsData
{
get
{
return new TheoryData<Expression<Func<HiddenModel, string>>, string>
{
{
model => model.Property3["key"],
@"<input data-val=""HtmlEncode[[true]]"" id=""HtmlEncode[[pre_Property3_key_]]"" name=""HtmlEncode[[pre.Property3[key]]]"" " +
@"type=""HtmlEncode[[hidden]]"" value=""HtmlEncode[[Prop3Val]]"" />"
},
{
model => model.Property4.Property5,
@"<input data-val=""HtmlEncode[[true]]"" id=""HtmlEncode[[pre_Property4_Property5]]"" name=""HtmlEncode[[pre.Property4.Property5]]"" " +
@"type=""HtmlEncode[[hidden]]"" value=""HtmlEncode[[Prop5Val]]"" />"
},
{
model => model.Property4.Property6[0],
@"<input data-val=""HtmlEncode[[true]]"" id=""HtmlEncode[[pre_Property4_Property6_0_]]"" " +
@"name=""HtmlEncode[[pre.Property4.Property6[0]]]"" type=""HtmlEncode[[hidden]]"" value=""HtmlEncode[[Prop6Val]]"" />"
}
};
}
}
[Theory]
[MemberData(nameof(HiddenFor_UsesModelStateValueForComplexExpressionsData))]
public void HiddenForInTemplate_UsesModelStateValueForComplexExpressions(
Expression<Func<HiddenModel, string>> expression,
string expected)
{
// Arrange
var viewData = GetViewDataWithNullModelAndNonNullViewData();
viewData.ModelState.SetModelValue("pre.Property3[key]", "Prop3Val", "Prop3Val");
viewData.ModelState.SetModelValue("pre.Property4.Property5", "Prop5Val", "Prop5Val");
viewData.ModelState.SetModelValue("pre.Property4.Property6[0]", "Prop6Val", "Prop6Val");
var helper = DefaultTemplatesUtilities.GetHtmlHelper(viewData);
viewData.TemplateInfo.HtmlFieldPrefix = "pre";
var attributes = new { data_val = "true", value = "attr-val" };
// Act
var result = helper.HiddenFor(expression, attributes);
// Assert
Assert.Equal(expected, HtmlContentUtilities.HtmlContentToString(result));
}
[Fact]
public void HiddenFor_DoesNotUseAttributeValue()
{
// Arrange
var expected = @"<input id=""HtmlEncode[[Property1]]"" name=""HtmlEncode[[Property1]]"" type=""HtmlEncode[[hidden]]"" value="""" />";
var helper = DefaultTemplatesUtilities.GetHtmlHelper(GetViewDataWithNullModelAndNonNullViewData());
var attributes = new Dictionary<string, object>
{
{ "value", "AttrValue" }
};
// Act
var result = helper.HiddenFor(m => m.Property1, attributes);
// Assert
Assert.Equal(expected, HtmlContentUtilities.HtmlContentToString(result));
}
[Fact]
public void Hidden_UsesSpecifiedExpression()
{
// Arrange
var metadataProvider = new EmptyModelMetadataProvider();
var helper = DefaultTemplatesUtilities.GetHtmlHelper(new ViewDataDictionary<TestModel>(metadataProvider));
helper.ViewContext.ClientValidationEnabled = false;
helper.ViewData.Model = new TestModel { Property1 = "propValue" };
// Act
var hiddenResult = helper.Hidden("Property1");
// Assert
Assert.Equal(
"<input id=\"HtmlEncode[[Property1]]\" name=\"HtmlEncode[[Property1]]\" type=\"HtmlEncode[[hidden]]\" value=\"HtmlEncode[[propValue]]\" />",
HtmlContentUtilities.HtmlContentToString(hiddenResult));
}
[Fact]
public void HiddenFor_UsesSpecifiedExpression()
{
// Arrange
var metadataProvider = new EmptyModelMetadataProvider();
var helper = DefaultTemplatesUtilities.GetHtmlHelper(new ViewDataDictionary<TestModel>(metadataProvider));
helper.ViewContext.ClientValidationEnabled = false;
helper.ViewData.Model = new TestModel { Property1 = "propValue" };
// Act
var hiddenForResult = helper.HiddenFor(m => m.Property1);
// Assert
Assert.Equal(
"<input id=\"HtmlEncode[[Property1]]\" name=\"HtmlEncode[[Property1]]\" type=\"HtmlEncode[[hidden]]\" value=\"HtmlEncode[[propValue]]\" />",
HtmlContentUtilities.HtmlContentToString(hiddenForResult));
}
[Fact]
public void Hidden_UsesSpecifiedValue()
{
// Arrange
var metadataProvider = new EmptyModelMetadataProvider();
var helper = DefaultTemplatesUtilities.GetHtmlHelper(new ViewDataDictionary<TestModel>(metadataProvider));
helper.ViewContext.ClientValidationEnabled = false;
helper.ViewData.Model = new TestModel { Property1 = "propValue" };
// Act
var hiddenResult = helper.Hidden("Property1", value: "myvalue");
// Assert
Assert.Equal(
"<input id=\"HtmlEncode[[Property1]]\" name=\"HtmlEncode[[Property1]]\" type=\"HtmlEncode[[hidden]]\" value=\"HtmlEncode[[myvalue]]\" />",
HtmlContentUtilities.HtmlContentToString(hiddenResult));
}
private static ViewDataDictionary<HiddenModel> GetViewDataWithNullModelAndNonNullViewData()
{
return new ViewDataDictionary<HiddenModel>(new EmptyModelMetadataProvider())
{
["Property1"] = "view-data-val",
};
}
private static ViewDataDictionary<HiddenModel> GetViewDataWithNonNullModel()
{
var viewData = new ViewDataDictionary<HiddenModel>(new EmptyModelMetadataProvider())
{
Model = new HiddenModel(),
};
return viewData;
}
private static ViewDataDictionary<HiddenModel> GetViewDataWithModelStateAndModelAndViewDataValues()
{
var viewData = GetViewDataWithNonNullModel();
viewData["Property1"] = "view-data-val";
viewData.ModelState.SetModelValue("Property1", "ModelStateValue", "ModelStateValue");
return viewData;
}
private static ViewDataDictionary<HiddenModel> GetViewDataWithErrors()
{
var viewData = GetViewDataWithModelStateAndModelAndViewDataValues();
viewData.ModelState.AddModelError("Property1", "error 1");
viewData.ModelState.AddModelError("Property1", "error 2");
return viewData;
}
public class HiddenModel
{
public string Property1 { get; set; }
public byte[] Bytes { get; set; }
[Required]
public string Property2 { get; set; }
public Dictionary<string, string> Property3 { get; } = new Dictionary<string, string>();
public NestedClass Property4 { get; } = new NestedClass();
}
public class NestedClass
{
public string Property5 { get; set; }
public List<string> Property6 { get; } = new List<string>();
}
private class TestModel
{
public string Property1 { get; set; }
}
}
}
| |
// ----------------------------------------------------------------------------------
//
// Copyright Microsoft Corporation
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ----------------------------------------------------------------------------------
using Microsoft.Azure.Commands.Common.Authentication.Abstractions;
using Microsoft.Azure.Commands.Management.Storage.Models;
using Microsoft.Azure.Management.Compute.Models;
using Microsoft.Azure.Management.Storage.Version2017_10_01;
using Microsoft.Azure.Management.Storage.Version2017_10_01.Models;
using Microsoft.WindowsAzure.Commands.Common.Storage;
using Microsoft.WindowsAzure.Commands.Storage.Adapters;
using Microsoft.WindowsAzure.Commands.Utilities.Common;
using Microsoft.WindowsAzure.Storage;
using Microsoft.WindowsAzure.Storage.Auth;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Management.Automation;
using System.Text;
using System.Xml;
using System.Xml.Linq;
using System.Xml.Serialization;
namespace Microsoft.Azure.Commands.Compute.Common
{
public static class DiagnosticsHelper
{
private static string EncodedXmlCfg = "xmlCfg";
private static string WadCfg = "WadCfg";
private static string WadCfgBlob = "WadCfgBlob";
private static string StorageType = "StorageType";
private static string StorageAccount = "storageAccount";
private static string Path = "path";
private static string ExpandResourceDirectory = "expandResourceDirectory";
private static string LocalResourceDirectory = "localResourceDirectory";
private static string StorageAccountNameTag = "storageAccountName";
private static string StorageAccountKeyTag = "storageAccountKey";
private static string StorageAccountEndPointTag = "storageAccountEndPoint";
private static string StorageAccountSASTokenTag = "storageAccountSasToken";
public static string XmlNamespace = "http://schemas.microsoft.com/ServiceHosting/2010/10/DiagnosticsConfiguration";
public static string DiagnosticsConfigurationElemStr = "DiagnosticsConfiguration";
public static string DiagnosticMonitorConfigurationElemStr = "DiagnosticMonitorConfiguration";
public static string PublicConfigElemStr = "PublicConfig";
public static string PrivateConfigElemStr = "PrivateConfig";
public static string StorageAccountElemStr = "StorageAccount";
public static string PrivConfNameAttr = "name";
public static string PrivConfKeyAttr = "key";
public static string PrivConfEndpointAttr = "endpoint";
public static string PrivConfSasKeyAttr = "sasToken";
public static string MetricsElemStr = "Metrics";
public static string MetricsResourceIdAttr = "resourceId";
public static string EventHubElemStr = "EventHub";
public static string EventHubUrlAttr = "Url";
public static string EventHubSharedAccessKeyNameAttr = "SharedAccessKeyName";
public static string EventHubSharedAccessKeyAttr = "SharedAccessKey";
private enum WadStorageType
{
Table,
Blob,
TableAndBlob
}
public enum ConfigFileType
{
Unknown,
Json,
Xml
}
public static ConfigFileType GetConfigFileType(string configurationPath)
{
if (!string.IsNullOrEmpty(configurationPath))
{
try
{
XmlDocument doc = new XmlDocument();
doc.Load(configurationPath);
return ConfigFileType.Xml;
}
catch (XmlException)
{ }
try
{
JsonConvert.DeserializeObject(File.ReadAllText(configurationPath));
return ConfigFileType.Json;
}
catch (JsonReaderException)
{ }
}
return ConfigFileType.Unknown;
}
public static Hashtable GetPublicDiagnosticsConfigurationFromFile(string configurationPath,
string storageAccountName, string resourceId, Cmdlet cmdlet)
{
switch (GetConfigFileType(configurationPath))
{
case ConfigFileType.Xml:
return GetPublicConfigFromXmlFile(configurationPath, storageAccountName, resourceId, cmdlet);
case ConfigFileType.Json:
return GetPublicConfigFromJsonFile(configurationPath, storageAccountName, resourceId, cmdlet);
default:
throw new ArgumentException(Properties.Resources.DiagnosticsExtensionInvalidConfigFileFormat);
}
}
private static Hashtable GetPublicConfigFromXmlFile(string configurationPath, string storageAccountName, string resourceId, Cmdlet cmdlet)
{
var doc = XDocument.Load(configurationPath);
var wadCfgElement = doc.Descendants().FirstOrDefault(d => d.Name.LocalName == WadCfg);
var wadCfgBlobElement = doc.Descendants().FirstOrDefault(d => d.Name.LocalName == WadCfgBlob);
if (wadCfgElement == null && wadCfgBlobElement == null)
{
throw new ArgumentException(Properties.Resources.DiagnosticsExtensionIaaSConfigElementNotDefinedInXml);
}
if (wadCfgElement != null)
{
AutoFillMetricsConfig(wadCfgElement, resourceId, cmdlet);
}
string originalConfiguration = wadCfgElement != null ? wadCfgElement.ToString() : wadCfgBlobElement.ToString();
string encodedConfiguration = Convert.ToBase64String(Encoding.UTF8.GetBytes(wadCfgElement.ToString().ToCharArray()));
// Now extract the local resource directory element
var node = doc.Descendants().FirstOrDefault(e => e.Name.LocalName == "LocalResourceDirectory");
string localDirectory = (node != null && node.Attribute(Path) != null) ? node.Attribute(Path).Value : null;
string localDirectoryExpand = (node != null && node.Attribute("expandEnvironment") != null)
? node.Attribute("expandEnvironment").Value
: null;
if (localDirectoryExpand == "0")
{
localDirectoryExpand = "false";
}
if (localDirectoryExpand == "1")
{
localDirectoryExpand = "true";
}
var hashTable = new Hashtable();
hashTable.Add(EncodedXmlCfg, encodedConfiguration);
hashTable.Add(StorageAccount, storageAccountName);
if (!string.IsNullOrEmpty(localDirectory))
{
var localDirectoryHashTable = new Hashtable();
localDirectoryHashTable.Add(Path, localDirectory);
localDirectoryHashTable.Add(ExpandResourceDirectory, localDirectoryExpand);
hashTable.Add(LocalResourceDirectory, localDirectoryHashTable);
}
var storageTypeElement = doc.Descendants().FirstOrDefault(d => d.Name.LocalName == StorageType);
if (storageTypeElement != null)
{
string storageType = storageTypeElement.Value;
WadStorageType wadStorageType;
if (!Enum.TryParse<WadStorageType>(storageType, out wadStorageType))
{
throw new ArgumentException(StorageType);
}
hashTable.Add(StorageType, storageTypeElement.Value);
}
return hashTable;
}
private static void AutoFillMetricsConfig(XElement wadCfgElement, string resourceId, Cmdlet cmdlet)
{
if (string.IsNullOrEmpty(resourceId))
{
return;
}
var configurationElem = wadCfgElement.Elements().FirstOrDefault(d => d.Name.LocalName == DiagnosticMonitorConfigurationElemStr);
if (configurationElem == null)
{
throw new ArgumentException(Properties.Resources.DiagnosticsExtensionDiagnosticMonitorConfigurationElementNotDefined);
}
var metricsElement = configurationElem.Elements().FirstOrDefault(d => d.Name.LocalName == MetricsElemStr);
if (metricsElement == null)
{
XNamespace ns = XmlNamespace;
metricsElement = new XElement(ns + MetricsElemStr,
new XAttribute(MetricsResourceIdAttr, resourceId));
configurationElem.Add(metricsElement);
}
else
{
var resourceIdAttr = metricsElement.Attribute(MetricsResourceIdAttr);
if (resourceIdAttr != null && !resourceIdAttr.Value.Equals(resourceId))
{
cmdlet.WriteWarning(Properties.Resources.DiagnosticsExtensionMetricsResourceIdNotMatch);
}
metricsElement.SetAttributeValue(MetricsResourceIdAttr, resourceId);
}
}
private static Hashtable GetPublicConfigFromJsonFile(string configurationPath, string storageAccountName, string resourceId, Cmdlet cmdlet)
{
var publicConfig = GetPublicConfigJObjectFromJsonFile(configurationPath);
var properties = publicConfig.Properties().Select(p => p.Name);
var wadCfgProperty = properties.FirstOrDefault(p => p.Equals(WadCfg, StringComparison.OrdinalIgnoreCase));
var wadCfgBlobProperty = properties.FirstOrDefault(p => p.Equals(WadCfgBlob, StringComparison.OrdinalIgnoreCase));
var xmlCfgProperty = properties.FirstOrDefault(p => p.Equals(EncodedXmlCfg, StringComparison.OrdinalIgnoreCase));
var storageAccountProperty = properties.FirstOrDefault(p => p.Equals(StorageAccount, StringComparison.OrdinalIgnoreCase));
var storageTypeProperty = properties.FirstOrDefault(p => p.Equals(StorageType, StringComparison.OrdinalIgnoreCase));
var hashTable = new Hashtable();
if (string.IsNullOrEmpty(storageAccountName) && storageAccountProperty != null)
{
storageAccountName = (string)publicConfig[storageAccountProperty];
}
hashTable.Add(StorageAccount, storageAccountName);
if (wadCfgProperty != null && publicConfig[wadCfgProperty] is JObject)
{
var wadCfgObject = (JObject)publicConfig[wadCfgProperty];
AutoFillMetricsConfig(wadCfgObject, resourceId, cmdlet);
hashTable.Add(wadCfgProperty, wadCfgObject);
}
else if (wadCfgBlobProperty != null)
{
hashTable.Add(wadCfgBlobProperty, publicConfig[wadCfgBlobProperty]);
}
else if (xmlCfgProperty != null)
{
hashTable.Add(xmlCfgProperty, publicConfig[xmlCfgProperty]);
}
else
{
throw new ArgumentException(Properties.Resources.DiagnosticsExtensionIaaSConfigElementNotDefinedInJson);
}
if (storageTypeProperty != null)
{
string storageType = (string)publicConfig[storageTypeProperty];
WadStorageType wadStorageType;
if (!Enum.TryParse<WadStorageType>(storageType, out wadStorageType))
{
throw new ArgumentException(StorageType);
}
hashTable.Add(StorageType, storageType);
}
return hashTable;
}
private static void AutoFillMetricsConfig(JObject wadCfgObject, string resourceId, Cmdlet cmdlet)
{
if (string.IsNullOrEmpty(resourceId))
{
return;
}
var configObject = wadCfgObject[DiagnosticMonitorConfigurationElemStr] as JObject;
if (configObject == null)
{
throw new ArgumentException(Properties.Resources.DiagnosticsExtensionDiagnosticMonitorConfigurationElementNotDefined);
}
var metricsObject = configObject[MetricsElemStr] as JObject;
if (metricsObject == null)
{
configObject.Add(new JProperty(MetricsElemStr,
new JObject(
new JProperty(MetricsResourceIdAttr, resourceId))));
}
else
{
var resourceIdValue = metricsObject[MetricsResourceIdAttr] as JValue;
if (resourceIdValue != null && !resourceIdValue.Value.Equals(resourceId))
{
cmdlet.WriteWarning(Properties.Resources.DiagnosticsExtensionMetricsResourceIdNotMatch);
}
metricsObject[MetricsResourceIdAttr] = resourceId;
}
}
public static Hashtable GetPrivateDiagnosticsConfiguration(string configurationPath,
string overrideStorageAccountName, string overrideStorageKey, string overrideEndpoint)
{
var privateConfig = new Hashtable();
var configFileType = GetConfigFileType(configurationPath);
if (configFileType == ConfigFileType.Xml)
{
var doc = XDocument.Load(configurationPath);
var privateConfigElement = doc.Descendants().FirstOrDefault(d => d.Name.LocalName == PrivateConfigElemStr);
if (privateConfigElement != null)
{
// Unfortunately, there is no easy way to convert the xml config to json config without involving a schema file.
// We take the schema file generated by the .xsd file, and let the serializer doing the conversion work for us.
// NOTE: this file need to be updated whenever the private schema is changed.
XmlSerializer serializer = new XmlSerializer(typeof(Cis.Monitoring.Wad.PrivateConfigConverter.PrivateConfig));
using (StringReader sr = new StringReader(privateConfigElement.ToString()))
{
var config = (Cis.Monitoring.Wad.PrivateConfigConverter.PrivateConfig)serializer.Deserialize(sr);
var storageAccount = config.StorageAccount;
// Set the StorageAccount element as null, so it won't appear after serialize to json
config.StorageAccount = null;
var privateConfigInJson = JsonConvert.SerializeObject(config,
new JsonSerializerSettings
{
NullValueHandling = NullValueHandling.Ignore
});
privateConfig = JsonConvert.DeserializeObject<Hashtable>(privateConfigInJson);
if (!string.IsNullOrEmpty(storageAccount.name))
{
privateConfig[StorageAccountNameTag] = storageAccount.name;
}
if (!string.IsNullOrEmpty(storageAccount.key))
{
privateConfig[StorageAccountKeyTag] = storageAccount.key;
}
if (!string.IsNullOrEmpty(storageAccount.endpoint))
{
privateConfig[StorageAccountEndPointTag] = storageAccount.endpoint;
}
if (!string.IsNullOrEmpty(storageAccount.sasToken))
{
privateConfig[StorageAccountSASTokenTag] = storageAccount.sasToken;
}
}
}
}
else if (configFileType == ConfigFileType.Json)
{
// Find the PrivateConfig
var jsonConfig = JsonConvert.DeserializeObject<JObject>(File.ReadAllText(configurationPath));
var hasPrivateConfig = jsonConfig.Properties().Any(p => p.Name.Equals(PrivateConfigElemStr));
if (hasPrivateConfig)
{
privateConfig = JsonConvert.DeserializeObject<Hashtable>(jsonConfig[PrivateConfigElemStr].ToString());
}
}
string storageAccountNameInPrivateConfig = privateConfig[StorageAccountNameTag] as string;
if (!string.IsNullOrEmpty(storageAccountNameInPrivateConfig) &&
!string.Equals(storageAccountNameInPrivateConfig, overrideStorageAccountName, StringComparison.OrdinalIgnoreCase))
{
throw new ArgumentException(Properties.Resources.DiagnosticsExtensionMismatchStorageAccountName, StorageAccountNameTag);
}
privateConfig[StorageAccountNameTag] = overrideStorageAccountName;
// Only overwrite storage key if no sas token is provided.
if (string.IsNullOrEmpty(privateConfig[StorageAccountSASTokenTag] as string))
{
privateConfig[StorageAccountKeyTag] = overrideStorageKey;
privateConfig[StorageAccountEndPointTag] = overrideEndpoint;
}
return privateConfig;
}
private static void AddEventHubPrivateConfig(Hashtable privateConfig, string configurationPath)
{
var eventHubUrl = GetConfigValueFromPrivateConfig(configurationPath, EventHubElemStr, EventHubUrlAttr);
var eventHubSharedAccessKeyName = GetConfigValueFromPrivateConfig(configurationPath, EventHubElemStr, EventHubSharedAccessKeyNameAttr);
var eventHubSharedAccessKey = GetConfigValueFromPrivateConfig(configurationPath, EventHubElemStr, EventHubSharedAccessKeyAttr);
if (!string.IsNullOrEmpty(eventHubUrl) || !string.IsNullOrEmpty(eventHubSharedAccessKeyName) || !string.IsNullOrEmpty(eventHubSharedAccessKey))
{
var eventHubConfig = new Hashtable();
eventHubConfig.Add(EventHubUrlAttr, eventHubUrl);
eventHubConfig.Add(EventHubSharedAccessKeyNameAttr, eventHubSharedAccessKeyName);
eventHubConfig.Add(EventHubSharedAccessKeyAttr, eventHubSharedAccessKey);
privateConfig.Add(EventHubElemStr, eventHubConfig);
}
}
private static XElement GetPublicConfigXElementFromXmlFile(string configurationPath)
{
XElement publicConfig = null;
if (!string.IsNullOrEmpty(configurationPath))
{
var xmlConfig = XElement.Load(configurationPath);
if (xmlConfig.Name.LocalName == PublicConfigElemStr)
{
// The passed in config file is public config
publicConfig = xmlConfig;
}
else if (xmlConfig.Name.LocalName == DiagnosticsConfigurationElemStr)
{
// The passed in config file is .wadcfgx file
publicConfig = xmlConfig.Elements().FirstOrDefault(ele => ele.Name.LocalName == PublicConfigElemStr);
}
}
return publicConfig;
}
private static JObject GetPublicConfigJObjectFromJsonFile(string configurationPath)
{
var config = JsonConvert.DeserializeObject<JObject>(File.ReadAllText(configurationPath));
var properties = config.Properties().Select(p => p.Name);
// If the json config has the public config as a property, we extract it. Otherwise, the root object is the public config.
var publicConfigProperty = properties.FirstOrDefault(p => p.Equals(PublicConfigElemStr, StringComparison.OrdinalIgnoreCase));
var publicConfig = publicConfigProperty == null ? config : config[publicConfigProperty] as JObject;
return publicConfig;
}
/// <summary>
/// Get the private config value for a specific attribute.
/// The private config looks like this:
/// XML:
/// <PrivateConfig xmlns="namespace">
/// <StorageAccount name = "name" key="key" endpoint="endpoint" />
/// <EventHub Url = "url" SharedAccessKeyName="sasKeyName" SharedAccessKey="sasKey"/>
/// </PrivateConfig>
///
/// JSON:
/// "PrivateConfig":{
/// "storageAccountName":"name",
/// "storageAccountKey":"key",
/// "storageAccountEndPoint":"endpoint",
/// "EventHub":{
/// "Url":"url",
/// "SharedAccessKeyName":"sasKeyName",
/// "SharedAccessKey":"sasKey"
/// }
/// }
/// </summary>
/// <param name="configurationPath">The path to the configuration file</param>
/// <param name="elementName">The element name of the private config. e.g., StorageAccount, EventHub</param>
/// <param name="attributeName">The attribute name of the element</param>
/// <returns></returns>
public static string GetConfigValueFromPrivateConfig(string configurationPath, string elementName, string attributeName)
{
string value = string.Empty;
var configFileType = GetConfigFileType(configurationPath);
if (configFileType == ConfigFileType.Xml)
{
var xmlConfig = XElement.Load(configurationPath);
if (xmlConfig.Name.LocalName == DiagnosticsConfigurationElemStr)
{
var privateConfigElem = xmlConfig.Elements().FirstOrDefault(ele => ele.Name.LocalName == PrivateConfigElemStr);
var configElem = privateConfigElem == null ? null : privateConfigElem.Elements().FirstOrDefault(ele => ele.Name.LocalName == elementName);
var attribute = configElem == null ? null : configElem.Attributes().FirstOrDefault(a => string.Equals(a.Name.LocalName, attributeName));
value = attribute == null ? null : attribute.Value;
}
}
else if (configFileType == ConfigFileType.Json)
{
// Find the PrivateConfig
var jsonConfig = JsonConvert.DeserializeObject<JObject>(File.ReadAllText(configurationPath));
var properties = jsonConfig.Properties().Select(p => p.Name);
var privateConfigProperty = properties.FirstOrDefault(p => p.Equals(PrivateConfigElemStr));
if (privateConfigProperty == null)
{
return value;
}
var privateConfig = jsonConfig[privateConfigProperty] as JObject;
// Find the target config object corresponding to elementName
JObject targetConfig = null;
if (elementName == StorageAccountElemStr)
{
// Special handling as private storage config is flattened
targetConfig = privateConfig;
var attributeNameMapping = new Dictionary<string, string>()
{
{ PrivConfNameAttr, "storageAccountName" },
{ PrivConfKeyAttr, "storageAccountKey" },
{ PrivConfEndpointAttr, "storageAccountEndPoint" }
};
attributeName = attributeNameMapping.FirstOrDefault(m => m.Key == attributeName).Value;
}
else
{
properties = privateConfig.Properties().Select(p => p.Name);
var configProperty = properties.FirstOrDefault(p => p.Equals(elementName));
targetConfig = configProperty == null ? null : privateConfig[configProperty] as JObject;
}
if (targetConfig == null || attributeName == null)
{
return value;
}
// Find the config value corresponding to attributeName
properties = targetConfig.Properties().Select(p => p.Name);
var attributeProperty = properties.FirstOrDefault(p => p.Equals(attributeName));
value = attributeProperty == null ? null : targetConfig[attributeProperty].Value<string>();
}
return value;
}
/// <summary>
/// Initialize the storage account name if it's not specified.
/// It can be defined in multiple places, we only take the one with higher precedence. And the precedence is:
/// 1. The one get from StorageContext parameter
/// 2. The one parsed from the diagnostics configuration file
/// </summary>
public static string InitializeStorageAccountName(IStorageContext storageContext = null, string configurationPath = null)
{
string storageAccountName = null;
var configFileType = GetConfigFileType(configurationPath);
if (storageContext != null)
{
storageAccountName = storageContext.StorageAccountName;
}
else if (configFileType == ConfigFileType.Xml)
{
var publicConfig = GetPublicConfigXElementFromXmlFile(configurationPath);
var storageNode = publicConfig == null ? null : publicConfig.Elements().FirstOrDefault(ele => ele.Name.LocalName == StorageAccountElemStr);
storageAccountName = storageNode == null ? null : storageNode.Value;
}
else if (configFileType == ConfigFileType.Json)
{
var publicConfig = GetPublicConfigJObjectFromJsonFile(configurationPath);
var properties = publicConfig.Properties().Select(p => p.Name);
var storageAccountProperty = properties.FirstOrDefault(p => p.Equals(StorageAccount, StringComparison.OrdinalIgnoreCase));
storageAccountName = storageAccountProperty == null ? null : publicConfig[storageAccountProperty].Value<string>();
}
return storageAccountName;
}
/// <summary>
/// Initialize the storage account key if it's not specified.
/// It can be defined in multiple places, we only take the one with higher precedence. And the precedence is:
/// 1. The one we try to resolve within current subscription
/// 2. The one defined in PrivateConfig in the configuration file
/// </summary>
public static string InitializeStorageAccountKey(IStorageManagementClient storageClient, string storageAccountName = null, string configurationPath = null)
{
string storageAccountKey = null;
StorageAccount storageAccount = null;
if (TryGetStorageAccount(storageClient, storageAccountName, out storageAccount))
{
var account = new ARMStorageProvider(storageClient).GetCloudStorageAccount(storageAccount.Name, ARMStorageService.ParseResourceGroupFromId(storageAccount.Id));
// Help user retrieve the storage account key
var credentials = account.Credentials;
storageAccountKey = credentials.ExportBase64EncodedKey();
}
else
{
// Use the one defined in PrivateConfig
storageAccountKey = GetConfigValueFromPrivateConfig(configurationPath, StorageAccountElemStr, PrivConfKeyAttr);
}
return storageAccountKey;
}
/// <summary>
/// Initialize the storage account endpoint if it's not specified.
/// We can get the value from multiple places, we only take the one with higher precedence. And the precedence is:
/// 1. The one get from StorageContext parameter
/// 2. The one get from the storage account
/// 3. The one get from PrivateConfig element in config file
/// 4. The one get from current Azure Environment
/// </summary>
public static string InitializeStorageAccountEndpoint(string storageAccountName, string storageAccountKey, IStorageManagementClient storageClient,
IStorageContext storageContext = null, string configurationPath = null, IAzureContext defaultContext = null)
{
string storageAccountEndpoint = null;
StorageAccount storageAccount = null;
if (storageContext != null)
{
// Get value from StorageContext
storageAccountEndpoint = GetEndpointFromStorageContext(storageContext);
}
else if (TryGetStorageAccount(storageClient, storageAccountName, out storageAccount))
{
// Get value from StorageAccount
var endpoints = storageAccount.PrimaryEndpoints;
var context = CreateStorageContext(new Uri(endpoints.Blob), new Uri(endpoints.Queue), new Uri(endpoints.Table), new Uri(endpoints.File), storageAccountName, storageAccountKey);
storageAccountEndpoint = GetEndpointFromStorageContext(context);
}
else if (!string.IsNullOrEmpty(
storageAccountEndpoint = GetConfigValueFromPrivateConfig(configurationPath, StorageAccountElemStr, PrivConfEndpointAttr)))
{
// We can get the value from PrivateConfig
}
else if (defaultContext != null && defaultContext.Environment != null)
{
// Get value from default azure environment. Default to use https
Uri blobEndpoint = defaultContext.Environment.GetStorageBlobEndpoint(storageAccountName);
Uri queueEndpoint = defaultContext.Environment.GetStorageQueueEndpoint(storageAccountName);
Uri tableEndpoint = defaultContext.Environment.GetStorageTableEndpoint(storageAccountName);
Uri fileEndpoint = defaultContext.Environment.GetStorageFileEndpoint(storageAccountName);
var context = CreateStorageContext(blobEndpoint, queueEndpoint, tableEndpoint, fileEndpoint, storageAccountName, storageAccountKey);
storageAccountEndpoint = GetEndpointFromStorageContext(context);
}
return storageAccountEndpoint;
}
private static bool TryGetStorageAccount(IStorageManagementClient storageClient, string storageAccountName, out StorageAccount storageAccount)
{
try
{
var storageAccounts = storageClient.StorageAccounts.List();
storageAccount = storageAccounts == null ? null : storageAccounts.FirstOrDefault(account => account.Name.Equals(storageAccountName));
}
catch
{
storageAccount = null;
}
return storageAccount != null;
}
private static AzureStorageContext CreateStorageContext(Uri blobEndpoint, Uri queueEndpoint, Uri tableEndpoint, Uri fileEndpoint,
string storageAccountName, string storageAccountKey)
{
var credentials = new StorageCredentials(storageAccountName, storageAccountKey);
var cloudStorageAccount = new CloudStorageAccount(credentials, blobEndpoint, queueEndpoint, tableEndpoint, fileEndpoint);
return new AzureStorageContext(cloudStorageAccount);
}
private static string GetEndpointFromStorageContext(IStorageContext context)
{
var scheme = context.BlobEndPoint.StartsWith("https://", StringComparison.OrdinalIgnoreCase) ? "https://" : "http://";
return scheme + context.EndPointSuffix;
}
/// <summary>
/// Parse public and private configurations, and automatically resolve storage key for private configuration.
/// </summary>
/// <param name="publicConfigPath">Public configuration file path</param>
/// <param name="privateConfigPath">Private configuration file path, can be empty</param>
/// <param name="storageClient">Storage client</param>
/// <returns>A tuple with public configuration as first element and private configuration as second element</returns>
public static Tuple<Hashtable, Hashtable> GetConfigurationsFromFiles(string publicConfigPath, string privateConfigPath, string resourceId, Cmdlet cmdlet, IStorageManagementClient storageClient)
{
var publicConfig = GetPublicConfigFromJsonFile(publicConfigPath, null, resourceId, cmdlet);
var privateConfig = string.IsNullOrEmpty(privateConfigPath) ? new Hashtable() :
JsonConvert.DeserializeObject<Hashtable>(File.ReadAllText(privateConfigPath));
// Resolve storage account name
// Storage account name must be provided in public config
var storageAccountNameInPublicConfig = publicConfig[StorageAccount] as string;
if (string.IsNullOrEmpty(storageAccountNameInPublicConfig))
{
throw new ArgumentException(Properties.Resources.DiagnosticsExtensionNullStorageAccountName);
}
string storageAccountNameInPrivateConfig = privateConfig[StorageAccountNameTag] as string;
if (!string.IsNullOrEmpty(storageAccountNameInPrivateConfig) &&
!string.Equals(storageAccountNameInPrivateConfig, storageAccountNameInPublicConfig, StringComparison.OrdinalIgnoreCase))
{
throw new ArgumentException(Properties.Resources.DiagnosticsExtensionMismatchStorageAccountName, StorageAccountNameTag);
}
privateConfig[StorageAccountNameTag] = storageAccountNameInPublicConfig;
string storageAccountKey = null;
// If sas token is provided, just use it.
// Otherwise, try to resolve storage key.
if (string.IsNullOrEmpty(privateConfig[StorageAccountSASTokenTag] as string))
{
// Resolve storage account key
storageAccountKey = InitializeStorageAccountKey(storageClient, storageAccountNameInPublicConfig, privateConfigPath);
if (string.IsNullOrEmpty(storageAccountKey))
{
storageAccountKey = privateConfig[StorageAccountKeyTag] as string;
if (string.IsNullOrEmpty(storageAccountKey))
{
// Throw exception if no storage key provided in private config and cannot retrieve it from server
throw new ArgumentException(Properties.Resources.DiagnosticsExtensionNullStorageAccountKey);
}
}
else
{
// If storage key can be retrieved, use that one.
privateConfig[StorageAccountKeyTag] = storageAccountKey;
}
}
// Resolve storage account endpoint
var storageAccountEndpoint = storageAccountKey == null? null: InitializeStorageAccountEndpoint(storageAccountNameInPublicConfig, storageAccountKey, storageClient);
if (string.IsNullOrEmpty(storageAccountEndpoint))
{
storageAccountEndpoint = privateConfig[StorageAccountEndPointTag] as string;
if (string.IsNullOrEmpty(storageAccountEndpoint))
{
// Throw exception if no storage endpoint provided in private config and cannot retrieve it from server
throw new ArgumentNullException(Properties.Resources.DiagnosticsExtensionNullStorageAccountEndpoint);
}
}
else
{
// If storage account endpoint can be retrieved, use that one.
privateConfig[StorageAccountEndPointTag] = storageAccountEndpoint;
}
return new Tuple<Hashtable, Hashtable>(publicConfig, privateConfig);
}
/// <summary>
/// Check if a VMSS extension is diagnostics extension.
/// </summary>
/// <param name="extension">VMSS extension</param>
/// <returns>Whether the VMSS extension is diagnostics extension</returns>
public static bool IsDiagnosticsExtension(VirtualMachineScaleSetExtension extension)
{
return extension.Publisher.Equals(DiagnosticsExtensionConstants.ExtensionPublisher, StringComparison.InvariantCultureIgnoreCase) &&
extension.Type.Equals(DiagnosticsExtensionConstants.ExtensionType, StringComparison.InvariantCultureIgnoreCase);
}
}
}
| |
using System.Collections.Generic;
using System.IO;
using System.Linq;
using DocSharp.Generators.HTML.CSharp;
using ICSharpCode.NRefactory.TypeSystem;
namespace DocSharp.Generators.HTML
{
public class HTMLCSharpClassGenerator : HTMLPage
{
public ITypeDefinition Type;
public HTMLCSharpClassGenerator(ITypeDefinition type)
{
Type = type;
Title = Type.Name;
}
public override string FullPath
{
get { return GetFilePath(Type); }
}
public static string GetFilePath(INamedElement element)
{
var namespaces = new List<string>();
namespaces.AddRange(element.Namespace.Split('.'));
var namespacePath = Path.Combine(namespaces.ToArray());
var outPath = Path.Combine(namespacePath, element.Name);
return string.Format(@"classes/{0}.html", outPath).Replace('\\', '/');
}
protected override void GenerateContents()
{
var title = string.Format("{0} {1}", Type.Name, Type.Kind);
Heading(title, DefaultHeading);
Paragraph(Type.Documentation);
var inherits = new HTMLTextGenerator();
// Write the type hierarchy.
var bases = Type.GetAllBaseTypeDefinitions().ToList();
bases.RemoveAt(bases.Count - 1);
if (bases.Any())
{
Heading("Hierarchy:", DefaultHeading + 1);
foreach (var @base in bases)
Paragraph(GetLink(GetLocalHref(@base), @base.FullName));
}
GenerateNestedTypesSummary();
GenerateConstructorsSummary();
GeneratePropertiesSummary();
GenerateFieldsSummary();
GenerateMethodsSummary();
GenerateEventsSummary();
}
private void GenerateNestedTypesSummary()
{
if (!Type.NestedTypes.Any())
return;
var table = new HTMLTableBuilder("Nested Types",
new[] { "Modifier and Type", "Class and Description" });
foreach (var nestedType in Type.NestedTypes)
{
var link = GetLink(GetLocalHref(nestedType), GetTypeName(nestedType.DeclaringType));
table.Row(link, nestedType.Name);
}
Write(table);
}
private void GenerateEventsSummary()
{
if (!Type.Events.Any())
return;
var table = new HTMLTableBuilder("Events",
new[] { "Type", "Name" });
foreach (var @event in Type.Events)
{
var link = GetLink(GetLocalHref(@event), GetTypeName(@event.DeclaringType));
table.Row(link, @event.Name);
}
Write(table);
}
#region C# constructs tables
private void GenerateConstructorsSummary()
{
var constructors = Type.GetConstructors().ToList();
if (!constructors.Any())
return;
var table = new HTMLTableBuilder("Constructors",
new[] { "Signature", "Description" });
foreach (var ctor in constructors)
{
if (ctor.SymbolKind != SymbolKind.Constructor)
return;
var desc = GetLink(GetLocalHref(ctor), GetTypeName(ctor.DeclaringType));
desc.Write(" ({0})", GetMethodSignature(ctor));
table.Row(desc, ctor.Documentation);
}
Write(table);
}
private void GeneratePropertiesSummary()
{
var properties = Type.Properties.ToList();
properties.Sort((prop, prop1) => string.CompareOrdinal(prop.Name,
prop1.Name));
if (!properties.Any())
return;
var table = new HTMLTableBuilder("Properties",
new[] { "Type", "Name", "Description" });
foreach (var prop in properties)
{
if (prop.SymbolKind != SymbolKind.Property)
return;
var type = GetLink(GetHref(prop.ReturnType), GetTypeName(prop.ReturnType));
var link = GetLink(GetLocalHref(prop), prop.Name);
table.Row(GetTypeName(prop.ReturnType), link, prop.Documentation);
}
Write(table);
}
private void GenerateFieldsSummary()
{
var fields = Type.Fields.ToList();
fields.Sort((prop, prop1) => string.CompareOrdinal(prop.Name,
prop1.Name));
if (!fields.Any())
return;
var table = new HTMLTableBuilder("Fields",
new[] { "Type", "Name", "Description" });
foreach (var field in fields)
{
if (field.SymbolKind != SymbolKind.Field)
return;
var type = GetLink(GetHref(field.Type), GetTypeName(field.Type));
var name = GetLink(GetLocalHref(field), field.Name);
table.Row(type, name, field.Documentation);
}
Write(table);
}
private void GenerateMethodsSummary()
{
var methods = Type.Methods.ToList();
methods.Sort((method, method1) => string.CompareOrdinal(method.Name,
method1.Name));
if (!methods.Any())
return;
var table = new HTMLTableBuilder("Methods", new[] { "Return Type", "Description" });
foreach (var method in methods)
{
if (method.SymbolKind != SymbolKind.Method)
return;
var desc = GetLink(GetLocalHref(method), method.Name);
desc.Write(" ({0})", GetMethodSignature(method));
if (!string.IsNullOrWhiteSpace(method.Documentation))
{
desc.LineBreak();
desc.WriteLine(method.Documentation);
}
table.Row(GetTypeName(method.ReturnType), desc);
}
Write(table);
}
#endregion
#region Helpers
static string GetLocalHref(IEntity entity)
{
return MarkdownDocumentSection.GenerateShortcutString(entity.Name);
}
static string GetHref(IType type)
{
return MarkdownDocumentSection.GenerateShortcutString(type.Name);
}
static string GetTypeName(IType type)
{
type.AcceptVisitor(new CSharpTypePrinter());
return type.Name;
}
static string GetParamSignature(IParameter param)
{
var name = string.Empty;
if (param.IsRef)
name += "ref ";
else if (param.IsOut)
name += "out ";
name += GetLink(GetHref(param.Type), GetTypeName(param.Type));
name += " " + param.Name;
if (param.IsOptional)
name += " = " + param.ConstantValue;
return name;
}
static string GetMethodSignature(IMethod method)
{
var paramTypes = new List<string>();
foreach (var param in method.Parameters)
{
var name = GetParamSignature(param);
paramTypes.Add(name);
}
return string.Join(", ", paramTypes);
}
static HTMLTextGenerator GetLink(string href, string text)
{
var gen = new HTMLTextGenerator();
gen.Anchor(href);
gen.Write(text);
gen.CloseInlineTag(HTMLTag.A);
return gen;
}
#endregion
}
}
| |
using System;
using System.IO;
using System.ComponentModel;
using System.Collections.Generic;
using System.Runtime.Serialization;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using ChargeBee.Internal;
using ChargeBee.Api;
using ChargeBee.Models.Enums;
using ChargeBee.Filters.Enums;
namespace ChargeBee.Models
{
public class Usage : Resource
{
public Usage() { }
public Usage(Stream stream)
{
using (StreamReader reader = new StreamReader(stream))
{
JObj = JToken.Parse(reader.ReadToEnd());
apiVersionCheck (JObj);
}
}
public Usage(TextReader reader)
{
JObj = JToken.Parse(reader.ReadToEnd());
apiVersionCheck (JObj);
}
public Usage(String jsonString)
{
JObj = JToken.Parse(jsonString);
apiVersionCheck (JObj);
}
#region Methods
public static CreateRequest Create(string id)
{
string url = ApiUtil.BuildUrl("subscriptions", CheckNull(id), "usages");
return new CreateRequest(url, HttpMethod.POST);
}
public static RetrieveRequest Retrieve(string id)
{
string url = ApiUtil.BuildUrl("subscriptions", CheckNull(id), "usages");
return new RetrieveRequest(url, HttpMethod.GET);
}
public static DeleteRequest Delete(string id)
{
string url = ApiUtil.BuildUrl("subscriptions", CheckNull(id), "delete_usage");
return new DeleteRequest(url, HttpMethod.POST);
}
public static UsageListRequest List()
{
string url = ApiUtil.BuildUrl("usages");
return new UsageListRequest(url);
}
public static PdfRequest Pdf()
{
string url = ApiUtil.BuildUrl("usages", "pdf");
return new PdfRequest(url, HttpMethod.POST);
}
#endregion
#region Properties
public string Id
{
get { return GetValue<string>("id", false); }
}
public DateTime UsageDate
{
get { return (DateTime)GetDateTime("usage_date", true); }
}
public string SubscriptionId
{
get { return GetValue<string>("subscription_id", true); }
}
public string ItemPriceId
{
get { return GetValue<string>("item_price_id", true); }
}
public string InvoiceId
{
get { return GetValue<string>("invoice_id", false); }
}
public string LineItemId
{
get { return GetValue<string>("line_item_id", false); }
}
public string Quantity
{
get { return GetValue<string>("quantity", true); }
}
public SourceEnum? Source
{
get { return GetEnum<SourceEnum>("source", false); }
}
public string Note
{
get { return GetValue<string>("note", false); }
}
public long? ResourceVersion
{
get { return GetValue<long?>("resource_version", false); }
}
public DateTime? UpdatedAt
{
get { return GetDateTime("updated_at", false); }
}
public DateTime CreatedAt
{
get { return (DateTime)GetDateTime("created_at", true); }
}
#endregion
#region Requests
public class CreateRequest : EntityRequest<CreateRequest>
{
public CreateRequest(string url, HttpMethod method)
: base(url, method)
{
}
public CreateRequest Id(string id)
{
m_params.AddOpt("id", id);
return this;
}
public CreateRequest ItemPriceId(string itemPriceId)
{
m_params.Add("item_price_id", itemPriceId);
return this;
}
public CreateRequest Quantity(string quantity)
{
m_params.Add("quantity", quantity);
return this;
}
public CreateRequest UsageDate(long usageDate)
{
m_params.Add("usage_date", usageDate);
return this;
}
[Obsolete]
public CreateRequest DedupeOption(ChargeBee.Models.Enums.DedupeOptionEnum dedupeOption)
{
m_params.AddOpt("dedupe_option", dedupeOption);
return this;
}
public CreateRequest Note(string note)
{
m_params.AddOpt("note", note);
return this;
}
}
public class RetrieveRequest : EntityRequest<RetrieveRequest>
{
public RetrieveRequest(string url, HttpMethod method)
: base(url, method)
{
}
public RetrieveRequest Id(string id)
{
m_params.Add("id", id);
return this;
}
}
public class DeleteRequest : EntityRequest<DeleteRequest>
{
public DeleteRequest(string url, HttpMethod method)
: base(url, method)
{
}
public DeleteRequest Id(string id)
{
m_params.Add("id", id);
return this;
}
}
public class UsageListRequest : ListRequestBase<UsageListRequest>
{
public UsageListRequest(string url)
: base(url)
{
}
public StringFilter<UsageListRequest> Id()
{
return new StringFilter<UsageListRequest>("id", this);
}
public StringFilter<UsageListRequest> SubscriptionId()
{
return new StringFilter<UsageListRequest>("subscription_id", this);
}
public TimestampFilter<UsageListRequest> UsageDate()
{
return new TimestampFilter<UsageListRequest>("usage_date", this);
}
public StringFilter<UsageListRequest> ItemPriceId()
{
return new StringFilter<UsageListRequest>("item_price_id", this);
}
public StringFilter<UsageListRequest> InvoiceId()
{
return new StringFilter<UsageListRequest>("invoice_id", this).SupportsPresenceOperator(true);
}
public EnumFilter<ChargeBee.Models.Enums.SourceEnum, UsageListRequest> Source()
{
return new EnumFilter<ChargeBee.Models.Enums.SourceEnum, UsageListRequest>("source", this);
}
public UsageListRequest SortByUsageDate(SortOrderEnum order) {
m_params.AddOpt("sort_by["+order.ToString().ToLower()+"]","usage_date");
return this;
}
}
public class PdfRequest : EntityRequest<PdfRequest>
{
public PdfRequest(string url, HttpMethod method)
: base(url, method)
{
}
public PdfRequest DispositionType(ChargeBee.Models.Enums.DispositionTypeEnum dispositionType)
{
m_params.AddOpt("disposition_type", dispositionType);
return this;
}
public PdfRequest InvoiceId(string invoiceId)
{
m_params.Add("invoice[id]", invoiceId);
return this;
}
}
#endregion
#region Subclasses
#endregion
}
}
| |
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
// Copyright (c) 2009 Novell, Inc. (http://www.novell.com)
//
// Authors:
// Mike Gorse <[email protected]>
//
using System;
using NUnit.Framework;
using Atspi;
namespace AtSpiTest
{
[TestFixture]
public class EventTest : Base
{
Accessible frame = null;
EditableText et = null;
int eventCount = 0;
int addEventCount = 0;
int removeEventCount = 0;
string detail;
int v1, v2;
object any;
string oldName, newName;
string oldDescription, newDescription;
Role oldRole, newRole;
[TestFixtureSetUp]
public void Init ()
{
frame = GetFrame ("DocumentTest.exe", "DocumentTest");
et = frame.QueryEditableText ();
Assert.IsNotNull (et, "frame.QueryEditableText");
}
#region Test
// Object event tests
[Test]
public void BoundsChanged ()
{
frame.ObjectEvents.BoundsChanged += OnEventR;
et.SetTextContents ("BoundsChanged");
Sync ();
AssertEvent ();
frame.ObjectEvents.BoundsChanged -= OnEventR;
et.SetTextContents ("BoundsChanged");
Sync ();
AssertNoEvent ();
}
[Test]
public void LinkSelected ()
{
frame.ObjectEvents.LinkSelected += OnEventI;
et.SetTextContents ("LinkSelected");
Sync ();
AssertEvent ();
frame.ObjectEvents.LinkSelected -= OnEventI;
et.SetTextContents ("LinkSelected");
Sync ();
AssertNoEvent ();
}
[Test]
public void VisibleDataChanged ()
{
frame.ObjectEvents.VisibleDataChanged += OnEventSimple;
et.SetTextContents ("VisibleDataChanged");
Sync ();
AssertEvent ();
frame.ObjectEvents.VisibleDataChanged -= OnEventSimple;
et.SetTextContents ("VisibleDataChanged");
Sync ();
AssertNoEvent ();
}
[Test]
[Ignore ("TODO: SelectionChanged")]
public void SelectionChanged ()
{
frame.ObjectEvents.SelectionChanged += OnEventSimple;
et.SetTextContents ("SelectionChanged");
Sync ();
AssertEvent ();
frame.ObjectEvents.SelectionChanged -= OnEventSimple;
et.SetTextContents ("SelectionChanged");
Sync ();
AssertNoEvent ();
}
[Test]
public void ModelChanged ()
{
frame.ObjectEvents.ModelChanged += OnEventSimple;
et.SetTextContents ("ModelChanged");
Sync ();
AssertEvent ();
frame.ObjectEvents.ModelChanged -= OnEventSimple;
et.SetTextContents ("ModelChanged");
Sync ();
AssertNoEvent ();
}
[Test]
public void ActiveDescendantChanged ()
{
frame.ObjectEvents.ActiveDescendantChanged += OnEventO;
et.SetTextContents ("ActiveDescendantChanged");
Sync ();
AssertEvent ();
frame.ObjectEvents.ActiveDescendantChanged -= OnEventO;
et.SetTextContents ("ActiveDescendantChanged");
Sync ();
AssertNoEvent ();
}
[Test]
public void RowInserted ()
{
frame.ObjectEvents.RowInserted += OnEventII;
et.SetTextContents ("RowInserted");
Sync ();
AssertEvent ();
frame.ObjectEvents.RowInserted -= OnEventII;
et.SetTextContents ("RowInserted");
Sync ();
AssertNoEvent ();
}
[Test]
public void RowReordered ()
{
frame.ObjectEvents.RowReordered += OnEventSimple;
et.SetTextContents ("RowReordered");
Sync ();
AssertEvent ();
frame.ObjectEvents.RowReordered -= OnEventSimple;
et.SetTextContents ("RowReordered");
Sync ();
AssertNoEvent ();
}
[Test]
public void RowDeleted ()
{
frame.ObjectEvents.RowDeleted += OnEventII;
et.SetTextContents ("RowDeleted");
Sync ();
AssertEvent ();
frame.ObjectEvents.RowDeleted -= OnEventII;
et.SetTextContents ("RowDeleted");
Sync ();
AssertNoEvent ();
}
[Test]
public void ColumnInserted ()
{
frame.ObjectEvents.ColumnInserted += OnEventII;
et.SetTextContents ("ColumnInserted");
Sync ();
AssertEvent ();
frame.ObjectEvents.ColumnInserted -= OnEventII;
et.SetTextContents ("ColumnInserted");
Sync ();
AssertNoEvent ();
}
[Test]
public void ColumnReordered ()
{
frame.ObjectEvents.ColumnReordered += OnEventSimple;
et.SetTextContents ("ColumnReordered");
Sync ();
AssertEvent ();
frame.ObjectEvents.ColumnReordered -= OnEventSimple;
et.SetTextContents ("ColumnReordered");
Sync ();
AssertNoEvent ();
}
[Test]
public void ColumnDeleted ()
{
frame.ObjectEvents.ColumnDeleted += OnEventII;
et.SetTextContents ("ColumnDeleted");
Sync ();
AssertEvent ();
frame.ObjectEvents.ColumnDeleted -= OnEventII;
et.SetTextContents ("ColumnDeleted");
Sync ();
AssertNoEvent ();
}
[Test]
public void TextSelectionChanged ()
{
frame.ObjectEvents.TextSelectionChanged += OnEventSimple;
et.SetTextContents ("TextSelectionChanged");
Sync ();
AssertEvent ();
frame.ObjectEvents.TextSelectionChanged -= OnEventSimple;
et.SetTextContents ("TextSelectionChanged");
Sync ();
AssertNoEvent ();
}
[Test]
public void TextChanged ()
{
frame.ObjectEvents.TextChanged += OnEventSIIS;
et.SetTextContents ("TextChanged");
Sync ();
AssertEvent ();
Assert.AreEqual (0, v1, "TextChanged v1");
Assert.AreEqual (11, v2, "TextChanged v2");
Assert.AreEqual ("insert", detail, "TextChanged detail");
Assert.AreEqual ("TextChanged", any, "TextChanged any");
frame.ObjectEvents.TextChanged -= OnEventSIIS;
et.SetTextContents ("TextChanged");
Sync ();
AssertNoEvent ();
}
[Test]
public void TextAttributesChanged ()
{
frame.ObjectEvents.TextAttributesChanged += OnEventSimple;
et.SetTextContents ("TextAttributesChanged");
Sync ();
AssertEvent ();
frame.ObjectEvents.TextAttributesChanged -= OnEventSimple;
et.SetTextContents ("TextAttributesChanged");
Sync ();
AssertNoEvent ();
}
[Test]
public void TextCaretMoved ()
{
frame.ObjectEvents.TextCaretMoved += OnEventI;
et.SetTextContents ("TextCaretMoved");
Sync ();
AssertEvent ();
frame.ObjectEvents.TextCaretMoved -= OnEventI;
et.SetTextContents ("TextCaretMoved");
Sync ();
AssertNoEvent ();
}
// Document event tests
[Test]
public void LoadComplete ()
{
frame.DocumentEvents.LoadComplete += OnEventSimple;
et.SetTextContents ("LoadComplete");
Sync ();
AssertEvent ();
frame.DocumentEvents.LoadComplete -= OnEventSimple;
et.SetTextContents ("LoadComplete");
Sync ();
AssertNoEvent ();
}
[Test]
public void Reload ()
{
frame.DocumentEvents.Reload += OnEventSimple;
et.SetTextContents ("Reload");
Sync ();
AssertEvent ();
frame.DocumentEvents.Reload -= OnEventSimple;
et.SetTextContents ("Reload");
Sync ();
AssertNoEvent ();
}
[Test]
public void LoadStopped ()
{
frame.DocumentEvents.LoadStopped += OnEventSimple;
et.SetTextContents ("LoadStopped");
Sync ();
AssertEvent ();
frame.DocumentEvents.LoadStopped -= OnEventSimple;
et.SetTextContents ("LoadStopped");
Sync ();
AssertNoEvent ();
}
[Test]
public void Focus ()
{
frame.FocusEvents.Focus += OnEventSimple;
et.SetTextContents ("Focus");
Sync ();
AssertEvent ();
frame.FocusEvents.Focus -= OnEventSimple;
et.SetTextContents ("Focus");
Sync ();
AssertNoEvent ();
}
[Test]
public void NameChanged ()
{
Desktop.NameChanged += OnNameChanged;
et.SetTextContents ("NameChanged");
Sync ();
Assert.AreEqual (string.Empty, oldName, "OldName");
Assert.AreEqual ("xyzzy", newName, "NameChanged");
Desktop.NameChanged -= OnNameChanged;
}
[Test]
public void DescriptionChanged ()
{
Desktop.DescriptionChanged += OnDescriptionChanged;
et.SetTextContents ("DescriptionChanged");
Sync ();
Assert.AreEqual (string.Empty, oldDescription, "OldDescription");
Assert.AreEqual ("plugh", newDescription, "DescriptionChanged");
Desktop.DescriptionChanged -= OnDescriptionChanged;
}
[Test]
public void RoleChanged ()
{
Desktop.RoleChanged += OnRoleChanged;
et.SetTextContents ("RoleChanged");
Sync ();
Assert.AreEqual (Role.Frame, oldRole, "RoleChanged OldRole");
Assert.AreEqual (Role.Dialog, newRole, "RoleChanged");
Desktop.RoleChanged -= OnRoleChanged;
}
[Test]
public void StateChanged ()
{
eventCount = 0;
Desktop.StateChanged += OnStateChanged;
et.SetTextContents ("StateChanged");
Sync ();
Desktop.StateChanged -= OnStateChanged;
AssertEvents (2);
}
[Test]
public void ChildRemoved ()
{
addEventCount = removeEventCount = 0;
Desktop.ChildAdded += OnChildAdded;
Desktop.ChildRemoved += OnChildRemoved;
et.SetTextContents ("RemoveChild");
Sync ();
Assert.AreEqual (0, addEventCount, "addEvents when removing");
Assert.AreEqual (1, removeEventCount, "removeEvents");
Desktop.ChildRemoved -= OnChildRemoved;
Desktop.ChildAdded -= OnChildAdded;
et.SetTextContents ("AddChild");
}
[Test]
public void ChildAdded ()
{
et.SetTextContents ("RemoveChild");
Sync ();
addEventCount = removeEventCount = 0;
Desktop.ChildAdded += OnChildAdded;
Desktop.ChildRemoved += OnChildRemoved;
et.SetTextContents ("AddChild");
Sync ();
Assert.AreEqual (1, addEventCount, "addEvents");
Assert.AreEqual (0, removeEventCount, "removeEvents when adding");
// Add a second child; ensure we don't get extra events
addEventCount = removeEventCount = 0;
et.SetTextContents ("AddChild");
Sync ();
Desktop.ChildAdded -= OnChildAdded;
Assert.AreEqual (1, addEventCount, "addEvents #2");
Assert.AreEqual (0, removeEventCount, "removeEvents when adding #2");
Desktop.ChildRemoved -= OnChildRemoved;
}
private void OnEventI (Accessible sender, int v1)
{
eventCount++;
this.v1 = v1;
}
private void OnEventII (Accessible sender, int v1, int v2)
{
eventCount++;
this.v1 = v1;
this.v2 = v2;
}
private void OnEventO (Accessible sender, Accessible obj)
{
eventCount++;
this.any = obj;
}
private void OnEventR (Accessible sender, BoundingBox rect)
{
eventCount++;
this.any = rect;
}
/*
private void OnEventSB (Accessible sender, string detail, bool val)
{
eventCount++;
this.detail = detail;
this.v1 = (val? 1: 0);
}
*/
/*
private void OnEventSII (Accessible sender, string detail, int v1, int v2)
{
eventCount++;
this.detail = detail;
this.v1 = v1;
this.v2 = v2;
}
*/
private void OnEventSIIS (Accessible sender, string detail, int v1, int v2, string any)
{
eventCount++;
this.detail = detail;
this.v1 = v1;
this.v2 = v2;
this.any = any;
}
/*
private void OnEventSIO (Accessible sender, string detail, int v1, Accessible obj)
{
eventCount++;
this.detail = detail;
this.v1 = v1;
this.any = obj;
}
private void OnEventSV (Accessible sender, string detail, object any)
{
eventCount++;
this.detail = detail;
this.any = any;
}
*/
private void OnEventSimple (Accessible sender)
{
eventCount++;
}
private void OnNameChanged (object sender, string oldName, string newName)
{
this.oldName = oldName;
this.newName = newName;
}
private void OnDescriptionChanged (object sender, string oldDescription, string newDescription)
{
this.oldDescription = oldDescription;
this.newDescription = newDescription;
}
private void OnRoleChanged (object sender, Role oldRole, Role newRole)
{
this.oldRole = oldRole;
this.newRole = newRole;
}
private void OnStateChanged (Accessible sender, StateType state, bool set)
{
if (sender.Role == Role.PushButton &&
state == StateType.Enabled &&
set == false)
eventCount++;
else if (sender.Role == Role.PushButton &&
state == StateType.Sensitive &&
set == false)
eventCount++;
}
private void OnChildAdded (Accessible parent, Accessible child)
{
addEventCount++;
}
private void OnChildRemoved (Accessible parent, Accessible child)
{
removeEventCount++;
}
#endregion
private void Sync ()
{
System.Threading.Thread.Sleep (500);
}
private void AssertEvent ()
{
AssertEvents (1);
}
private void AssertNoEvent ()
{
AssertEvents (0);
}
private void AssertEvents (int n)
{
int oldEventCount = eventCount;
eventCount = 0;
Assert.AreEqual (n, oldEventCount, "eventCount");
}
}
}
| |
//-----------------------------------------------------------------------
// <copyright file="FileItem.cs" company="CompanyName">
// Copyright info.
// </copyright>
//-----------------------------------------------------------------------
namespace Distribox.FileSystem
{
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using Distribox.CommonLib;
// TODO create a new class indicating version delta
/// <summary>
/// Stores all versions of a file.
/// </summary>
public class FileItem
{
/// <summary>
/// Initializes a new instance of the <see cref="Distribox.FileSystem.FileItem"/> class.
/// </summary>
public FileItem()
{
this.History = new List<FileEvent>();
}
/// <summary>
/// Initializes a new instance of the <see cref="Distribox.FileSystem.FileItem"/> class.
/// </summary>
/// <param name="id">The identifier.</param>
public FileItem(string id)
{
this.History = new List<FileEvent>();
this.Id = id;
}
/// <summary>
/// Initializes a new instance of the <see cref="Distribox.FileSystem.FileItem"/> class.
/// </summary>
/// <param name="name">The name.</param>
/// <param name="isDirectory">If set to <c>true</c> is directory.</param>
public FileItem(string name, bool isDirectory)
{
this.History = new List<FileEvent>();
this.Id = CommonHelper.GetRandomHash();
this.IsDirectory = isDirectory;
}
/// <summary>
/// Gets or sets the identifier of file.
/// </summary>
/// <value>The identifier of this file.</value>
public string Id { get; set; }
/// <summary>
/// Gets or sets a value indicating whether this file is a directory.
/// </summary>
/// <value><c>true</c> if this file is a directory; otherwise, <c>false</c>.</value>
public bool IsDirectory { get; set; }
/// <summary>
/// Gets a value indicating whether this file is alive (not deleted).
/// </summary>
/// <value><c>true</c> if this file is alive; otherwise, <c>false</c>.</value>
public bool IsAlive
{
get
{
return this.History.Find(x => x.EventId == this.CurrentEventId).Type != FileEventType.Deleted;
}
}
/// <summary>
/// Gets current name of the file.
/// </summary>
/// <value>The current name of the file.</value>
public string CurrentName
{
get
{
return this.CurrentEventId == null ? null : this.History.Find(x => x.EventId == this.CurrentEventId).Name;
}
}
/// <summary>
/// Gets or sets the current event id.
/// </summary>
public string CurrentEventId
{
get;
set;
}
/// <summary>
/// Gets SHA1 checksum.
/// </summary>
/// <value>SHA1 checksum.</value>
public string CurrentSHA1
{
get
{
return this.CurrentEventId == null ? null : this.History.Find(x => x.EventId == this.CurrentEventId).SHA1;
}
}
/// <summary>
/// Gets current file size.
/// </summary>
/// <value>File size.</value>
public long CurrentSize
{
get
{
return this.CurrentEventId == null ? 0 : this.History.Find(x => x.EventId == this.CurrentEventId).Size;
}
}
/// <summary>
/// Gets current parent id.
/// </summary>
/// <value>Current parent id.</value>
public string CurrentParentId
{
get
{
return this.CurrentEventId == null ? null : this.History.Find(x => x.EventId == this.CurrentEventId).EventId;
}
}
/// <summary>
/// Gets or sets history of the file.
/// </summary>
/// <value>The history of the file.</value>
public List<FileEvent> History { get; set; }
/// <summary>
/// Create the initial version.
/// </summary>
/// <param name="name">The name.</param>
/// <param name="when">Then when.</param>
public void Create(string name, DateTime when)
{
FileEvent vs = new FileEvent();
vs.FileId = this.Id;
vs.EventId = CommonHelper.GetRandomHash();
vs.ParentId = this.CurrentParentId;
vs.IsDirectory = this.IsDirectory;
vs.Name = name;
vs.When = when;
vs.SHA1 = null;
vs.Size = 0;
vs.Type = FileEventType.Created;
this.PushHistory(vs);
}
/// <summary>
/// Create a version of renaming
/// </summary>
/// <param name="name">The name.</param>
/// <param name="when">The when.</param>
public void Rename(string name, DateTime when)
{
FileEvent vs = new FileEvent();
vs.FileId = this.Id;
vs.EventId = CommonHelper.GetRandomHash();
vs.ParentId = this.CurrentParentId;
vs.IsDirectory = this.IsDirectory;
vs.Name = name;
vs.When = when;
vs.SHA1 = this.CurrentSHA1;
vs.Size = this.CurrentSize;
vs.Type = FileEventType.Renamed;
this.PushHistory(vs);
}
/// <summary>
/// Create a version of deleting
/// </summary>
/// <param name="when">The when.</param>
public void Delete(DateTime when)
{
FileEvent vs = new FileEvent();
vs.FileId = this.Id;
vs.EventId = CommonHelper.GetRandomHash();
vs.ParentId = this.CurrentParentId;
vs.IsDirectory = this.IsDirectory;
vs.Name = this.CurrentName;
vs.When = when;
vs.SHA1 = this.CurrentSHA1;
vs.Size = this.CurrentSize;
vs.Type = FileEventType.Deleted;
this.PushHistory(vs);
}
/// <summary>
/// Create a version of changing.
/// </summary>
/// <param name="name">The name.</param>
/// <param name="sha1">The SHA1.</param>
/// <param name="when">The when.</param>
public void Change(string name, string sha1, DateTime when)
{
if (this.CurrentSHA1 == sha1)
{
return;
}
FileEvent vs = new FileEvent();
vs.FileId = this.Id;
vs.EventId = CommonHelper.GetRandomHash();
vs.ParentId = this.CurrentParentId;
vs.IsDirectory = this.IsDirectory;
vs.Name = this.CurrentName;
vs.When = when;
vs.SHA1 = sha1;
vs.Size = this.IsDirectory || sha1 == null ? 0 : (new FileInfo(Config.MetaFolderData.File(vs.SHA1))).Length;
vs.Type = FileEventType.Changed;
this.PushHistory(vs);
}
/// <summary>
/// Checkout file.
/// </summary>
/// <param name="eventId">The event id.</param>
public void CheckOut(string eventId)
{
foreach (var item in this.History)
{
if (item.EventId == eventId)
{
GlobalFlag.AcceptFileEvent = false;
File.Delete(Config.RootFolder.File(this.CurrentName));
if (item.SHA1 == null)
{
File.WriteAllText(Config.RootFolder.File(item.Name), string.Empty);
}
else
{
File.Copy(Config.MetaFolderData.File(item.SHA1), Config.RootFolder.File(item.Name), true);
}
this.CurrentEventId = eventId;
GlobalFlag.AcceptFileEvent = true;
break;
}
}
}
/// <summary>
/// Merge the specified event.
/// </summary>
/// <param name="vs">The event.</param>
public void Merge(FileEvent vs)
{
if (this.History.Count() == 0)
{
this.Id = vs.FileId;
this.IsDirectory = vs.IsDirectory;
this.PushHistory(vs);
if (this.IsDirectory)
{
switch (vs.Type)
{
case FileEventType.Created:
GlobalFlag.AcceptFileEvent = false;
Directory.CreateDirectory(Config.RootFolder.Enter(vs.Name));
GlobalFlag.AcceptFileEvent = true;
break;
default:
Debug.Assert(false, "Not implement!");
break;
}
}
else
{
switch (vs.Type)
{
case FileEventType.Created:
if (vs.SHA1 == null)
{
GlobalFlag.AcceptFileEvent = false;
File.WriteAllText(Config.RootFolder.File(vs.Name), string.Empty);
GlobalFlag.AcceptFileEvent = true;
}
else
{
GlobalFlag.AcceptFileEvent = false;
File.Copy(Config.MetaFolderData.File(vs.SHA1), Config.RootFolder.File(vs.Name), true);
GlobalFlag.AcceptFileEvent = true;
}
break;
default:
Debug.Assert(false, "Not implement!");
break;
}
}
return;
}
FileEvent last = this.History.Last();
this.PushHistory(vs);
// Display changes
if (vs.When.Ticks > last.When.Ticks)
{
if (this.IsDirectory)
{
switch (vs.Type)
{
case FileEventType.Created:
GlobalFlag.AcceptFileEvent = false;
Directory.CreateDirectory(Config.RootFolder.Enter(vs.Name));
GlobalFlag.AcceptFileEvent = true;
break;
case FileEventType.Changed:
break;
case FileEventType.Renamed:
GlobalFlag.AcceptFileEvent = false;
Directory.Move(Config.RootFolder.Enter(last.Name), Config.RootFolder.Enter(vs.Name));
GlobalFlag.AcceptFileEvent = true;
break;
case FileEventType.Deleted:
GlobalFlag.AcceptFileEvent = false;
Directory.Delete(Config.RootFolder.Enter(vs.Name));
GlobalFlag.AcceptFileEvent = true;
break;
}
}
else
{
switch (vs.Type)
{
case FileEventType.Created:
if (vs.SHA1 == null)
{
GlobalFlag.AcceptFileEvent = false;
File.WriteAllText(Config.RootFolder.File(vs.Name), string.Empty);
GlobalFlag.AcceptFileEvent = true;
}
else
{
GlobalFlag.AcceptFileEvent = false;
File.Copy(Config.MetaFolderData.File(vs.SHA1), Config.RootFolder.File(vs.Name), true);
GlobalFlag.AcceptFileEvent = true;
}
break;
case FileEventType.Changed:
if (vs.SHA1 == null)
{
GlobalFlag.AcceptFileEvent = false;
File.WriteAllText(Config.RootFolder.File(vs.Name), string.Empty);
GlobalFlag.AcceptFileEvent = true;
}
else
{
GlobalFlag.AcceptFileEvent = false;
File.Copy(Config.MetaFolderData.File(vs.SHA1), Config.RootFolder.File(vs.Name), true);
GlobalFlag.AcceptFileEvent = true;
}
break;
case FileEventType.Renamed:
GlobalFlag.AcceptFileEvent = false;
File.Move(Config.RootFolder.File(last.Name), Config.RootFolder.File(vs.Name));
GlobalFlag.AcceptFileEvent = true;
break;
case FileEventType.Deleted:
GlobalFlag.AcceptFileEvent = false;
File.Delete(Config.RootFolder.File(vs.Name));
GlobalFlag.AcceptFileEvent = true;
break;
}
}
}
}
/// <summary>
/// Push the history.
/// </summary>
/// <param name="e">The event.</param>
private void PushHistory(FileEvent e)
{
this.History.Add(e);
this.History.Sort((x, y) => x.When.Ticks.CompareTo(y.When.Ticks));
this.CurrentEventId = e.EventId;
}
}
}
| |
using System;
using UIKit;
using CoreGraphics;
namespace Example_Drawing.Screens.iPad.Transformations
{
public class Controller : UIViewController
{
UIImageView imageView;
UIButton btnUp;
UIButton btnRight;
UIButton btnDown;
UIButton btnLeft;
UIButton btnReset;
UIButton btnRotateLeft;
UIButton btnRotateRight;
UIButton btnScaleUp;
UIButton btnScaleDown;
float currentScale, initialScale = 1.0f;
CGPoint currentLocation, initialLocation = new CGPoint(380, 500);
float currentRotation , initialRotation = 0;
float movementIncrement = 20;
float rotationIncrement = (float)(Math.PI * 2 / 16);
float scaleIncrement = 1.5f;
#region -= constructors =-
public Controller () : base()
{
currentScale = initialScale;
currentLocation = initialLocation;
currentRotation = initialRotation;
}
#endregion
public override void ViewDidLoad ()
{
base.ViewDidLoad ();
// set the background color of the view to white
View.BackgroundColor = UIColor.White;
// instantiate a new image view that takes up the whole screen and add it to
// the view hierarchy
CGRect imageViewFrame = new CGRect (0, -NavigationController.NavigationBar.Frame.Height, View.Frame.Width, View.Frame.Height);
imageView = new UIImageView (imageViewFrame);
View.AddSubview (imageView);
// add all of our buttons
InitializeButtons ();
DrawScreen ();
}
protected void DrawScreen ()
{
// create our offscreen bitmap context
// size
CGSize bitmapSize = new CGSize (imageView.Frame.Size);
using (CGBitmapContext context = new CGBitmapContext (IntPtr.Zero, (int)bitmapSize.Width, (int)bitmapSize.Height, 8, (int)(4 * bitmapSize.Width), CGColorSpace.CreateDeviceRGB (), CGImageAlphaInfo.PremultipliedFirst)) {
// save the state of the context while we change the CTM
context.SaveState ();
// draw our circle
context.SetFillColor (1, 0, 0, 1);
context.TranslateCTM (currentLocation.X, currentLocation.Y);
context.RotateCTM (currentRotation);
context.ScaleCTM (currentScale, currentScale);
context.FillRect (new CGRect (-10, -10, 20, 20));
// restore our transformations
context.RestoreState ();
// draw our coordinates for reference
DrawCoordinateSpace (context);
// output the drawing to the view
imageView.Image = UIImage.FromImage (context.ToImage ());
}
}
protected void InitializeButtons ()
{
InitButton (ref btnUp, new CGPoint (600, 20), 50, @"/\");
View.AddSubview (btnUp);
InitButton (ref btnRight, new CGPoint (660, 60), 50, ">");
View.AddSubview (btnRight);
InitButton (ref btnDown, new CGPoint (600, 100), 50, @"\/");
View.AddSubview (btnDown);
InitButton (ref btnLeft, new CGPoint (540, 60), 50, @"<");
View.AddSubview (btnLeft);
InitButton (ref btnReset, new CGPoint (600, 60), 50, @"X");
View.AddSubview (btnReset);
InitButton (ref btnRotateLeft, new CGPoint (540, 140), 75, "<@");
View.AddSubview (btnRotateLeft);
InitButton (ref btnRotateRight, new CGPoint (635, 140), 75, "@>");
View.AddSubview (btnRotateRight);
InitButton (ref btnScaleUp, new CGPoint (540, 180), 75, "+");
View.AddSubview (btnScaleUp);
InitButton (ref btnScaleDown, new CGPoint (635, 180), 75, "-");
View.AddSubview (btnScaleDown);
btnReset.TouchUpInside += delegate {
currentScale = initialScale;
currentLocation = initialLocation;
currentRotation = initialRotation;
DrawScreen();
};
btnUp.TouchUpInside += delegate {
currentLocation.Y += movementIncrement;
DrawScreen ();
};
btnDown.TouchUpInside += delegate {
currentLocation.Y -= movementIncrement;
DrawScreen ();
};
btnLeft.TouchUpInside += delegate {
currentLocation.X -= movementIncrement;
DrawScreen ();
};
btnRight.TouchUpInside += delegate {
currentLocation.X += movementIncrement;
DrawScreen ();
};
btnScaleUp.TouchUpInside += delegate {
currentScale = currentScale * scaleIncrement;
DrawScreen ();
};
btnScaleDown.TouchUpInside += delegate {
currentScale = currentScale / scaleIncrement;
DrawScreen ();
};
btnRotateLeft.TouchUpInside += delegate {
currentRotation += rotationIncrement;
DrawScreen ();
};
btnRotateRight.TouchUpInside += delegate {
currentRotation -= rotationIncrement;
DrawScreen ();
};
}
protected void InitButton (ref UIButton button, CGPoint location, float width, string text)
{
button = UIButton.FromType (UIButtonType.RoundedRect);
button.SetTitle (text, UIControlState.Normal);
button.Frame = new CGRect (location, new CGSize (width, 33));
}
// Draws the specified text starting at x,y of the specified height to the context.
protected void DrawTextAtPoint (CGContext context, float x, float y, string text, int textHeight)
{
// configure font
context.SelectFont ("Helvetica-Bold", textHeight, CGTextEncoding.MacRoman);
// set it to fill in our text, don't just outline
context.SetTextDrawingMode (CGTextDrawingMode.Fill);
// call showTextAtPoint
context.ShowTextAtPoint (x, y, text, text.Length);
}
/// <summary>
///
/// </summary>
protected void DrawCenteredTextAtPoint (CGContext context, float centerX, float y, string text, int textHeight)
{
context.SelectFont ("Helvetica-Bold", textHeight, CGTextEncoding.MacRoman);
context.SetTextDrawingMode (CGTextDrawingMode.Invisible);
context.ShowTextAtPoint (centerX, y, text, text.Length);
context.SetTextDrawingMode (CGTextDrawingMode.Fill);
context.ShowTextAtPoint (centerX - (context.TextPosition.X - centerX) / 2, y, text, text.Length);
}
/// <summary>
/// Draws our coordinate grid
/// </summary>
protected void DrawCoordinateSpace (CGBitmapContext context)
{
// declare vars
int remainder;
int textHeight = 20;
#region -= vertical ticks =-
// create our vertical tick lines
using (CGLayer verticalTickLayer = CGLayer.Create (context, new CGSize (20, 3))) {
// draw a single tick
verticalTickLayer.Context.FillRect (new CGRect (0, 1, 20, 2));
// draw a vertical tick every 20 pixels
float yPos = 20;
nint numberOfVerticalTicks = ((context.Height / 20) - 1);
for (int i = 0; i < numberOfVerticalTicks; i++) {
// draw the layer
context.DrawLayer (verticalTickLayer, new CGPoint (0, yPos));
// starting at 40, draw the coordinate text nearly to the top
if (yPos > 40 && i < (numberOfVerticalTicks - 2)) {
// draw it every 80 points
Math.DivRem ((int)yPos, (int)80, out remainder);
if (remainder == 0)
DrawTextAtPoint (context, 30, (yPos - (textHeight / 2)), yPos.ToString (), textHeight);
}
// increment the position of the next tick
yPos += 20;
}
}
#endregion
#region -= horizontal ticks =-
// create our horizontal tick lines
using (CGLayer horizontalTickLayer = CGLayer.Create (context, new CGSize (3, 20))) {
horizontalTickLayer.Context.FillRect (new CGRect (1, 0, 2, 20));
// draw a horizontal tick every 20 pixels
float xPos = 20;
nint numberOfHorizontalTicks = ((context.Width / 20) - 1);
for (int i = 0; i < numberOfHorizontalTicks; i++) {
context.DrawLayer (horizontalTickLayer, new CGPoint (xPos, 0));
// starting at 100, draw the coordinate text nearly to the top
if (xPos > 100 && i < (numberOfHorizontalTicks - 1)) {
// draw it every 80 points
Math.DivRem ((int)xPos, (int)80, out remainder);
if (remainder == 0)
DrawCenteredTextAtPoint (context, xPos, 30, xPos.ToString (), textHeight);
}
// increment the position of the next tick
xPos += 20;
}
}
#endregion
// draw our "origin" text
DrawTextAtPoint (context, 20, (20 + (textHeight / 2)), "Origin (0,0)", textHeight);
}
}
}
| |
/*
* $Id: Logger.cs 209 2006-12-22 19:11:35Z meebey $
* $URL: svn+ssh://svn.qnetp.net/svn/smartirc/SmartIrc4net/trunk/src/Logger.cs $
* $Rev: 209 $
* $Author: meebey $
* $Date: 2006-12-22 20:11:35 +0100 (Fri, 22 Dec 2006) $
*
* SmartIrc4net - the IRC library for .NET/C# <http://smartirc4net.sf.net>
*
* Copyright (c) 2003-2005 Mirco Bauer <[email protected]> <http://www.meebey.net>
*
* Full LGPL License: <http://www.gnu.org/licenses/lgpl.txt>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
using System.IO;
using System.Collections;
namespace Meebey.SmartIrc4net
{
#if LOG4NET
/// <summary>
///
/// </summary>
public enum LogCategory
{
Main,
Connection,
Socket,
Queue,
IrcMessages,
MessageTypes,
MessageParser,
ActionHandler,
TimeHandler,
MessageHandler,
ChannelSyncing,
UserSyncing,
Modules,
Dcc
}
/// <summary>
///
/// </summary>
/// <threadsafety static="true" instance="true" />
internal class Logger
{
private static SortedList _LoggerList = new SortedList();
private static bool _Init;
private Logger()
{
}
public static void Init()
{
if (_Init) {
return;
}
_Init = true;
/*
FileInfo fi = new FileInfo("SmartIrc4net_log.config");
if (fi.Exists) {
log4net.Config.DOMConfigurator.ConfigureAndWatch(fi);
} else {
log4net.Config.BasicConfigurator.Configure();
}
*/
_LoggerList[LogCategory.Main] = log4net.LogManager.GetLogger("MAIN");
_LoggerList[LogCategory.Socket] = log4net.LogManager.GetLogger("SOCKET");
_LoggerList[LogCategory.Queue] = log4net.LogManager.GetLogger("QUEUE");
_LoggerList[LogCategory.Connection] = log4net.LogManager.GetLogger("CONNECTION");
_LoggerList[LogCategory.IrcMessages] = log4net.LogManager.GetLogger("IRCMESSAGE");
_LoggerList[LogCategory.MessageParser] = log4net.LogManager.GetLogger("MESSAGEPARSER");
_LoggerList[LogCategory.MessageTypes] = log4net.LogManager.GetLogger("MESSAGETYPES");
_LoggerList[LogCategory.ActionHandler] = log4net.LogManager.GetLogger("ACTIONHANDLER");
_LoggerList[LogCategory.TimeHandler] = log4net.LogManager.GetLogger("TIMEHANDLER");
_LoggerList[LogCategory.MessageHandler] = log4net.LogManager.GetLogger("MESSAGEHANDLER");
_LoggerList[LogCategory.ChannelSyncing] = log4net.LogManager.GetLogger("CHANNELSYNCING");
_LoggerList[LogCategory.UserSyncing] = log4net.LogManager.GetLogger("USERSYNCING");
_LoggerList[LogCategory.Modules] = log4net.LogManager.GetLogger("MODULES");
_LoggerList[LogCategory.Dcc] = log4net.LogManager.GetLogger("DCC");
}
public static log4net.ILog Main
{
get {
return (log4net.ILog)_LoggerList[LogCategory.Main];
}
}
public static log4net.ILog Socket
{
get {
return (log4net.ILog)_LoggerList[LogCategory.Socket];
}
}
public static log4net.ILog Queue
{
get {
return (log4net.ILog)_LoggerList[LogCategory.Queue];
}
}
public static log4net.ILog Connection
{
get {
return (log4net.ILog)_LoggerList[LogCategory.Connection];
}
}
public static log4net.ILog IrcMessages
{
get {
return (log4net.ILog)_LoggerList[LogCategory.IrcMessages];
}
}
public static log4net.ILog MessageParser
{
get {
return (log4net.ILog)_LoggerList[LogCategory.MessageParser];
}
}
public static log4net.ILog MessageTypes
{
get {
return (log4net.ILog)_LoggerList[LogCategory.MessageTypes];
}
}
public static log4net.ILog ActionHandler
{
get {
return (log4net.ILog)_LoggerList[LogCategory.ActionHandler];
}
}
public static log4net.ILog TimeHandler
{
get {
return (log4net.ILog)_LoggerList[LogCategory.TimeHandler];
}
}
public static log4net.ILog MessageHandler
{
get {
return (log4net.ILog)_LoggerList[LogCategory.MessageHandler];
}
}
public static log4net.ILog ChannelSyncing
{
get {
return (log4net.ILog)_LoggerList[LogCategory.ChannelSyncing];
}
}
public static log4net.ILog UserSyncing
{
get {
return (log4net.ILog)_LoggerList[LogCategory.UserSyncing];
}
}
public static log4net.ILog Modules
{
get {
return (log4net.ILog)_LoggerList[LogCategory.Modules];
}
}
public static log4net.ILog Dcc
{
get {
return (log4net.ILog)_LoggerList[LogCategory.Dcc];
}
}
}
#endif
}
| |
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
// A copy from https://github.com/aspnet/HttpAbstractions/blob/057fc816fab1062700959cdaad2a32e9d85efca6/src/Microsoft.AspNetCore.WebUtilities/HttpResponseStreamWriter.cs
using System;
using System.Buffers;
using System.IO;
using System.Text;
using System.Threading.Tasks;
namespace GraphQL.NewtonsoftJson
{
/// <summary>
/// Writes to the <see cref="Stream"/> using the supplied <see cref="Encoding"/>.
/// It does not write the BOM and also does not close the stream.
/// </summary>
internal class HttpResponseStreamWriter : TextWriter
{
internal const int DEFAULT_BUFFER_SIZE = 16 * 1024;
private readonly Stream _stream;
private readonly Encoder _encoder;
private readonly ArrayPool<byte> _bytePool;
private readonly ArrayPool<char> _charPool;
private readonly int _charBufferSize;
private readonly byte[] _byteBuffer;
private readonly char[] _charBuffer;
private int _charBufferCount;
private bool _disposed;
public HttpResponseStreamWriter(Stream stream, Encoding encoding)
: this(stream, encoding, DEFAULT_BUFFER_SIZE, ArrayPool<byte>.Shared, ArrayPool<char>.Shared)
{
}
public HttpResponseStreamWriter(
Stream stream,
Encoding encoding,
int bufferSize,
ArrayPool<byte> bytePool,
ArrayPool<char> charPool)
{
_stream = stream ?? throw new ArgumentNullException(nameof(stream));
Encoding = encoding ?? throw new ArgumentNullException(nameof(encoding));
_bytePool = bytePool ?? throw new ArgumentNullException(nameof(bytePool));
_charPool = charPool ?? throw new ArgumentNullException(nameof(charPool));
if (bufferSize <= 0)
{
throw new ArgumentOutOfRangeException(nameof(bufferSize));
}
if (!_stream.CanWrite)
{
throw new ArgumentException("Stream is not writable", nameof(stream));
}
_charBufferSize = bufferSize;
_encoder = encoding.GetEncoder();
_charBuffer = charPool.Rent(bufferSize);
try
{
var requiredLength = encoding.GetMaxByteCount(bufferSize);
_byteBuffer = bytePool.Rent(requiredLength);
}
catch
{
charPool.Return(_charBuffer);
if (_byteBuffer != null)
{
bytePool.Return(_byteBuffer);
}
throw;
}
}
public override Encoding Encoding { get; }
public override void Write(char value)
{
if (_disposed)
{
throw new ObjectDisposedException(nameof(HttpResponseStreamWriter));
}
if (_charBufferCount == _charBufferSize)
{
FlushInternal(flushEncoder: false);
}
_charBuffer[_charBufferCount] = value;
_charBufferCount++;
}
public override void Write(char[] values, int index, int count)
{
if (_disposed)
{
throw new ObjectDisposedException(nameof(HttpResponseStreamWriter));
}
if (values == null)
{
return;
}
while (count > 0)
{
if (_charBufferCount == _charBufferSize)
{
FlushInternal(flushEncoder: false);
}
CopyToCharBuffer(values, ref index, ref count);
}
}
public override void Write(string value)
{
if (_disposed)
{
throw new ObjectDisposedException(nameof(HttpResponseStreamWriter));
}
if (value == null)
{
return;
}
var count = value.Length;
var index = 0;
while (count > 0)
{
if (_charBufferCount == _charBufferSize)
{
FlushInternal(flushEncoder: false);
}
CopyToCharBuffer(value, ref index, ref count);
}
}
public override async Task WriteAsync(char value)
{
if (_disposed)
{
throw new ObjectDisposedException(nameof(HttpResponseStreamWriter));
}
if (_charBufferCount == _charBufferSize)
{
await FlushInternalAsync(flushEncoder: false).ConfigureAwait(false);
}
_charBuffer[_charBufferCount] = value;
_charBufferCount++;
}
public override async Task WriteAsync(char[] values, int index, int count)
{
if (_disposed)
{
throw new ObjectDisposedException(nameof(HttpResponseStreamWriter));
}
if (values == null)
{
return;
}
while (count > 0)
{
if (_charBufferCount == _charBufferSize)
{
await FlushInternalAsync(flushEncoder: false).ConfigureAwait(false);
}
CopyToCharBuffer(values, ref index, ref count);
}
}
public override async Task WriteAsync(string value)
{
if (_disposed)
{
throw new ObjectDisposedException(nameof(HttpResponseStreamWriter));
}
if (value == null)
{
return;
}
var count = value.Length;
var index = 0;
while (count > 0)
{
if (_charBufferCount == _charBufferSize)
{
await FlushInternalAsync(flushEncoder: false).ConfigureAwait(false);
}
CopyToCharBuffer(value, ref index, ref count);
}
}
// We want to flush the stream when Flush/FlushAsync is explicitly
// called by the user (example: from a Razor view).
public override void Flush()
{
if (_disposed)
{
throw new ObjectDisposedException(nameof(HttpResponseStreamWriter));
}
FlushInternal(flushEncoder: true);
}
public override Task FlushAsync()
{
if (_disposed)
{
throw new ObjectDisposedException(nameof(HttpResponseStreamWriter));
}
return FlushInternalAsync(flushEncoder: true);
}
protected override void Dispose(bool disposing)
{
if (disposing && !_disposed)
{
_disposed = true;
try
{
FlushInternal(flushEncoder: true);
}
finally
{
_bytePool.Return(_byteBuffer);
_charPool.Return(_charBuffer);
}
}
base.Dispose(disposing);
}
// Note: our FlushInternal method does NOT flush the underlying stream. This would result in
// chunking.
private void FlushInternal(bool flushEncoder)
{
if (_charBufferCount == 0)
{
return;
}
var count = _encoder.GetBytes(
_charBuffer,
0,
_charBufferCount,
_byteBuffer,
0,
flush: flushEncoder);
_charBufferCount = 0;
if (count > 0)
{
_stream.Write(_byteBuffer, 0, count);
}
}
// Note: our FlushInternalAsync method does NOT flush the underlying stream. This would result in
// chunking.
private async Task FlushInternalAsync(bool flushEncoder)
{
if (_charBufferCount == 0)
{
return;
}
var count = _encoder.GetBytes(
_charBuffer,
0,
_charBufferCount,
_byteBuffer,
0,
flush: flushEncoder);
_charBufferCount = 0;
if (count > 0)
{
await _stream.WriteAsync(_byteBuffer, 0, count).ConfigureAwait(false);
}
}
private void CopyToCharBuffer(string value, ref int index, ref int count)
{
var remaining = Math.Min(_charBufferSize - _charBufferCount, count);
value.CopyTo(
sourceIndex: index,
destination: _charBuffer,
destinationIndex: _charBufferCount,
count: remaining);
_charBufferCount += remaining;
index += remaining;
count -= remaining;
}
private void CopyToCharBuffer(char[] values, ref int index, ref int count)
{
var remaining = Math.Min(_charBufferSize - _charBufferCount, count);
Buffer.BlockCopy(
src: values,
srcOffset: index * sizeof(char),
dst: _charBuffer,
dstOffset: _charBufferCount * sizeof(char),
count: remaining * sizeof(char));
_charBufferCount += remaining;
index += remaining;
count -= remaining;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Text;
using System.Xml;
using System.Xml.Serialization;
using Texture2D = Microsoft.Xna.Framework.Graphics.Texture2D;
//TODO: the AnimationChain namespace in the content assembly should probably be renamed to avoid this naming conflict
using Anim = FlatRedBall.Graphics.Animation;
using FlatRedBall.IO;
using FlatRedBall.Graphics.Animation;
using FlatRedBall.Graphics.Texture;
using FlatRedBall.Graphics;
using System.Globalization;
namespace FlatRedBall.Content.AnimationChain
{
[XmlRoot("AnimationChain")]
#if !UWP && !WINDOWS_8
[Serializable]
#endif
public class AnimationChainSave
{
#region Fields
public string Name;
/// <summary>
/// This is used if the AnimationChain actually comes from
/// a file like a .gif.
/// </summary>
public string ParentFile;
[XmlElementAttribute("Frame")]
public List<AnimationFrameSave> Frames = new List<AnimationFrameSave>();
#endregion
#region Methods
public AnimationChainSave()
{ }
internal static AnimationChainSave FromAnimationChain(Anim.AnimationChain animationChain, TimeMeasurementUnit timeMeasurementUnit)
{
AnimationChainSave animationChainSave = new AnimationChainSave();
animationChainSave.Frames = new List<AnimationFrameSave>();
animationChainSave.Name = animationChain.Name;
foreach (Anim.AnimationFrame frame in animationChain)
{
AnimationFrameSave save = new AnimationFrameSave(frame);
animationChainSave.Frames.Add(save);
}
if (!string.IsNullOrEmpty(animationChain.ParentGifFileName))
{
animationChainSave.ParentFile = animationChain.ParentGifFileName;
}
return animationChainSave;
}
public void MakeRelative()
{
foreach (AnimationFrameSave afs in Frames)
{
if (!string.IsNullOrEmpty(afs.TextureName) && FileManager.IsRelative(afs.TextureName) == false)
{
afs.TextureName = FileManager.MakeRelative(afs.TextureName);
}
}
if (string.IsNullOrEmpty(ParentFile) == false && FileManager.IsRelative(ParentFile) == false)
{
ParentFile = FileManager.MakeRelative(ParentFile);
}
}
//public Anim.AnimationChain ToAnimationChain(Graphics.Texture.TextureAtlas textureAtlas, TimeMeasurementUnit timeMeasurementUnit)
//{
// return ToAnimationChain(null, textureAtlas, timeMeasurementUnit, TextureCoordinateType.UV);
//}
public Anim.AnimationChain ToAnimationChain(string contentManagerName, TimeMeasurementUnit timeMeasurementUnit)
{
return ToAnimationChain(contentManagerName, timeMeasurementUnit, TextureCoordinateType.UV);
}
public Anim.AnimationChain ToAnimationChain(string contentManagerName, TimeMeasurementUnit timeMeasurementUnit, TextureCoordinateType coordinateType)
{
if (!string.IsNullOrEmpty(ParentFile))
{
#if !WINDOWS_8 && !UWP && !DESKTOP_GL && !STANDARD
FlatRedBall.Graphics.Animation.AnimationChain animationChain =
FlatRedBall.Graphics.Animation.AnimationChain.FromGif(
ParentFile, contentManagerName);
animationChain.Name = Name;
animationChain.ParentGifFileName = ParentFile;
if (animationChain.Count == this.Frames.Count)
{
for (int i = 0; i < animationChain.Count; i++)
{
animationChain[i].FlipHorizontal = Frames[i].FlipHorizontal;
animationChain[i].FlipVertical = Frames[i].FlipVertical;
animationChain[i].FrameLength = Frames[i].FrameLength;
animationChain[i].RelativeX = Frames[i].RelativeX;
animationChain[i].RelativeY = Frames[i].RelativeY;
animationChain[i].TopCoordinate = Frames[i].TopCoordinate;
animationChain[i].BottomCoordinate = Frames[i].BottomCoordinate;
animationChain[i].LeftCoordinate = Frames[i].LeftCoordinate;
animationChain[i].RightCoordinate = Frames[i].RightCoordinate;
}
}
return animationChain;
#else
throw new NotImplementedException();
#endif
}
else
{
Anim.AnimationChain animationChain =
new Anim.AnimationChain();
animationChain.Name = Name;
float divisor = 1;
if (timeMeasurementUnit == TimeMeasurementUnit.Millisecond)
divisor = 1000;
foreach (AnimationFrameSave save in Frames)
{
// process the AnimationFrame and add it to the newly-created AnimationChain
AnimationFrame frame = null;
bool loadTexture = true;
frame = save.ToAnimationFrame(contentManagerName, loadTexture, coordinateType);
frame.FrameLength /= divisor;
animationChain.Add(frame);
}
return animationChain;
}
}
// private Anim.AnimationChain ToAnimationChain(string contentManagerName, TextureAtlas textureAtlas,
// TimeMeasurementUnit timeMeasurementUnit, TextureCoordinateType coordinateType)
// {
// if (!string.IsNullOrEmpty(ParentFile))
// {
//#if !WINDOWS_8
// FlatRedBall.Graphics.Animation.AnimationChain animationChain =
// FlatRedBall.Graphics.Animation.AnimationChain.FromGif(
// ParentFile, contentManagerName);
// animationChain.Name = Name;
// animationChain.ParentGifFileName = ParentFile;
// if (animationChain.Count == this.Frames.Count)
// {
// for (int i = 0; i < animationChain.Count; i++)
// {
// animationChain[i].FlipHorizontal = Frames[i].FlipHorizontal;
// animationChain[i].FlipVertical = Frames[i].FlipVertical;
// animationChain[i].FrameLength = Frames[i].FrameLength;
// animationChain[i].RelativeX = Frames[i].RelativeX;
// animationChain[i].RelativeY = Frames[i].RelativeY;
// animationChain[i].TopCoordinate = Frames[i].TopCoordinate;
// animationChain[i].BottomCoordinate = Frames[i].BottomCoordinate;
// animationChain[i].LeftCoordinate = Frames[i].LeftCoordinate;
// animationChain[i].RightCoordinate = Frames[i].RightCoordinate;
// }
// }
// return animationChain;
//#else
// throw new NotImplementedException();
//#endif
// }
// else
// {
// Anim.AnimationChain animationChain =
// new Anim.AnimationChain();
// animationChain.Name = Name;
// float divisor = 1;
// if (timeMeasurementUnit == TimeMeasurementUnit.Millisecond)
// divisor = 1000;
// foreach (AnimationFrameSave save in Frames)
// {
// // process the AnimationFrame and add it to the newly-created AnimationChain
// AnimationFrame frame = null;
// if (textureAtlas == null)
// {
// bool loadTexture = true;
// frame = save.ToAnimationFrame(contentManagerName, loadTexture, coordinateType);
// }
// else
// {
// frame = save.ToAnimationFrame(textureAtlas);
// }
// frame.FrameLength /= divisor;
// animationChain.Add(frame);
// }
// return animationChain;
// }
// }
public override string ToString()
{
return this.Name + " with " + this.Frames.Count + " frames";
}
#endregion
internal static AnimationChainSave FromXElement(System.Xml.Linq.XElement element)
{
AnimationChainSave toReturn = new AnimationChainSave();
foreach (var subElement in element.Elements())
{
switch (subElement.Name.LocalName)
{
case "Name":
toReturn.Name = subElement.Value;
break;
case "Frame":
toReturn.Frames.Add(AnimationFrameSave.FromXElement(subElement));
break;
}
}
return toReturn;
}
private static uint AsUint(System.Xml.Linq.XElement element)
{
return uint.Parse(element.Value, CultureInfo.InvariantCulture);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using BTCPayServer.Abstractions.Constants;
using BTCPayServer.Abstractions.Extensions;
using BTCPayServer.Abstractions.Models;
using BTCPayServer.BIP78.Sender;
using BTCPayServer.HostedServices;
using BTCPayServer.ModelBinders;
using BTCPayServer.Models;
using BTCPayServer.Models.WalletViewModels;
using BTCPayServer.Payments.PayJoin.Sender;
using BTCPayServer.Services;
using Microsoft.AspNetCore.Mvc;
using NBitcoin;
using NBitcoin.Payment;
using NBXplorer;
using NBXplorer.Models;
namespace BTCPayServer.Controllers
{
public partial class UIWalletsController
{
[NonAction]
public async Task<CreatePSBTResponse> CreatePSBT(BTCPayNetwork network, DerivationSchemeSettings derivationSettings, WalletSendModel sendModel, CancellationToken cancellationToken)
{
var nbx = ExplorerClientProvider.GetExplorerClient(network);
CreatePSBTRequest psbtRequest = new CreatePSBTRequest();
if (sendModel.InputSelection)
{
psbtRequest.IncludeOnlyOutpoints = sendModel.SelectedInputs?.Select(OutPoint.Parse)?.ToList() ?? new List<OutPoint>();
}
foreach (var transactionOutput in sendModel.Outputs)
{
var psbtDestination = new CreatePSBTDestination();
psbtRequest.Destinations.Add(psbtDestination);
psbtDestination.Destination = BitcoinAddress.Create(transactionOutput.DestinationAddress, network.NBitcoinNetwork);
psbtDestination.Amount = Money.Coins(transactionOutput.Amount.Value);
psbtDestination.SubstractFees = transactionOutput.SubtractFeesFromOutput;
}
if (network.SupportRBF)
{
if (sendModel.AllowFeeBump is WalletSendModel.ThreeStateBool.Yes)
psbtRequest.RBF = true;
if (sendModel.AllowFeeBump is WalletSendModel.ThreeStateBool.No)
psbtRequest.RBF = false;
}
psbtRequest.AlwaysIncludeNonWitnessUTXO = sendModel.AlwaysIncludeNonWitnessUTXO;
psbtRequest.FeePreference = new FeePreference();
if (sendModel.FeeSatoshiPerByte is decimal v &&
v > decimal.Zero)
{
psbtRequest.FeePreference.ExplicitFeeRate = new FeeRate(v);
}
if (sendModel.NoChange)
{
psbtRequest.ExplicitChangeAddress = psbtRequest.Destinations.First().Destination;
}
var psbt = (await nbx.CreatePSBTAsync(derivationSettings.AccountDerivation, psbtRequest, cancellationToken));
if (psbt == null)
throw new NotSupportedException("You need to update your version of NBXplorer");
// Not supported by coldcard, remove when they do support it
psbt.PSBT.GlobalXPubs.Clear();
return psbt;
}
[HttpPost("{walletId}/cpfp")]
public async Task<IActionResult> WalletCPFP([ModelBinder(typeof(WalletIdModelBinder))]
WalletId walletId, string[] outpoints, string[] transactionHashes, string returnUrl)
{
outpoints ??= Array.Empty<string>();
transactionHashes ??= Array.Empty<string>();
var network = NetworkProvider.GetNetwork<BTCPayNetwork>(walletId.CryptoCode);
var explorer = ExplorerClientProvider.GetExplorerClient(network);
var fr = _feeRateProvider.CreateFeeProvider(network);
var targetFeeRate = await fr.GetFeeRateAsync(1);
// Since we don't know the actual fee rate paid by a tx from NBX
// we just assume that it is 20 blocks
var assumedFeeRate = await fr.GetFeeRateAsync(20);
var settings = (this.GetCurrentStore().GetDerivationSchemeSettings(NetworkProvider, network.CryptoCode));
var derivationScheme = settings.AccountDerivation;
if (derivationScheme is null)
return NotFound();
var utxos = await explorer.GetUTXOsAsync(derivationScheme);
var outpointsHashet = outpoints.ToHashSet();
var transactionHashesSet = transactionHashes.ToHashSet();
var bumpableUTXOs = utxos.GetUnspentUTXOs().Where(u => u.Confirmations == 0 &&
(outpointsHashet.Contains(u.Outpoint.ToString()) ||
transactionHashesSet.Contains(u.Outpoint.Hash.ToString()))).ToArray();
if (bumpableUTXOs.Length == 0)
{
TempData[WellKnownTempData.ErrorMessage] = "There isn't any UTXO available to bump fee";
return Redirect(returnUrl);
}
Money bumpFee = Money.Zero;
foreach (var txid in bumpableUTXOs.Select(u => u.TransactionHash).ToHashSet())
{
var tx = await explorer.GetTransactionAsync(txid);
var vsize = tx.Transaction.GetVirtualSize();
var assumedFeePaid = assumedFeeRate.GetFee(vsize);
var expectedFeePaid = targetFeeRate.GetFee(vsize);
bumpFee += Money.Max(Money.Zero, expectedFeePaid - assumedFeePaid);
}
var returnAddress = (await explorer.GetUnusedAsync(derivationScheme, NBXplorer.DerivationStrategy.DerivationFeature.Deposit)).Address;
TransactionBuilder builder = explorer.Network.NBitcoinNetwork.CreateTransactionBuilder();
builder.AddCoins(bumpableUTXOs.Select(utxo => utxo.AsCoin(derivationScheme)));
// The fee of the bumped transaction should pay for both, the fee
// of the bump transaction and those that are being bumped
builder.SendEstimatedFees(targetFeeRate);
builder.SendFees(bumpFee);
builder.SendAll(returnAddress);
var psbt = builder.BuildPSBT(false);
psbt = (await explorer.UpdatePSBTAsync(new UpdatePSBTRequest()
{
PSBT = psbt,
DerivationScheme = derivationScheme
})).PSBT;
return View("PostRedirect", new PostRedirectViewModel
{
AspController = "UIWallets",
AspAction = nameof(UIWalletsController.WalletSign),
RouteParameters = {
{ "walletId", walletId.ToString() },
{ "returnUrl", returnUrl }
},
FormParameters =
{
{ "walletId", walletId.ToString() },
{ "psbt", psbt.ToHex() }
}
});
}
[HttpPost("{walletId}/sign")]
public async Task<IActionResult> WalletSign([ModelBinder(typeof(WalletIdModelBinder))]
WalletId walletId, WalletPSBTViewModel vm, string returnUrl = null, string command = null)
{
var network = NetworkProvider.GetNetwork<BTCPayNetwork>(walletId.CryptoCode);
if (returnUrl is null)
returnUrl = Url.Action(nameof(WalletTransactions), new { walletId });
var psbt = await vm.GetPSBT(network.NBitcoinNetwork);
if (psbt is null || vm.InvalidPSBT)
{
ModelState.AddModelError(nameof(vm.PSBT), "Invalid PSBT");
return View("WalletSigningOptions", new WalletSigningOptionsModel(vm.SigningContext, returnUrl));
}
switch (command)
{
case "vault":
return ViewVault(walletId, vm.SigningContext);
case "seed":
return SignWithSeed(walletId, vm.SigningContext);
case "decode":
return await WalletPSBT(walletId, vm, "decode");
default:
break;
}
if (await CanUseHotWallet())
{
var derivationScheme = GetDerivationSchemeSettings(walletId);
if (derivationScheme.IsHotWallet)
{
var extKey = await ExplorerClientProvider.GetExplorerClient(walletId.CryptoCode)
.GetMetadataAsync<string>(derivationScheme.AccountDerivation,
WellknownMetadataKeys.MasterHDKey);
if (extKey != null)
{
return await SignWithSeed(walletId,
new SignWithSeedViewModel { SeedOrKey = extKey, SigningContext = vm.SigningContext });
}
}
}
return View("WalletSigningOptions", new WalletSigningOptionsModel(vm.SigningContext, returnUrl));
}
[HttpGet("{walletId}/psbt")]
public async Task<IActionResult> WalletPSBT([ModelBinder(typeof(WalletIdModelBinder))]
WalletId walletId)
{
var network = NetworkProvider.GetNetwork<BTCPayNetwork>(walletId.CryptoCode);
var vm = new WalletPSBTViewModel();
vm.CryptoCode = network.CryptoCode;
var derivationSchemeSettings = GetDerivationSchemeSettings(walletId);
if (derivationSchemeSettings == null)
return NotFound();
vm.NBXSeedAvailable = await CanUseHotWallet() && derivationSchemeSettings.IsHotWallet;
return View(vm);
}
[HttpPost("{walletId}/psbt")]
public async Task<IActionResult> WalletPSBT(
[ModelBinder(typeof(WalletIdModelBinder))]
WalletId walletId,
WalletPSBTViewModel vm, string command)
{
var network = NetworkProvider.GetNetwork<BTCPayNetwork>(walletId.CryptoCode);
vm.CryptoCode = network.CryptoCode;
var derivationSchemeSettings = GetDerivationSchemeSettings(walletId);
if (derivationSchemeSettings == null)
return NotFound();
vm.NBXSeedAvailable = await CanUseHotWallet() && derivationSchemeSettings.IsHotWallet;
var psbt = await vm.GetPSBT(network.NBitcoinNetwork);
if (vm.InvalidPSBT)
{
ModelState.AddModelError(nameof(vm.PSBT), "Invalid PSBT");
return View(vm);
}
if (psbt is null)
{
return View("WalletPSBT", vm);
}
switch (command)
{
case "sign":
return await WalletSign(walletId, vm);
case "decode":
ModelState.Remove(nameof(vm.PSBT));
ModelState.Remove(nameof(vm.FileName));
ModelState.Remove(nameof(vm.UploadedPSBTFile));
await FetchTransactionDetails(derivationSchemeSettings, vm, network);
return View("WalletPSBTDecoded", vm);
case "save-psbt":
return FilePSBT(psbt, vm.FileName);
case "update":
psbt = await ExplorerClientProvider.UpdatePSBT(derivationSchemeSettings, psbt);
if (psbt == null)
{
TempData[WellKnownTempData.ErrorMessage] = "You need to update your version of NBXplorer";
return View(vm);
}
TempData[WellKnownTempData.SuccessMessage] = "PSBT updated!";
return RedirectToWalletPSBT(new WalletPSBTViewModel
{
PSBT = psbt.ToBase64(),
FileName = vm.FileName
});
case "combine":
ModelState.Remove(nameof(vm.PSBT));
return View(nameof(WalletPSBTCombine), new WalletPSBTCombineViewModel { OtherPSBT = psbt.ToBase64() });
case "broadcast":
{
return RedirectToWalletPSBTReady(new WalletPSBTReadyViewModel
{
SigningContext = new SigningContextModel(psbt)
});
}
default:
return View("WalletPSBTDecoded", vm);
}
}
private async Task<PSBT> GetPayjoinProposedTX(BitcoinUrlBuilder bip21, PSBT psbt, DerivationSchemeSettings derivationSchemeSettings, BTCPayNetwork btcPayNetwork, CancellationToken cancellationToken)
{
var cloned = psbt.Clone();
cloned = cloned.Finalize();
await _broadcaster.Schedule(DateTimeOffset.UtcNow + TimeSpan.FromMinutes(2.0), cloned.ExtractTransaction(), btcPayNetwork);
using var cts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
cts.CancelAfter(TimeSpan.FromSeconds(30));
return await _payjoinClient.RequestPayjoin(bip21, new PayjoinWallet(derivationSchemeSettings), psbt, cts.Token);
}
private async Task FetchTransactionDetails(DerivationSchemeSettings derivationSchemeSettings, WalletPSBTReadyViewModel vm, BTCPayNetwork network)
{
var psbtObject = PSBT.Parse(vm.SigningContext.PSBT, network.NBitcoinNetwork);
if (!psbtObject.IsAllFinalized())
psbtObject = await ExplorerClientProvider.UpdatePSBT(derivationSchemeSettings, psbtObject) ?? psbtObject;
IHDKey signingKey = null;
RootedKeyPath signingKeyPath = null;
try
{
signingKey = new BitcoinExtPubKey(vm.SigningKey, network.NBitcoinNetwork);
}
catch { }
try
{
signingKey = signingKey ?? new BitcoinExtKey(vm.SigningKey, network.NBitcoinNetwork);
}
catch { }
try
{
signingKeyPath = RootedKeyPath.Parse(vm.SigningKeyPath);
}
catch { }
if (signingKey == null || signingKeyPath == null)
{
var signingKeySettings = derivationSchemeSettings.GetSigningAccountKeySettings();
if (signingKey == null)
{
signingKey = signingKeySettings.AccountKey;
vm.SigningKey = signingKey.ToString();
}
if (vm.SigningKeyPath == null)
{
signingKeyPath = signingKeySettings.GetRootedKeyPath();
vm.SigningKeyPath = signingKeyPath?.ToString();
}
}
if (psbtObject.IsAllFinalized())
{
vm.CanCalculateBalance = false;
}
else
{
var balanceChange = psbtObject.GetBalance(derivationSchemeSettings.AccountDerivation, signingKey, signingKeyPath);
vm.BalanceChange = ValueToString(balanceChange, network);
vm.CanCalculateBalance = true;
vm.Positive = balanceChange >= Money.Zero;
}
vm.Inputs = new List<WalletPSBTReadyViewModel.InputViewModel>();
foreach (var input in psbtObject.Inputs)
{
var inputVm = new WalletPSBTReadyViewModel.InputViewModel();
vm.Inputs.Add(inputVm);
var mine = input.HDKeysFor(derivationSchemeSettings.AccountDerivation, signingKey, signingKeyPath).Any();
var balanceChange2 = input.GetTxOut()?.Value ?? Money.Zero;
if (mine)
balanceChange2 = -balanceChange2;
inputVm.BalanceChange = ValueToString(balanceChange2, network);
inputVm.Positive = balanceChange2 >= Money.Zero;
inputVm.Index = (int)input.Index;
}
vm.Destinations = new List<WalletPSBTReadyViewModel.DestinationViewModel>();
foreach (var output in psbtObject.Outputs)
{
var dest = new WalletPSBTReadyViewModel.DestinationViewModel();
vm.Destinations.Add(dest);
var mine = output.HDKeysFor(derivationSchemeSettings.AccountDerivation, signingKey, signingKeyPath).Any();
var balanceChange2 = output.Value;
if (!mine)
balanceChange2 = -balanceChange2;
dest.Balance = ValueToString(balanceChange2, network);
dest.Positive = balanceChange2 >= Money.Zero;
dest.Destination = output.ScriptPubKey.GetDestinationAddress(network.NBitcoinNetwork)?.ToString() ?? output.ScriptPubKey.ToString();
}
if (psbtObject.TryGetFee(out var fee))
{
vm.Destinations.Add(new WalletPSBTReadyViewModel.DestinationViewModel
{
Positive = false,
Balance = ValueToString(-fee, network),
Destination = "Mining fees"
});
}
if (psbtObject.TryGetEstimatedFeeRate(out var feeRate))
{
vm.FeeRate = feeRate.ToString();
}
var sanityErrors = psbtObject.CheckSanity();
if (sanityErrors.Count != 0)
{
vm.SetErrors(sanityErrors);
}
else if (!psbtObject.IsAllFinalized() && !psbtObject.TryFinalize(out var errors))
{
vm.SetErrors(errors);
}
}
[HttpPost("{walletId}/psbt/ready")]
public async Task<IActionResult> WalletPSBTReady(
[ModelBinder(typeof(WalletIdModelBinder))]
WalletId walletId, WalletPSBTViewModel vm, string command, CancellationToken cancellationToken = default)
{
var network = NetworkProvider.GetNetwork<BTCPayNetwork>(walletId.CryptoCode);
PSBT psbt = await vm.GetPSBT(network.NBitcoinNetwork);
if (vm.InvalidPSBT || psbt is null)
{
if (vm.InvalidPSBT)
vm.GlobalError = "Invalid PSBT";
return View(nameof(WalletPSBT), vm);
}
DerivationSchemeSettings derivationSchemeSettings = GetDerivationSchemeSettings(walletId);
if (derivationSchemeSettings == null)
return NotFound();
await FetchTransactionDetails(derivationSchemeSettings, vm, network);
switch (command)
{
case "payjoin":
string error;
try
{
var proposedPayjoin = await GetPayjoinProposedTX(new BitcoinUrlBuilder(vm.SigningContext.PayJoinBIP21, network.NBitcoinNetwork), psbt,
derivationSchemeSettings, network, cancellationToken);
try
{
proposedPayjoin.Settings.SigningOptions = new SigningOptions
{
EnforceLowR = !(vm.SigningContext?.EnforceLowR is false)
};
var extKey = ExtKey.Parse(vm.SigningKey, network.NBitcoinNetwork);
proposedPayjoin = proposedPayjoin.SignAll(derivationSchemeSettings.AccountDerivation,
extKey,
RootedKeyPath.Parse(vm.SigningKeyPath));
vm.SigningContext.PSBT = proposedPayjoin.ToBase64();
vm.SigningContext.OriginalPSBT = psbt.ToBase64();
proposedPayjoin.Finalize();
var hash = proposedPayjoin.ExtractTransaction().GetHash();
_EventAggregator.Publish(new UpdateTransactionLabel(walletId, hash, UpdateTransactionLabel.PayjoinLabelTemplate()));
TempData.SetStatusMessageModel(new StatusMessageModel
{
Severity = StatusMessageModel.StatusSeverity.Success,
AllowDismiss = false,
Html = $"The payjoin transaction has been successfully broadcasted ({proposedPayjoin.ExtractTransaction().GetHash()})"
});
return await WalletPSBTReady(walletId, vm, "broadcast");
}
catch (Exception)
{
TempData.SetStatusMessageModel(new StatusMessageModel()
{
Severity = StatusMessageModel.StatusSeverity.Warning,
AllowDismiss = false,
Html =
"This transaction has been coordinated between the receiver and you to create a <a href='https://en.bitcoin.it/wiki/PayJoin' target='_blank'>payjoin transaction</a> by adding inputs from the receiver.<br/>" +
"The amount being sent may appear higher but is in fact almost same.<br/><br/>" +
"If you cancel or refuse to sign this transaction, the payment will proceed without payjoin"
});
vm.SigningContext.PSBT = proposedPayjoin.ToBase64();
vm.SigningContext.OriginalPSBT = psbt.ToBase64();
return ViewVault(walletId, vm.SigningContext);
}
}
catch (PayjoinReceiverException ex)
{
error = $"The payjoin receiver could not complete the payjoin: {ex.Message}";
}
catch (PayjoinSenderException ex)
{
error = $"We rejected the receiver's payjoin proposal: {ex.Message}";
}
catch (Exception ex)
{
error = $"Unexpected payjoin error: {ex.Message}";
}
//we possibly exposed the tx to the receiver, so we need to broadcast straight away
psbt.Finalize();
TempData.SetStatusMessageModel(new StatusMessageModel
{
Severity = StatusMessageModel.StatusSeverity.Warning,
AllowDismiss = false,
Html = $"The payjoin transaction could not be created.<br/>" +
$"The original transaction was broadcasted instead. ({psbt.ExtractTransaction().GetHash()})<br/><br/>" +
$"{error}"
});
return await WalletPSBTReady(walletId, vm, "broadcast");
case "broadcast" when !psbt.IsAllFinalized() && !psbt.TryFinalize(out var errors):
vm.SetErrors(errors);
return View(nameof(WalletPSBT), vm);
case "broadcast":
{
var transaction = psbt.ExtractTransaction();
try
{
var broadcastResult = await ExplorerClientProvider.GetExplorerClient(network).BroadcastAsync(transaction);
if (!broadcastResult.Success)
{
if (!string.IsNullOrEmpty(vm.SigningContext.OriginalPSBT))
{
TempData.SetStatusMessageModel(new StatusMessageModel
{
Severity = StatusMessageModel.StatusSeverity.Warning,
AllowDismiss = false,
Html = $"The payjoin transaction could not be broadcasted.<br/>({broadcastResult.RPCCode} {broadcastResult.RPCCodeMessage} {broadcastResult.RPCMessage}).<br/>The transaction has been reverted back to its original format and has been broadcast."
});
vm.SigningContext.PSBT = vm.SigningContext.OriginalPSBT;
vm.SigningContext.OriginalPSBT = null;
return await WalletPSBTReady(walletId, vm, "broadcast");
}
vm.GlobalError = $"RPC Error while broadcasting: {broadcastResult.RPCCode} {broadcastResult.RPCCodeMessage} {broadcastResult.RPCMessage}";
return View(nameof(WalletPSBT), vm);
}
else
{
var wallet = _walletProvider.GetWallet(network);
var derivationSettings = GetDerivationSchemeSettings(walletId);
wallet.InvalidateCache(derivationSettings.AccountDerivation);
}
}
catch (Exception ex)
{
vm.GlobalError = "Error while broadcasting: " + ex.Message;
return View(nameof(WalletPSBT), vm);
}
if (!TempData.HasStatusMessage())
{
TempData[WellKnownTempData.SuccessMessage] = $"Transaction broadcasted successfully ({transaction.GetHash()})";
}
var returnUrl = this.HttpContext.Request.Query["returnUrl"].FirstOrDefault();
if (returnUrl is not null)
{
return Redirect(returnUrl);
}
return RedirectToAction(nameof(WalletTransactions), new { walletId = walletId.ToString() });
}
case "analyze-psbt":
return RedirectToWalletPSBT(new WalletPSBTViewModel()
{
PSBT = psbt.ToBase64()
});
case "decode":
await FetchTransactionDetails(derivationSchemeSettings, vm, network);
return View("WalletPSBTDecoded", vm);
default:
vm.GlobalError = "Unknown command";
return View(nameof(WalletPSBT), vm);
}
}
private IActionResult FilePSBT(PSBT psbt, string fileName)
{
return File(psbt.ToBytes(), "application/octet-stream", fileName);
}
[HttpPost("{walletId}/psbt/combine")]
public async Task<IActionResult> WalletPSBTCombine([ModelBinder(typeof(WalletIdModelBinder))]
WalletId walletId, WalletPSBTCombineViewModel vm)
{
var network = NetworkProvider.GetNetwork<BTCPayNetwork>(walletId.CryptoCode);
var psbt = await vm.GetPSBT(network.NBitcoinNetwork);
if (psbt == null)
{
ModelState.AddModelError(nameof(vm.PSBT), "Invalid PSBT");
return View(vm);
}
var sourcePSBT = vm.GetSourcePSBT(network.NBitcoinNetwork);
if (sourcePSBT == null)
{
ModelState.AddModelError(nameof(vm.OtherPSBT), "Invalid PSBT");
return View(vm);
}
sourcePSBT = sourcePSBT.Combine(psbt);
TempData[WellKnownTempData.SuccessMessage] = "PSBT Successfully combined!";
return RedirectToWalletPSBT(new WalletPSBTViewModel()
{
PSBT = sourcePSBT.ToBase64()
});
}
}
}
| |
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Orleans.Configuration;
using Orleans.Providers.Streams.AzureQueue;
using Orleans.Providers.Streams.Common;
using Orleans.Runtime;
using Orleans.Streams;
using TestExtensions;
using Xunit;
using Xunit.Abstractions;
using Orleans.Internal;
using Orleans.Serialization;
namespace Tester.AzureUtils.Streaming
{
[Collection(TestEnvironmentFixture.DefaultCollection)]
[TestCategory("Azure"), TestCategory("Streaming")]
public class AzureQueueAdapterTests : AzureStorageBasicTests, IAsyncLifetime
{
private readonly ITestOutputHelper output;
private readonly TestEnvironmentFixture fixture;
private const int NumBatches = 20;
private const int NumMessagesPerBatch = 20;
public static readonly string AZURE_QUEUE_STREAM_PROVIDER_NAME = "AQAdapterTests";
private readonly ILoggerFactory loggerFactory;
private static List<string> azureQueueNames = AzureQueueUtilities.GenerateQueueNames($"AzureQueueAdapterTests-{Guid.NewGuid()}", 8);
public AzureQueueAdapterTests(ITestOutputHelper output, TestEnvironmentFixture fixture)
{
this.output = output;
this.fixture = fixture;
this.loggerFactory = this.fixture.Services.GetService<ILoggerFactory>();
}
public Task InitializeAsync() => Task.CompletedTask;
public async Task DisposeAsync()
{
if (!string.IsNullOrWhiteSpace(TestDefaultConfiguration.DataConnectionString))
{
await AzureQueueStreamProviderUtils.DeleteAllUsedAzureQueues(this.loggerFactory, azureQueueNames, new AzureQueueOptions().ConfigureTestDefaults());
}
}
[SkippableFact, TestCategory("Functional"), TestCategory("Halo")]
public async Task SendAndReceiveFromAzureQueue()
{
var options = new AzureQueueOptions
{
MessageVisibilityTimeout = TimeSpan.FromSeconds(30),
QueueNames = azureQueueNames
};
options.ConfigureTestDefaults();
var serializer = this.fixture.Services.GetService<Serializer>();
var clusterOptions = this.fixture.Services.GetRequiredService<IOptions<ClusterOptions>>();
var queueCacheOptions = new SimpleQueueCacheOptions();
var queueDataAdapter = new AzureQueueDataAdapterV2(serializer);
var adapterFactory = new AzureQueueAdapterFactory(
AZURE_QUEUE_STREAM_PROVIDER_NAME,
options,
queueCacheOptions,
queueDataAdapter,
clusterOptions,
loggerFactory);
adapterFactory.Init();
await SendAndReceiveFromQueueAdapter(adapterFactory);
}
private async Task SendAndReceiveFromQueueAdapter(IQueueAdapterFactory adapterFactory)
{
IQueueAdapter adapter = await adapterFactory.CreateAdapter();
IQueueAdapterCache cache = adapterFactory.GetQueueAdapterCache();
// Create receiver per queue
IStreamQueueMapper mapper = adapterFactory.GetStreamQueueMapper();
Dictionary<QueueId, IQueueAdapterReceiver> receivers = mapper.GetAllQueues().ToDictionary(queueId => queueId, adapter.CreateReceiver);
Dictionary<QueueId, IQueueCache> caches = mapper.GetAllQueues().ToDictionary(queueId => queueId, cache.CreateQueueCache);
await Task.WhenAll(receivers.Values.Select(receiver => receiver.Initialize(TimeSpan.FromSeconds(5))));
// test using 2 streams
Guid streamId1 = Guid.NewGuid();
Guid streamId2 = Guid.NewGuid();
int receivedBatches = 0;
var streamsPerQueue = new ConcurrentDictionary<QueueId, HashSet<StreamId>>();
// reader threads (at most 2 active queues because only two streams)
var work = new List<Task>();
foreach( KeyValuePair<QueueId, IQueueAdapterReceiver> receiverKvp in receivers)
{
QueueId queueId = receiverKvp.Key;
var receiver = receiverKvp.Value;
var qCache = caches[queueId];
Task task = Task.Factory.StartNew(() =>
{
while (receivedBatches < NumBatches)
{
var messages = receiver.GetQueueMessagesAsync(QueueAdapterConstants.UNLIMITED_GET_QUEUE_MSG).Result.ToArray();
if (!messages.Any())
{
continue;
}
foreach (IBatchContainer message in messages)
{
streamsPerQueue.AddOrUpdate(queueId,
id => new HashSet<StreamId> { message.StreamId },
(id, set) =>
{
set.Add(message.StreamId);
return set;
});
this.output.WriteLine("Queue {0} received message on stream {1}", queueId,
message.StreamId);
Assert.Equal(NumMessagesPerBatch / 2, message.GetEvents<int>().Count()); // "Half the events were ints"
Assert.Equal(NumMessagesPerBatch / 2, message.GetEvents<string>().Count()); // "Half the events were strings"
}
Interlocked.Add(ref receivedBatches, messages.Length);
qCache.AddToCache(messages);
}
});
work.Add(task);
}
// send events
List<object> events = CreateEvents(NumMessagesPerBatch);
work.Add(Task.Factory.StartNew(() => Enumerable.Range(0, NumBatches)
.Select(i => i % 2 == 0 ? streamId1 : streamId2)
.ToList()
.ForEach(streamId =>
adapter.QueueMessageBatchAsync(StreamId.Create(streamId.ToString(), streamId),
events.Take(NumMessagesPerBatch).ToArray(), null, RequestContextExtensions.Export(this.fixture.DeepCopier)).Wait())));
await Task.WhenAll(work);
// Make sure we got back everything we sent
Assert.Equal(NumBatches, receivedBatches);
// check to see if all the events are in the cache and we can enumerate through them
StreamSequenceToken firstInCache = new EventSequenceTokenV2(0);
foreach (KeyValuePair<QueueId, HashSet<StreamId>> kvp in streamsPerQueue)
{
var receiver = receivers[kvp.Key];
var qCache = caches[kvp.Key];
foreach (StreamId streamGuid in kvp.Value)
{
// read all messages in cache for stream
IQueueCacheCursor cursor = qCache.GetCacheCursor(streamGuid, firstInCache);
int messageCount = 0;
StreamSequenceToken tenthInCache = null;
StreamSequenceToken lastToken = firstInCache;
while (cursor.MoveNext())
{
Exception ex;
messageCount++;
IBatchContainer batch = cursor.GetCurrent(out ex);
this.output.WriteLine("Token: {0}", batch.SequenceToken);
Assert.True(batch.SequenceToken.CompareTo(lastToken) >= 0, $"order check for event {messageCount}");
lastToken = batch.SequenceToken;
if (messageCount == 10)
{
tenthInCache = batch.SequenceToken;
}
}
this.output.WriteLine("On Queue {0} we received a total of {1} message on stream {2}", kvp.Key, messageCount, streamGuid);
Assert.Equal(NumBatches / 2, messageCount);
Assert.NotNull(tenthInCache);
// read all messages from the 10th
cursor = qCache.GetCacheCursor(streamGuid, tenthInCache);
messageCount = 0;
while (cursor.MoveNext())
{
messageCount++;
}
this.output.WriteLine("On Queue {0} we received a total of {1} message on stream {2}", kvp.Key, messageCount, streamGuid);
const int expected = NumBatches / 2 - 10 + 1; // all except the first 10, including the 10th (10 + 1)
Assert.Equal(expected, messageCount);
}
}
}
private List<object> CreateEvents(int count)
{
return Enumerable.Range(0, count).Select(i =>
{
if (i % 2 == 0)
{
return ThreadSafeRandom.Next(int.MaxValue) as object;
}
return ThreadSafeRandom.Next(int.MaxValue).ToString(CultureInfo.InvariantCulture);
}).ToList();
}
internal static string MakeClusterId()
{
const string DeploymentIdFormat = "cluster-{0}";
string now = DateTime.UtcNow.ToString("yyyy-MM-dd-hh-mm-ss-ffff");
return string.Format(DeploymentIdFormat, now);
}
}
}
| |
// Copyright (c) 2015, Outercurve Foundation.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// - Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// - Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// - Neither the name of the Outercurve Foundation nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
// ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
using System;
using System.Data;
using System.Web;
using System.Collections;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.ComponentModel;
using Microsoft.Web.Services3;
using WebsitePanel.Server.Utils;
using WebsitePanel.Providers;
using WebsitePanel.Providers.Database;
namespace WebsitePanel.Server
{
/// <summary>
/// Summary description for DatabaseServer
/// </summary>
[WebService(Namespace = "http://smbsaas/websitepanel/server/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[Policy("ServerPolicy")]
[ToolboxItem(false)]
public class DatabaseServer : HostingServiceProviderWebService, IDatabaseServer
{
private IDatabaseServer DatabaseProvider
{
get { return (IDatabaseServer)Provider; }
}
#region General methods
[WebMethod, SoapHeader("settings")]
public bool CheckConnectivity(string databaseName, string username, string password)
{
try
{
Log.WriteStart("'{0}' CheckConnectivity", ProviderSettings.ProviderName);
bool result = DatabaseProvider.CheckConnectivity(databaseName, username, password);
Log.WriteEnd("'{0}' CheckConnectivity", ProviderSettings.ProviderName);
return result;
}
catch (Exception ex)
{
Log.WriteError(String.Format("'{0}' CheckConnectivity", ProviderSettings.ProviderName), ex);
throw;
}
}
[WebMethod, SoapHeader("settings")]
public DataSet ExecuteSqlQuery(string databaseName, string commandText)
{
try
{
Log.WriteStart("'{0}' ExecuteSqlQuery", ProviderSettings.ProviderName);
DataSet result = DatabaseProvider.ExecuteSqlQuery(databaseName, commandText);
Log.WriteEnd("'{0}' ExecuteSqlQuery", ProviderSettings.ProviderName);
return result;
}
catch (Exception ex)
{
Log.WriteError(String.Format("'{0}' ExecuteSqlQuery", ProviderSettings.ProviderName), ex);
throw;
}
}
[WebMethod, SoapHeader("settings")]
public void ExecuteSqlNonQuery(string databaseName, string commandText)
{
try
{
Log.WriteStart("'{0}' ExecuteSqlNonQuery", ProviderSettings.ProviderName);
DatabaseProvider.ExecuteSqlNonQuery(databaseName, commandText);
Log.WriteEnd("'{0}' ExecuteSqlNonQuery", ProviderSettings.ProviderName);
}
catch (Exception ex)
{
Log.WriteError(String.Format("'{0}' ExecuteSqlNonQuery", ProviderSettings.ProviderName), ex);
throw;
}
}
[WebMethod, SoapHeader("settings")]
public DataSet ExecuteSqlQuerySafe(string databaseName, string username, string password, string commandText)
{
try
{
Log.WriteStart("'{0}' ExecuteSqlQuerySafe", ProviderSettings.ProviderName);
DataSet result = DatabaseProvider.ExecuteSqlQuerySafe(databaseName, username, password, commandText);
Log.WriteEnd("'{0}' ExecuteSqlQuerySafe", ProviderSettings.ProviderName);
return result;
}
catch (Exception ex)
{
Log.WriteError(String.Format("'{0}' ExecuteSqlQuerySafe", ProviderSettings.ProviderName), ex);
throw;
}
}
[WebMethod, SoapHeader("settings")]
public void ExecuteSqlNonQuerySafe(string databaseName, string username, string password, string commandText)
{
try
{
Log.WriteStart("'{0}' ExecuteSqlNonQuerySafe", ProviderSettings.ProviderName);
DatabaseProvider.ExecuteSqlNonQuerySafe(databaseName, username, password, commandText);
Log.WriteEnd("'{0}' ExecuteSqlNonQuerySafe", ProviderSettings.ProviderName);
}
catch (Exception ex)
{
Log.WriteError(String.Format("'{0}' ExecuteSqlNonQuerySafe", ProviderSettings.ProviderName), ex);
throw;
}
}
#endregion
#region Databases
[WebMethod, SoapHeader("settings")]
public bool DatabaseExists(string databaseName)
{
try
{
Log.WriteStart("'{0}' DatabaseExists", ProviderSettings.ProviderName);
bool result = DatabaseProvider.DatabaseExists(databaseName);
Log.WriteEnd("'{0}' DatabaseExists", ProviderSettings.ProviderName);
return result;
}
catch (Exception ex)
{
Log.WriteError(String.Format("'{0}' DatabaseExists", ProviderSettings.ProviderName), ex);
throw;
}
}
[WebMethod, SoapHeader("settings")]
public string[] GetDatabases()
{
try
{
Log.WriteStart("'{0}' GetDatabases", ProviderSettings.ProviderName);
string[] result = DatabaseProvider.GetDatabases();
Log.WriteEnd("'{0}' GetDatabases", ProviderSettings.ProviderName);
return result;
}
catch (Exception ex)
{
Log.WriteError(String.Format("'{0}' GetDatabases", ProviderSettings.ProviderName), ex);
throw;
}
}
[WebMethod, SoapHeader("settings")]
public SqlDatabase GetDatabase(string databaseName)
{
try
{
Log.WriteStart("'{0}' GetDatabase", ProviderSettings.ProviderName);
SqlDatabase result = DatabaseProvider.GetDatabase(databaseName);
Log.WriteEnd("'{0}' GetDatabase", ProviderSettings.ProviderName);
return result;
}
catch (Exception ex)
{
Log.WriteError(String.Format("'{0}' GetDatabase", ProviderSettings.ProviderName), ex);
throw;
}
}
[WebMethod, SoapHeader("settings")]
public void CreateDatabase(SqlDatabase database)
{
try
{
Log.WriteStart("'{0}' CreateDatabase", ProviderSettings.ProviderName);
DatabaseProvider.CreateDatabase(database);
Log.WriteEnd("'{0}' CreateDatabase", ProviderSettings.ProviderName);
}
catch (Exception ex)
{
Log.WriteError(String.Format("'{0}' CreateDatabase", ProviderSettings.ProviderName), ex);
throw;
}
}
[WebMethod, SoapHeader("settings")]
public void UpdateDatabase(SqlDatabase database)
{
try
{
Log.WriteStart("'{0}' UpdateDatabase", ProviderSettings.ProviderName);
DatabaseProvider.UpdateDatabase(database);
Log.WriteEnd("'{0}' UpdateDatabase", ProviderSettings.ProviderName);
}
catch (Exception ex)
{
Log.WriteError(String.Format("'{0}' UpdateDatabase", ProviderSettings.ProviderName), ex);
throw;
}
}
[WebMethod, SoapHeader("settings")]
public void DeleteDatabase(string databaseName)
{
try
{
Log.WriteStart("'{0}' DeleteDatabase", ProviderSettings.ProviderName);
DatabaseProvider.DeleteDatabase(databaseName);
Log.WriteEnd("'{0}' DeleteDatabase", ProviderSettings.ProviderName);
}
catch (Exception ex)
{
Log.WriteError(String.Format("'{0}' DeleteDatabase", ProviderSettings.ProviderName), ex);
throw;
}
}
[WebMethod, SoapHeader("settings")]
public void TruncateDatabase(string databaseName)
{
try
{
Log.WriteStart("'{0}' TruncateDatabase", ProviderSettings.ProviderName);
DatabaseProvider.TruncateDatabase(databaseName);
Log.WriteEnd("'{0}' TruncateDatabase", ProviderSettings.ProviderName);
}
catch (Exception ex)
{
Log.WriteError(String.Format("'{0}' TruncateDatabase", ProviderSettings.ProviderName), ex);
throw;
}
}
[WebMethod, SoapHeader("settings")]
public byte[] GetTempFileBinaryChunk(string path, int offset, int length)
{
try
{
Log.WriteStart("'{0}' GetTempFileBinaryChunk", ProviderSettings.ProviderName);
byte[] result = DatabaseProvider.GetTempFileBinaryChunk(path, offset, length);
Log.WriteEnd("'{0}' GetTempFileBinaryChunk", ProviderSettings.ProviderName);
return result;
}
catch (Exception ex)
{
Log.WriteError(String.Format("'{0}' GetTempFileBinaryChunk", ProviderSettings.ProviderName), ex);
throw;
}
}
[WebMethod, SoapHeader("settings")]
public string AppendTempFileBinaryChunk(string fileName, string path, byte[] chunk)
{
try
{
Log.WriteStart("'{0}' AppendTempFileBinaryChunk", ProviderSettings.ProviderName);
string result = DatabaseProvider.AppendTempFileBinaryChunk(fileName, path, chunk);
Log.WriteEnd("'{0}' AppendTempFileBinaryChunk", ProviderSettings.ProviderName);
return result;
}
catch (Exception ex)
{
Log.WriteError(String.Format("'{0}' AppendTempFileBinaryChunk", ProviderSettings.ProviderName), ex);
throw;
}
}
[WebMethod, SoapHeader("settings")]
public string BackupDatabase(string databaseName, string backupName, bool zipBackup)
{
try
{
Log.WriteStart("'{0}' BackupDatabase", ProviderSettings.ProviderName);
string result = DatabaseProvider.BackupDatabase(databaseName, backupName, zipBackup);
Log.WriteEnd("'{0}' BackupDatabase", ProviderSettings.ProviderName);
return result;
}
catch (Exception ex)
{
Log.WriteError(String.Format("'{0}' BackupDatabase", ProviderSettings.ProviderName), ex);
throw;
}
}
[WebMethod, SoapHeader("settings")]
public void RestoreDatabase(string databaseName, string[] fileNames)
{
try
{
Log.WriteStart("'{0}' RestoreDatabase", ProviderSettings.ProviderName);
DatabaseProvider.RestoreDatabase(databaseName, fileNames);
Log.WriteEnd("'{0}' RestoreDatabase", ProviderSettings.ProviderName);
}
catch (Exception ex)
{
Log.WriteError(String.Format("'{0}' RestoreDatabase", ProviderSettings.ProviderName), ex);
throw;
}
}
#endregion
#region Users
[WebMethod, SoapHeader("settings")]
public bool UserExists(string userName)
{
try
{
Log.WriteStart("'{0}' UserExists", ProviderSettings.ProviderName);
bool result = DatabaseProvider.UserExists(userName);
Log.WriteEnd("'{0}' UserExists", ProviderSettings.ProviderName);
return result;
}
catch (Exception ex)
{
Log.WriteError(String.Format("'{0}' UserExists", ProviderSettings.ProviderName), ex);
throw;
}
}
[WebMethod, SoapHeader("settings")]
public string[] GetUsers()
{
try
{
Log.WriteStart("'{0}' GetUsers", ProviderSettings.ProviderName);
string[] result = DatabaseProvider.GetUsers();
Log.WriteEnd("'{0}' GetUsers", ProviderSettings.ProviderName);
return result;
}
catch (Exception ex)
{
Log.WriteError(String.Format("'{0}' GetUsers", ProviderSettings.ProviderName), ex);
throw;
}
}
[WebMethod, SoapHeader("settings")]
public SqlUser GetUser(string username, string[] databases)
{
try
{
Log.WriteStart("'{0}' GetUser", ProviderSettings.ProviderName);
SqlUser result = DatabaseProvider.GetUser(username, databases);
Log.WriteEnd("'{0}' GetUser", ProviderSettings.ProviderName);
return result;
}
catch (Exception ex)
{
Log.WriteError(String.Format("'{0}' GetUser", ProviderSettings.ProviderName), ex);
throw;
}
}
[WebMethod, SoapHeader("settings")]
public void CreateUser(SqlUser user, string password)
{
try
{
Log.WriteStart("'{0}' CreateUser", ProviderSettings.ProviderName);
DatabaseProvider.CreateUser(user, password);
Log.WriteEnd("'{0}' CreateUser", ProviderSettings.ProviderName);
}
catch (Exception ex)
{
Log.WriteError(String.Format("'{0}' CreateUser", ProviderSettings.ProviderName), ex);
throw;
}
}
[WebMethod, SoapHeader("settings")]
public void UpdateUser(SqlUser user, string[] databases)
{
try
{
Log.WriteStart("'{0}' UpdateUser", ProviderSettings.ProviderName);
DatabaseProvider.UpdateUser(user, databases);
Log.WriteEnd("'{0}' UpdateUser", ProviderSettings.ProviderName);
}
catch (Exception ex)
{
Log.WriteError(String.Format("'{0}' UpdateUser", ProviderSettings.ProviderName), ex);
throw;
}
}
[WebMethod, SoapHeader("settings")]
public void DeleteUser(string username, string[] databases)
{
try
{
Log.WriteStart("'{0}' DeleteUser", ProviderSettings.ProviderName);
DatabaseProvider.DeleteUser(username, databases);
Log.WriteEnd("'{0}' DeleteUser", ProviderSettings.ProviderName);
}
catch (Exception ex)
{
Log.WriteError(String.Format("'{0}' DeleteUser", ProviderSettings.ProviderName), ex);
throw;
}
}
[WebMethod, SoapHeader("settings")]
public void ChangeUserPassword(string username, string password)
{
try
{
Log.WriteStart("'{0}' ChangeUserPassword", ProviderSettings.ProviderName);
DatabaseProvider.ChangeUserPassword(username, password);
Log.WriteEnd("'{0}' ChangeUserPassword", ProviderSettings.ProviderName);
}
catch (Exception ex)
{
Log.WriteError(String.Format("'{0}' ChangeUserPassword", ProviderSettings.ProviderName), ex);
throw;
}
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics;
namespace Lucene.Net.Search.Spans
{
using BytesRef = Lucene.Net.Util.BytesRef;
using DocsAndPositionsEnum = Lucene.Net.Index.DocsAndPositionsEnum;
/// <summary>
/// Copyright 2005 The Apache Software Foundation
///
/// Licensed under the Apache License, Version 2.0 (the "License");
/// you may not use this file except in compliance with the License.
/// You may obtain a copy of the License at
///
/// http://www.apache.org/licenses/LICENSE-2.0
///
/// Unless required by applicable law or agreed to in writing, software
/// distributed under the License is distributed on an "AS IS" BASIS,
/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
/// See the License for the specific language governing permissions and
/// limitations under the License.
/// </summary>
using Term = Lucene.Net.Index.Term;
/// <summary>
/// Expert:
/// Public for extension only
/// </summary>
public class TermSpans : Spans
{
protected internal readonly DocsAndPositionsEnum Postings_Renamed;
protected internal readonly Term Term;
protected internal int Doc_Renamed;
protected internal int Freq;
protected internal int Count;
protected internal int Position;
protected internal bool ReadPayload;
public TermSpans(DocsAndPositionsEnum postings, Term term)
{
this.Postings_Renamed = postings;
this.Term = term;
Doc_Renamed = -1;
}
// only for EmptyTermSpans (below)
internal TermSpans()
{
Term = null;
Postings_Renamed = null;
}
public override bool Next()
{
if (Count == Freq)
{
if (Postings_Renamed == null)
{
return false;
}
Doc_Renamed = Postings_Renamed.NextDoc();
if (Doc_Renamed == DocIdSetIterator.NO_MORE_DOCS)
{
return false;
}
Freq = Postings_Renamed.Freq();
Count = 0;
}
Position = Postings_Renamed.NextPosition();
Count++;
ReadPayload = false;
return true;
}
public override bool SkipTo(int target)
{
Debug.Assert(target > Doc_Renamed);
Doc_Renamed = Postings_Renamed.Advance(target);
if (Doc_Renamed == DocIdSetIterator.NO_MORE_DOCS)
{
return false;
}
Freq = Postings_Renamed.Freq();
Count = 0;
Position = Postings_Renamed.NextPosition();
Count++;
ReadPayload = false;
return true;
}
public override int Doc()
{
return Doc_Renamed;
}
public override int Start()
{
return Position;
}
public override int End()
{
return Position + 1;
}
public override long Cost()
{
return Postings_Renamed.Cost();
}
// TODO: Remove warning after API has been finalized
public override ICollection<byte[]> Payload
{
get
{
var payload = Postings_Renamed.Payload;
ReadPayload = true;
byte[] bytes;
if (payload != null)
{
bytes = new byte[payload.Length];
Array.Copy(payload.Bytes, payload.Offset, bytes, 0, payload.Length);
}
else
{
bytes = null;
}
//LUCENE TO-DO
return new[] { bytes };
//return Collections.singletonList(bytes);
}
}
// TODO: Remove warning after API has been finalized
public override bool PayloadAvailable
{
get
{
return ReadPayload == false && Postings_Renamed.Payload != null;
}
}
public override string ToString()
{
return "spans(" + Term.ToString() + ")@" + (Doc_Renamed == -1 ? "START" : (Doc_Renamed == int.MaxValue) ? "END" : Doc_Renamed + "-" + Position);
}
public virtual DocsAndPositionsEnum Postings
{
get
{
return Postings_Renamed;
}
}
private sealed class EmptyTermSpans : TermSpans
{
public override bool Next()
{
return false;
}
public override bool SkipTo(int target)
{
return false;
}
public override int Doc()
{
return DocIdSetIterator.NO_MORE_DOCS;
}
public override int Start()
{
return -1;
}
public override int End()
{
return -1;
}
public override ICollection<byte[]> Payload
{
get
{
return null;
}
}
public override bool PayloadAvailable
{
get
{
return false;
}
}
public override long Cost()
{
return 0;
}
}
public static readonly TermSpans EMPTY_TERM_SPANS = new EmptyTermSpans();
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
namespace Apache.Ignite.Core.Tests
{
using System;
using System.Collections;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Threading;
using Apache.Ignite.Core.Binary;
using Apache.Ignite.Core.Cache.Affinity;
using Apache.Ignite.Core.Client;
using Apache.Ignite.Core.Cluster;
using Apache.Ignite.Core.Configuration;
using Apache.Ignite.Core.Discovery.Tcp;
using Apache.Ignite.Core.Discovery.Tcp.Static;
using Apache.Ignite.Core.Failure;
using Apache.Ignite.Core.Impl;
using Apache.Ignite.Core.Impl.Binary;
using Apache.Ignite.Core.Impl.Client;
using Apache.Ignite.Core.Impl.Common;
using Apache.Ignite.Core.Impl.Unmanaged.Jni;
using Apache.Ignite.Core.Lifecycle;
using Apache.Ignite.Core.Log;
using Apache.Ignite.Core.Resource;
using Apache.Ignite.Core.Tests.Process;
using NUnit.Framework;
using NUnit.Framework.Interfaces;
using NUnit.Framework.Internal;
using ILogger = Apache.Ignite.Core.Log.ILogger;
/// <summary>
/// Test utility methods.
/// </summary>
public static class TestUtils
{
/** Indicates long running and/or memory/cpu intensive test. */
public const string CategoryIntensive = "LONG_TEST";
/** Indicates examples tests. */
public const string CategoryExamples = "EXAMPLES_TEST";
/** */
public const int DfltBusywaitSleepInterval = 200;
/** System cache name. */
public const string UtilityCacheName = "ignite-sys-cache";
/** Work dir. */
private static readonly string WorkDir =
// ReSharper disable once AssignNullToNotNullAttribute
Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "ignite_work");
/** */
private static readonly IList<string> TestJvmOpts = Environment.Is64BitProcess
? new List<string>
{
"-XX:+HeapDumpOnOutOfMemoryError",
"-Xms2g",
"-Xmx6g",
"-ea",
"-DIGNITE_QUIET=true",
"-Duser.timezone=UTC"
}
: new List<string>
{
"-XX:+HeapDumpOnOutOfMemoryError",
"-Xms64m",
"-Xmx99m",
"-ea",
"-DIGNITE_ATOMIC_CACHE_DELETE_HISTORY_SIZE=1000",
"-DIGNITE_QUIET=true",
"-Duser.timezone=UTC"
};
/** */
private static readonly IList<string> JvmDebugOpts =
new List<string> { "-Xdebug", "-Xnoagent", "-Djava.compiler=NONE", "-agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=5005", "-DIGNITE_LOG_CLASSPATH_CONTENT_ON_STARTUP=false" };
/** */
public static bool JvmDebug = true;
/** */
[ThreadStatic]
private static Random _random;
/** */
private static int _seed = Environment.TickCount;
/// <summary>
///
/// </summary>
public static Random Random
{
get { return _random ?? (_random = new Random(Interlocked.Increment(ref _seed))); }
}
/// <summary>
/// Gets current test name.
/// </summary>
public static string TestName
{
get { return TestContext.CurrentContext.Test.Name; }
}
/// <summary>
///
/// </summary>
/// <returns></returns>
public static IList<string> TestJavaOptions(bool? jvmDebug = null)
{
IList<string> ops = new List<string>(TestJvmOpts);
if (jvmDebug ?? JvmDebug)
{
foreach (string opt in JvmDebugOpts)
ops.Add(opt);
}
return ops;
}
/// <summary>
///
/// </summary>
/// <param name="action"></param>
/// <param name="threadNum"></param>
public static void RunMultiThreaded(Action action, int threadNum)
{
List<Thread> threads = new List<Thread>(threadNum);
var errors = new ConcurrentBag<Exception>();
for (int i = 0; i < threadNum; i++)
{
threads.Add(new Thread(() =>
{
try
{
action();
}
catch (Exception e)
{
errors.Add(e);
}
}));
}
foreach (Thread thread in threads)
thread.Start();
foreach (Thread thread in threads)
thread.Join();
foreach (var ex in errors)
Assert.Fail("Unexpected exception: " + ex);
}
/// <summary>
///
/// </summary>
/// <param name="action"></param>
/// <param name="threadNum"></param>
/// <param name="duration">Duration of test execution in seconds</param>
public static void RunMultiThreaded(Action action, int threadNum, int duration)
{
List<Thread> threads = new List<Thread>(threadNum);
var errors = new ConcurrentBag<Exception>();
bool stop = false;
for (int i = 0; i < threadNum; i++)
{
threads.Add(new Thread(() =>
{
try
{
while (true)
{
Thread.MemoryBarrier();
// ReSharper disable once AccessToModifiedClosure
if (stop)
break;
action();
}
}
catch (Exception e)
{
errors.Add(e);
}
}));
}
foreach (Thread thread in threads)
thread.Start();
Thread.Sleep(duration * 1000);
stop = true;
Thread.MemoryBarrier();
foreach (Thread thread in threads)
thread.Join();
foreach (var ex in errors)
Assert.Fail("Unexpected exception: " + ex);
}
/// <summary>
/// Wait for particular topology size.
/// </summary>
/// <param name="grid">Grid.</param>
/// <param name="size">Size.</param>
/// <param name="timeout">Timeout.</param>
/// <returns>
/// <c>True</c> if topology took required size.
/// </returns>
public static bool WaitTopology(this IIgnite grid, int size, int timeout = 30000)
{
int left = timeout;
while (true)
{
if (grid.GetCluster().GetNodes().Count != size)
{
if (left > 0)
{
Thread.Sleep(100);
left -= 100;
}
else
break;
}
else
return true;
}
return false;
}
/// <summary>
/// Waits for particular topology on specific cache (system cache by default).
/// </summary>
/// <param name="grid">Grid.</param>
/// <param name="waitingTop">Topology version.</param>
/// <param name="cacheName">Cache name.</param>
/// <param name="timeout">Timeout.</param>
/// <returns>
/// <c>True</c> if topology took required size.
/// </returns>
public static bool WaitTopology(this IIgnite grid, AffinityTopologyVersion waitingTop,
string cacheName = UtilityCacheName, int timeout = 30000)
{
int checkPeriod = 200;
// Wait for late affinity.
for (var iter = 0;; iter++)
{
var result = grid.GetCompute().ExecuteJavaTask<long[]>(
"org.apache.ignite.platform.PlatformCacheAffinityVersionTask", cacheName);
var top = new AffinityTopologyVersion(result[0], (int) result[1]);
if (top.CompareTo(waitingTop) >= 0)
{
Console.Out.WriteLine("Current topology: " + top);
break;
}
if (iter % 10 == 0)
Console.Out.WriteLine("Waiting topology cur=" + top + " wait=" + waitingTop);
if (iter * checkPeriod > timeout)
return false;
Thread.Sleep(checkPeriod);
}
return true;
}
/// <summary>
/// Waits for condition, polling in busy wait loop.
/// </summary>
/// <param name="cond">Condition.</param>
/// <param name="timeout">Timeout, in milliseconds.</param>
/// <returns>True if condition predicate returned true within interval; false otherwise.</returns>
public static bool WaitForCondition(Func<bool> cond, int timeout)
{
if (timeout <= 0)
return cond();
var maxTime = DateTime.Now.AddMilliseconds(timeout + DfltBusywaitSleepInterval);
while (DateTime.Now < maxTime)
{
if (cond())
return true;
Thread.Sleep(DfltBusywaitSleepInterval);
}
return false;
}
/// <summary>
/// Waits for condition, polling in a busy wait loop, then asserts that condition is true.
/// </summary>
/// <param name="cond">Condition.</param>
/// <param name="timeout">Timeout, in milliseconds.</param>
/// <param name="message">Assertion message.</param>
public static void WaitForTrueCondition(Func<bool> cond, int timeout = 1000, string message = null)
{
WaitForTrueCondition(cond, message == null ? (Func<string>) null : () => message, timeout);
}
/// <summary>
/// Waits for condition, polling in a busy wait loop, then asserts that condition is true.
/// </summary>
/// <param name="cond">Condition.</param>
/// <param name="messageFunc">Assertion message func.</param>
/// <param name="timeout">Timeout, in milliseconds.</param>
public static void WaitForTrueCondition(Func<bool> cond, Func<string> messageFunc, int timeout = 1000)
{
var res = WaitForCondition(cond, timeout);
if (!res)
{
var message = string.Format("Condition not reached within {0} ms", timeout);
if (messageFunc != null)
{
message += string.Format(" ({0})", messageFunc());
}
Assert.IsTrue(res, message);
}
}
/// <summary>
/// Gets the static discovery.
/// </summary>
public static TcpDiscoverySpi GetStaticDiscovery(int? maxPort = null)
{
return new TcpDiscoverySpi
{
IpFinder = new TcpDiscoveryStaticIpFinder
{
Endpoints = new[] { "127.0.0.1:47500" + (maxPort == null ? null : (".." + maxPort)) }
},
SocketTimeout = TimeSpan.FromSeconds(0.3)
};
}
/// <summary>
/// Gets cache keys.
/// </summary>
public static IEnumerable<int> GetKeys(IIgnite ignite, string cacheName,
IClusterNode node = null, bool primary = true)
{
var aff = ignite.GetAffinity(cacheName);
node = node ?? ignite.GetCluster().GetLocalNode();
return Enumerable.Range(1, int.MaxValue).Where(x => aff.IsPrimary(node, x) == primary);
}
/// <summary>
/// Gets the primary keys.
/// </summary>
public static IEnumerable<int> GetPrimaryKeys(IIgnite ignite, string cacheName,
IClusterNode node = null)
{
return GetKeys(ignite, cacheName, node);
}
/// <summary>
/// Gets the primary key.
/// </summary>
public static int GetPrimaryKey(IIgnite ignite, string cacheName, IClusterNode node = null)
{
return GetPrimaryKeys(ignite, cacheName, node).First();
}
/// <summary>
/// Gets the primary key.
/// </summary>
public static int GetKey(IIgnite ignite, string cacheName, IClusterNode node = null, bool primaryKey = false)
{
return GetKeys(ignite, cacheName, node, primaryKey).First();
}
/// <summary>
/// Asserts that the handle registry is empty.
/// </summary>
/// <param name="timeout">Timeout, in milliseconds.</param>
/// <param name="grids">Grids to check.</param>
public static void AssertHandleRegistryIsEmpty(int timeout, params IIgnite[] grids)
{
foreach (var g in grids)
AssertHandleRegistryHasItems(g, 0, timeout);
}
/// <summary>
/// Asserts that the handle registry has specified number of entries.
/// </summary>
/// <param name="timeout">Timeout, in milliseconds.</param>
/// <param name="expectedCount">Expected item count.</param>
/// <param name="grids">Grids to check.</param>
public static void AssertHandleRegistryHasItems(int timeout, int expectedCount, params IIgnite[] grids)
{
foreach (var g in grids)
AssertHandleRegistryHasItems(g, expectedCount, timeout);
}
/// <summary>
/// Asserts that the handle registry has specified number of entries.
/// </summary>
/// <param name="grid">The grid to check.</param>
/// <param name="expectedCount">Expected item count.</param>
/// <param name="timeout">Timeout, in milliseconds.</param>
public static void AssertHandleRegistryHasItems(IIgnite grid, int expectedCount, int timeout)
{
Func<IEnumerable<KeyValuePair<long, object>>> getItems = () =>
((Ignite)grid).HandleRegistry.GetItems().Where(x => !(x.Value is LifecycleHandlerHolder));
if (WaitForCondition(() => getItems().Count() == expectedCount, timeout))
return;
var items = getItems().ToList();
if (items.Any())
{
Assert.Fail("HandleRegistry is not empty in grid '{0}' (expected {1}, actual {2}):\n '{3}'",
grid.Name, expectedCount, items.Count,
items.Select(x => x.ToString()).Aggregate((x, y) => x + "\n" + y));
}
}
/// <summary>
/// Serializes and deserializes back an object.
/// </summary>
public static T SerializeDeserialize<T>(T obj, bool raw = false)
{
var cfg = new BinaryConfiguration
{
Serializer = raw ? new BinaryReflectiveSerializer {RawMode = true} : null
};
var marsh = new Marshaller(cfg) { CompactFooter = false };
return marsh.Unmarshal<T>(marsh.Marshal(obj));
}
/// <summary>
/// Clears the work dir.
/// </summary>
public static void ClearWorkDir()
{
if (!Directory.Exists(WorkDir))
{
return;
}
// Delete everything we can. Some files may be locked.
foreach (var e in Directory.GetFileSystemEntries(WorkDir, "*", SearchOption.AllDirectories))
{
try
{
File.Delete(e);
}
catch (Exception)
{
// Ignore
}
try
{
Directory.Delete(e, true);
}
catch (Exception)
{
// Ignore
}
}
}
/// <summary>
/// Gets the dot net source dir.
/// </summary>
public static DirectoryInfo GetDotNetSourceDir()
{
// ReSharper disable once AssignNullToNotNullAttribute
var dir = new DirectoryInfo(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location));
while (dir != null)
{
if (dir.GetFiles().Any(x => x.Name == "Apache.Ignite.sln"))
return dir;
dir = dir.Parent;
}
throw new InvalidOperationException("Could not resolve Ignite.NET source directory.");
}
/// <summary>
/// Gets a value indicating whether specified partition is reserved.
/// </summary>
public static bool IsPartitionReserved(IIgnite ignite, string cacheName, int part)
{
Debug.Assert(ignite != null);
Debug.Assert(cacheName != null);
const string taskName = "org.apache.ignite.platform.PlatformIsPartitionReservedTask";
return ignite.GetCompute().ExecuteJavaTask<bool>(taskName, new object[] {cacheName, part});
}
/// <summary>
/// Gets the innermost exception.
/// </summary>
public static Exception GetInnermostException(this Exception ex)
{
while (ex.InnerException != null)
{
ex = ex.InnerException;
}
return ex;
}
/// <summary>
/// Gets the private field value.
/// </summary>
public static T GetPrivateField<T>(object obj, string name)
{
Assert.IsNotNull(obj);
var field = obj.GetType().GetField(name, BindingFlags.Instance | BindingFlags.NonPublic);
Assert.IsNotNull(field);
return (T) field.GetValue(obj);
}
/// <summary>
/// Gets active notification listeners.
/// </summary>
public static ICollection GetActiveNotificationListeners(this IIgniteClient client)
{
var failoverSocket = GetPrivateField<ClientFailoverSocket>(client, "_socket");
var socket = GetPrivateField<ClientSocket>(failoverSocket, "_socket");
return GetPrivateField<ICollection>(socket, "_notificationListeners");
}
/// <summary>
///
/// </summary>
/// <returns></returns>
public static string CreateTestClasspath()
{
var home = IgniteHome.Resolve();
return Classpath.CreateClasspath(null, home, forceTestClasspath: true);
}
/// <summary>
/// Kill Ignite processes.
/// </summary>
public static void KillProcesses()
{
IgniteProcess.KillAll();
}
/// <summary>
/// Gets the default code-based test configuration.
/// </summary>
public static IgniteConfiguration GetTestConfiguration(bool? jvmDebug = null, string name = null, bool noLogger = false)
{
return new IgniteConfiguration
{
DiscoverySpi = GetStaticDiscovery(),
Localhost = "127.0.0.1",
JvmOptions = TestJavaOptions(jvmDebug),
JvmClasspath = CreateTestClasspath(),
IgniteInstanceName = name,
DataStorageConfiguration = new DataStorageConfiguration
{
DefaultDataRegionConfiguration = new DataRegionConfiguration
{
Name = DataStorageConfiguration.DefaultDataRegionName,
InitialSize = 128 * 1024 * 1024,
MaxSize = Environment.Is64BitProcess
? DataRegionConfiguration.DefaultMaxSize
: 256 * 1024 * 1024
}
},
FailureHandler = new NoOpFailureHandler(),
WorkDirectory = WorkDir,
Logger = noLogger ? null : new TestContextLogger()
};
}
/// <summary>
/// Creates the JVM if necessary.
/// </summary>
public static void EnsureJvmCreated()
{
if (Jvm.Get(true) == null)
{
var logger = new TestContextLogger();
JvmDll.Load(null, logger);
IgniteManager.CreateJvm(GetTestConfiguration(), logger);
}
}
/// <summary>
/// Runs the test in new process.
/// </summary>
[SuppressMessage("ReSharper", "AssignNullToNotNullAttribute")]
public static void RunTestInNewProcess(string fixtureName, string testName)
{
var procStart = new ProcessStartInfo
{
FileName = typeof(TestUtils).Assembly.Location,
Arguments = fixtureName + " " + testName,
CreateNoWindow = true,
UseShellExecute = false,
RedirectStandardOutput = true,
RedirectStandardError = true
};
var proc = System.Diagnostics.Process.Start(procStart);
Assert.IsNotNull(proc);
try
{
var reader = new ListDataReader();
proc.AttachProcessConsoleReader(reader, new IgniteProcessConsoleOutputReader());
Assert.IsTrue(proc.WaitForExit(50000), string.Join("\n", reader.GetOutput()));
Assert.AreEqual(0, proc.ExitCode, string.Join("\n", reader.GetOutput()));
}
finally
{
if (!proc.HasExited)
{
proc.Kill();
}
}
}
/// <summary>
/// Deploys the Java service.
/// </summary>
public static string DeployJavaService(IIgnite ignite)
{
const string serviceName = "javaService";
ignite.GetCompute()
.ExecuteJavaTask<object>("org.apache.ignite.platform.PlatformDeployServiceTask", serviceName);
var services = ignite.GetServices();
WaitForCondition(() => services.GetServiceDescriptors().Any(x => x.Name == serviceName), 1000);
return serviceName;
}
/// <summary>
/// Logs to test progress. Produces immediate console output on .NET Core.
/// </summary>
public class TestContextLogger : ILogger
{
private readonly TestExecutionContext _ctx = TestExecutionContext.CurrentContext;
private readonly ITestListener _listener;
public TestContextLogger()
{
var prop = _ctx.GetType().GetProperty("Listener", BindingFlags.Instance | BindingFlags.NonPublic);
Debug.Assert(prop != null);
_listener = (ITestListener)prop.GetValue(_ctx);
}
/** <inheritdoc /> */
public void Log(LogLevel level, string message, object[] args, IFormatProvider formatProvider,
string category, string nativeErrorInfo, Exception ex)
{
if (!IsEnabled(level))
{
return;
}
var text = args != null
? string.Format(formatProvider ?? CultureInfo.InvariantCulture, message, args)
: message;
_listener.TestOutput(new TestOutput(text + Environment.NewLine, "Progress", _ctx.CurrentTest?.Id, _ctx.CurrentTest?.FullName));
}
/** <inheritdoc /> */
public bool IsEnabled(LogLevel level)
{
return level >= LogLevel.Info;
}
}
}
/** */
public class SetUseBinaryArray : ILifecycleHandler
{
/** Task name. */
private const string SetUseTypedArrayTask = "org.apache.ignite.platform.PlatformSetUseBinaryArrayTask";
/** */
[InstanceResource]
private readonly IIgnite _ignite = null;
/** <inheritdoc /> */
public void OnLifecycleEvent(LifecycleEventType evt)
{
if (evt != LifecycleEventType.AfterNodeStart && evt != LifecycleEventType.BeforeNodeStop)
return;
_ignite.GetCompute()
.ExecuteJavaTask<object>(SetUseTypedArrayTask, evt == LifecycleEventType.AfterNodeStart);
}
}
}
| |
// Copyright (c) Winton. All rights reserved.
// Licensed under the Apache License, Version 2.0. See LICENCE in the project root for license information.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.Transactions;
using FluentAssertions;
using Winton.Extensions.Threading.Actor.Tests.Utilities;
using Xunit;
namespace Winton.Extensions.Threading.Actor.Tests.Unit
{
public sealed class ActorTests : IDisposable
{
public enum ResumeTestCase
{
AwaitOnSecondActor,
AwaitOnTaskFactoryScheduledTask
}
public enum StopTaskCancellationTestCase
{
CancelPriorToInvoke,
CancelDuringWork
}
public enum StopWorkOutcome
{
Completes,
Faults
}
private readonly List<IActor> _createdActors = new List<IActor>();
private readonly TimeSpan _waitTimeout = TimeSpan.FromSeconds(30);
public void Dispose()
{
if (_createdActors.Any())
{
try
{
Task.WaitAll(_createdActors.Select(x => x.Stop()).ToArray(), _waitTimeout);
}
catch (AggregateException exception)
{
Console.WriteLine($"One or more errors occurred whilst stopping the test actor(s):\n{string.Join("\n", exception.InnerExceptions)}");
}
}
}
[Fact]
public void ShouldBeAbleToEnqueueBasicNonVoidTaskAndAwaitItsReturn()
{
var actor = CreateActor();
actor.Enqueue(() => true).AwaitingShouldCompleteIn(_waitTimeout).And.Should().BeTrue();
}
[Fact]
public async Task ShouldBeAbleToEnqueueBasicVoidTaskAndAwaitItsReturn()
{
var actor = CreateActor();
var ran = false;
await actor.Enqueue(() => { ran = true; });
ran.Should().BeTrue();
}
[Fact]
public void ShouldRunMultipleNonVoidTasksInTheOrderTheyAreEnqueued()
{
var actor = CreateActor();
var output = new List<int>();
var tasks =
Enumerable.Range(1, 50)
.Select(x => actor.Enqueue(() =>
{
// Without this the test will usually pass even
// with a dodgy implementation
Thread.Sleep(1);
return x;
})
.ContinueWith(y => output.Add(y.Result), TaskContinuationOptions.ExecuteSynchronously))
.ToArray();
Task.WhenAll(tasks).AwaitingShouldCompleteIn(_waitTimeout);
output.Should().Equal(Enumerable.Range(1, 50));
}
[Fact]
public void ShouldRunMultipleVoidTasksInTheOrderTheyAreEnqueued()
{
var actor = CreateActor();
var output = new List<int>();
var tasks =
Enumerable.Range(1, 50)
.Select(x => actor.Enqueue(() =>
{
// Without this the test will usually pass even
// with a dodgy implementation
Thread.Sleep(1);
output.Add(x);
}))
.ToArray();
Task.WhenAll(tasks).AwaitingShouldCompleteIn(_waitTimeout);
output.Should().Equal(Enumerable.Range(1, 50));
}
[Fact]
public void ShouldHideSchedulerFromPotentialChildTasksOfBasicNonVoidTask()
{
var actor = CreateActor();
var task = actor.Enqueue(() => TaskScheduler.Current);
task.AwaitingShouldCompleteIn(_waitTimeout).And.Should().Be(TaskScheduler.Default);
}
[Fact]
public void ShouldHideSchedulerFromPotentialChildTasksOfBasicVoidTask()
{
var actor = CreateActor();
var taskScheduler = default(TaskScheduler);
actor.Enqueue(() => { taskScheduler = TaskScheduler.Current; }).AwaitingShouldCompleteIn(_waitTimeout);
taskScheduler.Should().Be(TaskScheduler.Default);
}
[Theory]
[InlineData(ResumeTestCase.AwaitOnTaskFactoryScheduledTask)]
[InlineData(ResumeTestCase.AwaitOnSecondActor)]
public void ShouldBeAbleToResumeAsyncNonVoidTask(ResumeTestCase testCase)
{
var actor1 = CreateActor();
var actor2 = CreateActor();
var stageOrder = new List<string>();
var expectedStageOrder =
new List<string>
{
"PreActor2Call",
"PreTrigger",
"PostTrigger",
"Slept",
"PostActor2Call"
};
var trigger = new TaskCompletionSource<bool>();
var suspendWork = default(Func<Task<int>>);
var actor1TaskSchedulers = new List<TaskScheduler>();
var actor1CurrentActorIds = new List<ActorId>();
var nonActor1CurrentActorIds = new List<ActorId>();
switch (testCase)
{
case ResumeTestCase.AwaitOnSecondActor:
suspendWork = () => actor2.Enqueue(() =>
{
nonActor1CurrentActorIds.Add(Actor.CurrentId);
ThrowIfWaitTimesOut(trigger.Task);
return 345;
});
break;
case ResumeTestCase.AwaitOnTaskFactoryScheduledTask:
suspendWork = () => Task.Factory.StartNew(() =>
{
nonActor1CurrentActorIds.Add(Actor.CurrentId);
ThrowIfWaitTimesOut(trigger.Task);
return 345;
});
break;
default:
throw new Exception($"Unhandled test case {testCase}.");
}
var task1 =
actor1.Enqueue(async () =>
{
actor1CurrentActorIds.Add(Actor.CurrentId);
stageOrder.Add("PreActor2Call");
actor1TaskSchedulers.Add(TaskScheduler.Current);
var value = await suspendWork();
stageOrder.Add("PostActor2Call");
actor1TaskSchedulers.Add(TaskScheduler.Current);
actor1CurrentActorIds.Add(Actor.CurrentId);
return value * 37;
});
var task2 =
actor1.Enqueue(() =>
{
actor1CurrentActorIds.Add(Actor.CurrentId);
actor1TaskSchedulers.Add(TaskScheduler.Current);
stageOrder.Add("PreTrigger");
trigger.SetResult(true);
stageOrder.Add("PostTrigger");
Thread.Sleep(TimeSpan.FromSeconds(0.5));
stageOrder.Add("Slept");
});
Task.WhenAll(task1, task2).AwaitingShouldCompleteIn(_waitTimeout);
actor1TaskSchedulers.Should().NotBeEmpty().And.OnlyContain(x => ReferenceEquals(x, TaskScheduler.Default));
stageOrder.Should().Equal(expectedStageOrder);
actor1CurrentActorIds.Should().NotBeEmpty().And.OnlyContain(x => x == actor1.Id);
nonActor1CurrentActorIds.Should().NotBeEmpty().And.OnlyContain(x => x != actor1.Id);
task1.Result.Should().Be(37 * 345);
}
[Theory]
[InlineData(ResumeTestCase.AwaitOnTaskFactoryScheduledTask)]
[InlineData(ResumeTestCase.AwaitOnSecondActor)]
public void ShouldBeAbleToResumeAsyncVoidTask(ResumeTestCase testCase)
{
var actor1 = CreateActor();
var actor2 = CreateActor();
var stageOrder = new List<string>();
var expectedStageOrder =
new List<string>
{
"PreActor2Call",
"PreTrigger",
"PostTrigger",
"Slept",
"PostActor2Call",
"Result=345"
};
var trigger = new TaskCompletionSource<bool>();
var suspendWork = default(Func<Task<int>>);
var actor1TaskSchedulers = new List<TaskScheduler>();
var actor1CurrentActorIds = new List<ActorId>();
var nonActor1CurrentActorIds = new List<ActorId>();
switch (testCase)
{
case ResumeTestCase.AwaitOnSecondActor:
suspendWork = () => actor2.Enqueue(() =>
{
nonActor1CurrentActorIds.Add(Actor.CurrentId);
ThrowIfWaitTimesOut(trigger.Task);
return 345;
});
break;
case ResumeTestCase.AwaitOnTaskFactoryScheduledTask:
suspendWork = () => Task.Factory.StartNew(() =>
{
nonActor1CurrentActorIds.Add(Actor.CurrentId);
ThrowIfWaitTimesOut(trigger.Task);
return 345;
});
break;
default:
throw new Exception($"Unhandled test case {testCase}.");
}
var task1 =
actor1.Enqueue(async () =>
{
actor1CurrentActorIds.Add(Actor.CurrentId);
actor1TaskSchedulers.Add(TaskScheduler.Current);
stageOrder.Add("PreActor2Call");
var value = await suspendWork();
stageOrder.Add("PostActor2Call");
Thread.Sleep(TimeSpan.FromSeconds(0.5));
stageOrder.Add($"Result={value}");
actor1TaskSchedulers.Add(TaskScheduler.Current);
actor1CurrentActorIds.Add(Actor.CurrentId);
});
var task2 =
actor1.Enqueue(() =>
{
actor1CurrentActorIds.Add(Actor.CurrentId);
actor1TaskSchedulers.Add(TaskScheduler.Current);
stageOrder.Add("PreTrigger");
trigger.SetResult(true);
stageOrder.Add("PostTrigger");
Thread.Sleep(TimeSpan.FromSeconds(0.5));
stageOrder.Add("Slept");
});
Task.WhenAll(task1, task2).AwaitingShouldCompleteIn(_waitTimeout);
actor1TaskSchedulers.Should().NotBeEmpty().And.OnlyContain(x => ReferenceEquals(x, TaskScheduler.Default));
stageOrder.Should().Equal(expectedStageOrder);
actor1CurrentActorIds.Should().NotBeEmpty().And.OnlyContain(x => x == actor1.Id);
nonActor1CurrentActorIds.Should().NotBeEmpty().And.OnlyContain(x => x != actor1.Id);
}
[Theory]
[InlineData(ActorEnqueueOptions.WorkIsLongRunning)]
[InlineData(ActorEnqueueOptions.Default)]
public async Task ShouldScheduleTaskAsLongRunningIfRequested(ActorEnqueueOptions enqueueOptions)
{
var actor = new Actor();
await actor.Start();
await actor.Awaiting(x => x.Enqueue(() => ValidateActorThread(enqueueOptions), enqueueOptions)).Should().NotThrowAsync();
await actor.Awaiting(
x => x.Enqueue(
() =>
{
ValidateActorThread(enqueueOptions);
return 676;
}, enqueueOptions)).Should().NotThrowAsync();
await actor.Awaiting(
x => x.Enqueue(
async () =>
{
await Task.Yield();
ValidateActorThread(enqueueOptions);
}, enqueueOptions)).Should().NotThrowAsync();
await actor.Awaiting(
x => x.Enqueue(
async () =>
{
await Task.Yield();
ValidateActorThread(enqueueOptions);
return "moose";
}, enqueueOptions)).Should().NotThrowAsync();
}
[Fact]
public void ShouldBeAbleToSpecifyWorkToRunAtStartUpWhichIsGuaranteedToBeTheFirstThingRun()
{
var numbers = new List<int>();
var actor = CreateActor(x => x.StartWork = new ActorStartWork(() => { numbers.Add(1); }), ActorCreateOptions.None);
_createdActors.Add(actor);
actor.Enqueue(() => numbers.Add(2));
var task = actor.Enqueue(() => numbers.Add(3));
var startTask = actor.Start();
startTask.AwaitingShouldCompleteIn(_waitTimeout);
task.AwaitingShouldCompleteIn(_waitTimeout);
numbers.Should().Equal(Enumerable.Range(1, 3));
}
[Fact]
public async Task ShouldNotEnqueueAnyMoreWorkAfterAskedToStop()
{
var stageOrder = new List<string>();
var expectedStageOrder =
new List<string>
{
"Start",
"Work1",
"Work2",
"Stop"
};
var actor = CreateActor(x =>
{
x.StartWork = new ActorStartWork(() => stageOrder.Add("Start"));
x.StopWork = new ActorStopWork(() => stageOrder.Add("Stop"));
},
ActorCreateOptions.None);
actor.Enqueue(() => stageOrder.Add("Work1"));
actor.Enqueue(() => stageOrder.Add("Work2"));
actor.Start().AwaitingShouldCompleteIn(_waitTimeout);
var stopTask = actor.Stop();
var lateWork = actor.Enqueue(() => stageOrder.Add("Work3"));
MarkAlreadyStopped();
await ShouldBeCancelled(lateWork);
stopTask.AwaitingShouldCompleteIn(_waitTimeout);
stageOrder.Should().Equal(expectedStageOrder);
}
[Fact]
public async Task ShouldCompleteStoppedTaskWhenStopCompleted()
{
var stageOrder = new List<string>();
var expectedStageOrder =
new List<string>
{
"Start",
"Stop",
"Stopped"
};
var actor = CreateActor(x =>
{
x.StartWork = new ActorStartWork(() => stageOrder.Add("Start"));
x.StopWork = new ActorStopWork(
() =>
{
Thread.Sleep(TimeSpan.FromMilliseconds(250));
stageOrder.Add("Stop");
});
},
ActorCreateOptions.None);
await actor.Start();
var stopTask = actor.Stop();
await actor.StoppedTask;
stageOrder.Add("Stopped");
await stopTask;
stageOrder.Should().Equal(expectedStageOrder);
}
[Fact]
public async Task ShouldCancelStoppedTokenWhenStopCompleted()
{
var actor = CreateActor(x => { }, ActorCreateOptions.None);
await actor.Start();
var cancelledPromise = new TaskCompletionSource<object>();
var cancellationRegistrationToken = actor.StoppedToken().Register(() => cancelledPromise.SetResult(null));
await actor.Stop();
cancelledPromise.Task.Wait(TimeSpan.FromMilliseconds(1000)).Should().BeTrue();
cancellationRegistrationToken.Dispose();
}
[Theory]
[InlineData(ResumeTestCase.AwaitOnTaskFactoryScheduledTask, StopWorkOutcome.Completes)]
[InlineData(ResumeTestCase.AwaitOnTaskFactoryScheduledTask, StopWorkOutcome.Faults)]
[InlineData(ResumeTestCase.AwaitOnSecondActor, StopWorkOutcome.Completes)]
[InlineData(ResumeTestCase.AwaitOnSecondActor, StopWorkOutcome.Faults)]
public async Task ShouldNotBeAbleToResumeWorkAfterStop(ResumeTestCase resumeTestCase, StopWorkOutcome stopWorkOutcome)
{
var actor1 = CreateActor(
x => x.StopWork = new ActorStopWork(
() =>
{
if (stopWorkOutcome == StopWorkOutcome.Faults)
{
throw new InvalidOperationException("Never meant to be");
}
}));
var actor2 = CreateActor();
var pretrigger = new TaskCompletionSource<bool>();
var trigger = new TaskCompletionSource<bool>();
var suspendWork = default(Func<Task<int>>);
var stages = new List<string>();
var expectedStageOrder =
new List<string>
{
"PreSuspend",
"PreTriggerWait",
"PostTriggerWait"
};
int OffActorWork()
{
stages.Add("PreTriggerWait");
pretrigger.SetResult(true);
ThrowIfWaitTimesOut(trigger.Task);
stages.Add("PostTriggerWait");
return 345;
}
switch (resumeTestCase)
{
case ResumeTestCase.AwaitOnSecondActor:
suspendWork = () => actor2.Enqueue((Func<int>)OffActorWork);
break;
case ResumeTestCase.AwaitOnTaskFactoryScheduledTask:
suspendWork = () => new TaskFactory(TaskScheduler.Default).StartNew(OffActorWork);
break;
default:
throw new Exception($"Unhandled test case {resumeTestCase}.");
}
//var task1 =
actor1.Enqueue(
async () =>
{
stages.Add("PreSuspend");
var value = await suspendWork();
stages.Add("PostSuspend");
return value * 37;
});
pretrigger.Task.AwaitingShouldCompleteIn(_waitTimeout);
stages.Should().Equal(expectedStageOrder.Take(2));
var stopTask = actor1.Stop();
MarkAlreadyStopped();
switch (stopWorkOutcome)
{
case StopWorkOutcome.Completes:
stopTask.AwaitingShouldCompleteIn(_waitTimeout);
break;
case StopWorkOutcome.Faults:
await ((Func<Task>)(async () => await stopTask)).Should().ThrowAsync<InvalidOperationException>().WithMessage("Never meant to be");
break;
default:
throw new Exception($"Unhandled test case {stopWorkOutcome}.");
}
trigger.SetResult(true);
Within.OneSecond(() => stages.Should().Equal(expectedStageOrder));
For.OneSecond(() => stages.Should().Equal(expectedStageOrder));
// The below would be nice but has proved intractable to achieve.
//task1.Awaiting(async x => await x).ShouldThrow<TaskCanceledException>();
actor2.Stop().Wait();
}
[Fact]
public void ShouldNotProcessAnyWorkUntilAsyncStartUpWorkIsComplete()
{
var trigger = new TaskCompletionSource<object>();
var numbers = new List<int>();
var actor = CreateActor(x => x.StartWork = new ActorStartWork(async () =>
{
await trigger.Task;
numbers.Add(1);
}),
ActorCreateOptions.None);
_createdActors.Add(actor);
actor.Enqueue(() => numbers.Add(2));
var task = actor.Enqueue(() => numbers.Add(3));
var startTask = actor.Start();
startTask.IsCompleted.Should().BeFalse();
trigger.SetResult(null);
startTask.AwaitingShouldCompleteIn(_waitTimeout);
task.AwaitingShouldCompleteIn(_waitTimeout);
numbers.Should().Equal(Enumerable.Range(1, 3));
}
[Fact]
public async Task ShouldNotStartProcessingIfStopAlreadyCalled()
{
var stageOrder = new List<string>();
var actor = CreateActor(x =>
{
x.StartWork = new ActorStartWork(() => stageOrder.Add("Start"));
x.StopWork = new ActorStopWork(() => stageOrder.Add("Stop"));
},
ActorCreateOptions.None);
var shouldBeCancelled =
new List<Task>
{
actor.Enqueue(() => stageOrder.Add("Work1")),
actor.Enqueue(() => stageOrder.Add("Work2"))
};
var stopTask = actor.Stop();
var startTask = actor.Start();
MarkAlreadyStopped();
startTask.AwaitingShouldCompleteIn(_waitTimeout);
stopTask.AwaitingShouldCompleteIn(_waitTimeout);
stageOrder.Should().BeEmpty();
await ShouldBeCancelled(shouldBeCancelled[0]);
await ShouldBeCancelled(shouldBeCancelled[1]);
}
[Fact]
public void ShouldProcessAlreadyQueuedWorkBeforeSignallingStoppedWhenAskedToStop()
{
var stageOrder = new List<string>();
var expectedStageOrder =
new List<string>
{
"Start",
"Work1",
"Work2",
"Stop"
};
var actor = CreateActor(x =>
{
x.StartWork = new ActorStartWork(() => stageOrder.Add("Start"));
x.StopWork = new ActorStopWork(() => stageOrder.Add("Stop"));
},
ActorCreateOptions.None);
actor.Enqueue(() => stageOrder.Add("Work1"));
actor.Enqueue(() => stageOrder.Add("Work2"));
actor.Start().AwaitingShouldCompleteIn(_waitTimeout);
actor.Stop().AwaitingShouldCompleteIn(_waitTimeout);
stageOrder.Should().Equal(expectedStageOrder);
}
[Fact]
public void ShouldProcessAlreadyQueuedWorkBeforeSignallingStoppedWhenAskedToStopWhilstStartWorkStillBeingProcessed()
{
var stageOrder = new List<string>();
var expectedStageOrder =
new List<string>
{
"Start",
"Work1",
"Work2",
"Stop"
};
var actor = CreateActor(x =>
{
x.StartWork = new ActorStartWork(() => stageOrder.Add("Start"));
x.StopWork = new ActorStopWork(() => stageOrder.Add("Stop"));
},
ActorCreateOptions.None);
actor.Enqueue(() => stageOrder.Add("Work1"));
actor.Enqueue(() => stageOrder.Add("Work2"));
var startTask = actor.Start();
var stopTask = actor.Stop();
startTask.AwaitingShouldCompleteIn(_waitTimeout);
stopTask.AwaitingShouldCompleteIn(_waitTimeout);
stageOrder.Should().Equal(expectedStageOrder);
}
[Theory]
[InlineData(ActorEnqueueOptions.WorkIsLongRunning)]
[InlineData(ActorEnqueueOptions.Default)]
public async Task ShouldScheduleStartTaskAsLongRunningIfRequested(ActorEnqueueOptions startOptions)
{
var actor = new Actor
{
StartWork = new ActorStartWork(() => ValidateActorThread(startOptions))
{
Options = startOptions
}
};
await actor.Awaiting(x => x.Start()).Should().NotThrowAsync();
}
[Theory]
[InlineData(ActorEnqueueOptions.WorkIsLongRunning)]
[InlineData(ActorEnqueueOptions.Default)]
public async Task ShouldScheduleStopTaskAsLongRunningIfRequested(ActorEnqueueOptions stopOptions)
{
var actor = new Actor
{
StopWork = new ActorStopWork(() => ValidateActorThread(stopOptions))
{
Options = stopOptions
}
};
await actor.Start();
await actor.Awaiting(x => x.Stop()).Should().NotThrowAsync();
}
[Fact]
public void ShouldSilentlyCompleteCallsToStartAfterTheFirstButOnlyOnceActorHasFinallyStarted()
{
var barrier = new TaskCompletionSource<bool>();
var attempts = 0;
var actor = CreateActor(x => x.StartWork = new ActorStartWork(() =>
{
Interlocked.Increment(ref attempts);
ThrowIfWaitTimesOut(barrier.Task);
}),
ActorCreateOptions.None);
var task1 = actor.Start();
var task2 = actor.Start();
task2.Wait(TimeSpan.FromSeconds(1)).Should().BeFalse("Should not have already completed.");
barrier.SetResult(true);
Task.WhenAll(task1, task2).AwaitingShouldCompleteIn(_waitTimeout);
attempts.Should().Be(1);
}
[Fact]
public void ShouldSilentlyCompleteCallsToStopAfterTheFirstButOnlyOnceActorHasFinallyStopped()
{
var barrier = new TaskCompletionSource<bool>();
var attempts = 0;
var actor = CreateActor(x => x.StopWork = new ActorStopWork(() =>
{
Interlocked.Increment(ref attempts);
ThrowIfWaitTimesOut(barrier.Task);
}));
var task1 = actor.Stop();
MarkAlreadyStopped();
var task2 = actor.Stop();
task2.Wait(TimeSpan.FromSeconds(1)).Should().BeFalse("Should not have already completed.");
barrier.SetResult(true);
Task.WhenAll(task1, task2).AwaitingShouldCompleteIn(_waitTimeout);
attempts.Should().Be(1);
}
[Fact]
public void ShouldOnlyBeAbleToSpecifyStartWorkOnce()
{
var actor = CreateActor(ActorCreateOptions.None);
actor.StartWork = new ActorStartWork(() => { });
Action action = () => actor.StartWork = new ActorStartWork(() => { });
action.Should().Throw<InvalidOperationException>().WithMessage("Start work already specified.");
}
[Fact]
public async Task ShouldHaveNoAmbientTransactionInStartUpWork()
{
var attempts = 0;
var actor = CreateActor(ActorCreateOptions.None)
.WithStartWork(async () =>
{
using (var scope = new TransactionScope(TransactionScopeOption.Suppress, TransactionScopeAsyncFlowOption.Enabled))
{
await Task.Delay(200);
} // Restores ambient transaction scope which should be null
if (Transaction.Current == null)
{
Interlocked.Increment(ref attempts);
}
});
await actor.Start();
attempts.Should().Be(1);
}
[Fact]
public async Task ShouldHaveNoAmbientTransactionInEnqueuedWork()
{
var attempts = 0;
var actor = CreateActor(ActorCreateOptions.None);
await actor.Start();
await actor.Enqueue(async () =>
{
using (var scope = new TransactionScope(TransactionScopeOption.Suppress, TransactionScopeAsyncFlowOption.Enabled))
{
await Task.Delay(200);
} // Restores ambient transaction scope which should be null
if (Transaction.Current == null)
{
Interlocked.Increment(ref attempts);
}
});
attempts.Should().Be(1);
}
[Fact]
public async Task ShouldHaveNoAmbientTransactionInEnqueuedWorkThatReturnsData()
{
var attempts = 0;
var actor = CreateActor(ActorCreateOptions.None);
await actor.Start();
var result = await actor.Enqueue(async () =>
{
using (var scope = new TransactionScope(TransactionScopeOption.Suppress, TransactionScopeAsyncFlowOption.Enabled))
{
await Task.Delay(200);
} // Restores ambient transaction scope which should be null
if (Transaction.Current == null)
{
Interlocked.Increment(ref attempts);
}
return attempts;
});
attempts.Should().Be(1);
result.Should().Be(1);
}
[Fact]
public async Task ShouldHaveNoAmbientTransactionInEnqueuedWorkThatIsSynchronousAndReturnsData()
{
var attempts = 0;
var actor = CreateActor(ActorCreateOptions.None);
await actor.Start();
var result = await actor.Enqueue(() =>
{
using (var scope = new TransactionScope(TransactionScopeOption.Suppress))
{
Thread.Sleep(200);
} // Restores ambient transaction scope which should be null
if (Transaction.Current == null)
{
Interlocked.Increment(ref attempts);
}
return attempts;
});
attempts.Should().Be(1);
result.Should().Be(1);
}
[Fact]
public void ShouldOnlyBeAbleToSpecifyStopWorkOnce()
{
var actor = CreateActor(ActorCreateOptions.None);
actor.StopWork = new ActorStopWork(() => { });
Action action = () => actor.StopWork = new ActorStopWork(() => { });
action.Should().Throw<InvalidOperationException>().WithMessage("Stop work already specified.");
}
[Fact]
public void ShouldNotBeAbleToSpecifyStartWorkOnceActorStarted()
{
var actor = CreateActor();
Action action = () => actor.StartWork = new ActorStartWork(() => { });
action.Should().Throw<InvalidOperationException>().WithMessage("Start work cannot be specified after starting an actor.");
}
[Fact]
public void ShouldNotBeAbleToSpecifyStopWorkOnceActorStarted()
{
var actor = CreateActor();
Action action = () => actor.StopWork = new ActorStopWork(() => { });
action.Should().Throw<InvalidOperationException>()
.WithMessage("Stop work cannot be specified after starting an actor.");
}
[Theory]
[InlineData(true)]
[InlineData(false)]
public async Task ShouldBeAbleToCancelAnyEnqueuedWork(bool delayStart)
{
var actor = CreateActor(delayStart ? ActorCreateOptions.None : ActorCreateOptions.Start);
var cancellationTokenSource1 = new CancellationTokenSource();
var cancellationTokenSource2 = new CancellationTokenSource();
var cancellationTokenSource3 = new CancellationTokenSource();
var cancellationTokenSource4 = new CancellationTokenSource();
cancellationTokenSource3.Cancel();
var task1 = actor.Enqueue(() => { cancellationTokenSource1.Cancel(); });
var task2 = actor.Enqueue(() =>
{
cancellationTokenSource1.Token.ThrowIfCancellationRequested();
return 28282;
}, cancellationTokenSource1.Token);
var task3 = actor.Enqueue(() =>
{
cancellationTokenSource2.Cancel();
cancellationTokenSource2.Token.ThrowIfCancellationRequested();
}, cancellationTokenSource2.Token);
var task4 = actor.Enqueue(() =>
{
cancellationTokenSource4.Cancel();
return 676;
});
var task5 = actor.Enqueue(async () =>
{
await Task.Delay(100);
cancellationTokenSource3.Token.ThrowIfCancellationRequested();
}, cancellationTokenSource3.Token);
var task6 = actor.Enqueue(async () => await Task.Delay(100));
var task7 = actor.Enqueue(async () =>
{
await Task.Delay(100);
cancellationTokenSource4.Token.ThrowIfCancellationRequested();
return "moose";
}, cancellationTokenSource4.Token);
var task8 = actor.Enqueue(async () =>
{
await Task.Delay(100);
return "moose";
});
if (delayStart)
{
await actor.Start();
}
await task1;
await task4;
await task6;
await task8;
await ShouldBeCancelled(task2);
await ShouldBeCancelled(task3);
await ShouldBeCancelled(task5);
await ShouldBeCancelled(task7);
}
[Theory]
[InlineData(StopTaskCancellationTestCase.CancelDuringWork)]
[InlineData(StopTaskCancellationTestCase.CancelPriorToInvoke)]
public async Task ShouldBeAbleToCancelStopWorkButNotTermination(StopTaskCancellationTestCase testCase)
{
var cancellationTokenSource = new CancellationTokenSource();
var startedStopWorkFlag = new TaskCompletionSource<bool>();
var actor = CreateActor(x => x.StopWork = new ActorStopWork(() =>
{
startedStopWorkFlag.SetResult(true);
Task.Delay(TimeSpan.FromMinutes(1)).Wait(cancellationTokenSource.Token);
},
cancellationTokenSource.Token));
var barrier = new TaskCompletionSource<bool>();
actor.Enqueue(() => ThrowIfWaitTimesOut(barrier.Task));
var stopTask = actor.Stop();
MarkAlreadyStopped();
switch (testCase)
{
case StopTaskCancellationTestCase.CancelPriorToInvoke:
cancellationTokenSource.Cancel();
barrier.SetResult(true);
break;
case StopTaskCancellationTestCase.CancelDuringWork:
barrier.SetResult(true);
startedStopWorkFlag.Task.AwaitingShouldCompleteIn(_waitTimeout);
cancellationTokenSource.Cancel();
break;
default:
throw new Exception($"Unhandled test case {testCase}.");
}
await ShouldBeCancelled(stopTask);
if (testCase == StopTaskCancellationTestCase.CancelPriorToInvoke)
{
startedStopWorkFlag.Task.Wait(TimeSpan.FromSeconds(1)).Should().BeFalse();
}
await ShouldBeCancelled(actor.Enqueue(() => { }));
}
[Fact]
public async Task ShouldNotFailEnqueuingWorkAlreadyCancelled()
{
var actor = CreateActor();
var cancellationTokenSource1 = new CancellationTokenSource();
var cancellationTokenSource2 = new CancellationTokenSource();
var cancellationTokenSource3 = new CancellationTokenSource();
var cancellationTokenSource4 = new CancellationTokenSource();
cancellationTokenSource1.Cancel();
cancellationTokenSource2.Cancel();
cancellationTokenSource3.Cancel();
cancellationTokenSource4.Cancel();
var task1 = actor.Enqueue(() => 28282, cancellationTokenSource1.Token);
var task2 = actor.Enqueue(() => { }, cancellationTokenSource2.Token);
var task3 = actor.Enqueue(async () => { await Task.Delay(100); }, cancellationTokenSource3.Token);
var task4 = actor.Enqueue(async () =>
{
await Task.Delay(100);
return "moose";
}, cancellationTokenSource4.Token);
await ShouldBeCancelled(task1);
await ShouldBeCancelled(task2);
await ShouldBeCancelled(task3);
await ShouldBeCancelled(task4);
}
[Fact]
public async Task ShouldStopActorAndNotProcessAnyAlreadyEnqueuedWorkIfStartWorkCancelled()
{
var cancellationTokenSource = new CancellationTokenSource();
var actor = CreateActor(x => x.StartWork = new ActorStartWork(() => { Task.Delay(TimeSpan.FromMinutes(1)).Wait(cancellationTokenSource.Token); }, cancellationTokenSource.Token),
ActorCreateOptions.None);
var attempts = 0;
var startTask = actor.Start();
var task = actor.Enqueue(() => Interlocked.Increment(ref attempts));
MarkAlreadyStopped();
cancellationTokenSource.Cancel();
await ShouldBeCancelled(startTask);
await ShouldBeCancelled(task);
await ShouldBeCancelled(actor.Enqueue(() => { }));
attempts.Should().Be(0);
}
[Theory]
[InlineData(ActorEnqueueOptions.Default, ActorEnqueueOptions.Default)]
[InlineData(ActorEnqueueOptions.WorkIsLongRunning, ActorEnqueueOptions.Default)]
[InlineData(ActorEnqueueOptions.WorkIsLongRunning, ActorEnqueueOptions.WorkIsLongRunning)]
[InlineData(ActorEnqueueOptions.Default, ActorEnqueueOptions.WorkIsLongRunning)]
public async Task ShouldBeAbleToPauseActorUntilResumeFromAwait(ActorEnqueueOptions awaiterOptions, ActorEnqueueOptions otherOptions)
{
// Do this repeatedly to try to expose race conditions in the pausing logic
for (var i = 0; i < 1000; i++)
{
var actor = new Actor();
var numbers = new List<int>();
await actor.Start();
var tasks = new Task[3];
tasks[0] =
actor.Enqueue(
async () =>
{
numbers.Add(i);
var task = Task.Run(() => numbers.Add(i + 1));
await task.WhileActorPaused();
numbers.Add(i + 2);
}, awaiterOptions);
tasks[1] = actor.Enqueue(() => numbers.Add(i + 3), otherOptions);
tasks[2] = actor.Enqueue(() => numbers.Add(i + 4), otherOptions);
await Task.WhenAll(tasks);
await actor.Stop();
numbers.Should().Equal(i, i + 1, i + 2, i + 3, i + 4);
}
}
[Theory]
[InlineData(ActorEnqueueOptions.Default, ActorEnqueueOptions.Default)]
[InlineData(ActorEnqueueOptions.WorkIsLongRunning, ActorEnqueueOptions.Default)]
[InlineData(ActorEnqueueOptions.WorkIsLongRunning, ActorEnqueueOptions.WorkIsLongRunning)]
[InlineData(ActorEnqueueOptions.Default, ActorEnqueueOptions.WorkIsLongRunning)]
public async Task ShouldBeAbleToPauseActorUntilResumeFromAwaitReturningData(ActorEnqueueOptions awaiterOptions, ActorEnqueueOptions otherOptions)
{
// Do this repeatedly to try to expose race conditions in the pausing logic
for (var i = 0; i < 1000; i++)
{
var actor = CreateActor();
var numbers = new List<int>();
await actor.Start();
var tasks = new Task[4];
tasks[0] =
actor.Enqueue(
async () =>
{
numbers.Add(i);
var next = await Task.Run(() => i + 1).WhileActorPaused();
numbers.Add(next);
}, awaiterOptions);
tasks[1] = actor.Enqueue(() => numbers.Add(i + 2), otherOptions);
tasks[2] = actor.Enqueue(() => numbers.Add(i + 3), otherOptions);
tasks[3] = actor.Enqueue(() => numbers.Add(i + 4), otherOptions);
foreach (var task in tasks)
{
await task;
}
await actor.Stop();
numbers.Should().Equal(i, i + 1, i + 2, i + 3, i + 4);
}
}
[Fact]
public async Task StopShouldNotRunStopWorkIfStartWorkFails()
{
var stopWorkCalled = false;
var actor =
new Actor
{
StartWork = new ActorStartWork(() => throw new Exception("Error.")),
StopWork = new ActorStopWork(() => stopWorkCalled = true)
};
await actor.Awaiting(x => x.Start()).Should().ThrowAsync<Exception>().WithMessage("Error.");
await actor.Stop();
stopWorkCalled.Should().BeFalse();
}
[Flags]
private enum ActorCreateOptions
{
None = 0,
Start = 0x01,
Default = Start
}
private IActor CreateActor(ActorCreateOptions options = ActorCreateOptions.Default)
{
return CreateActor(_ => { }, options);
}
private IActor CreateActor(Action<IActor> setup, ActorCreateOptions options = ActorCreateOptions.Default)
{
var actor = new Actor();
setup(actor);
_createdActors.Add(actor);
if (options.HasFlag(ActorCreateOptions.Start))
{
actor.Start().AwaitingShouldCompleteIn(_waitTimeout);
}
return actor;
}
private static async Task ShouldBeCancelled(Task task)
{
await Expect.That(async () => await task).Should().ThrowAsync<OperationCanceledException>();
}
private void MarkAlreadyStopped()
{
_createdActors.Clear(); // To avoid errors in TearDown when it fails to stop a second time.
}
private void ThrowIfWaitTimesOut(Task task)
{
if (!task.Wait(_waitTimeout))
{
throw new TimeoutException();
}
}
private static void ValidateActorThread(ActorEnqueueOptions enqueueOptions)
{
if (enqueueOptions.HasFlag(ActorEnqueueOptions.WorkIsLongRunning))
{
ActorThreadAssertions.CurrentThreadShouldNotBeThreadPoolThread();
}
else
{
ActorThreadAssertions.CurrentThreadShouldBeThreadPoolThread();
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq.Expressions;
using Stratus.Utilities;
using UnityEngine;
namespace Stratus
{
/// <summary>
/// A programmatic overlay for debugging use. You can use the preset window
/// for quick prototyping, or make your own windows.
/// </summary>
[StratusSingleton("Stratus Overlay", true, true)]
public partial class StratusGUI : StratusSingletonBehaviour<StratusGUI>
{
//------------------------------------------------------------------------/
// Declarations
//------------------------------------------------------------------------/
public class OverlayWindows
{
public Window Watch;
public Window Buttons;
public Console Console;
}
public delegate void OnGUILayout(Rect rect);
//------------------------------------------------------------------------/
// Properties
//------------------------------------------------------------------------/
/// <summary>
/// Displays the current FPS
/// </summary>
public static bool showFPS { get; set; } = true;
/// <summary>
/// The current screen size of the game window
/// </summary>
public static Vector2 screenSize
{
get
{
#if UNITY_EDITOR
string[] res = UnityEditor.UnityStats.screenRes.Split('x');
Vector2 screenSize = new Vector2(int.Parse(res[0]), int.Parse(res[1]));
#else
Vector2 screenSize = new Vector2(Screen.currentResolution.width, Screen.currentResolution.height);
#endif
return screenSize;
}
}
//------------------------------------------------------------------------/
// Fields
//------------------------------------------------------------------------/
/// <summary>
/// The anchored position of the default overlay window
/// </summary>
private OverlayWindows Windows = new OverlayWindows();
/// <summary>
/// All custom windows written by the user
/// </summary>
private Dictionary<string, Window> CustomWindows = new Dictionary<string, Window>();
/// <summary>
/// Displays the FPS in the game Window
/// </summary>
private FPSCounter fpsCounter = new FPSCounter();
///// <summary>
///// Draw requests
///// </summary>
//private List<OnGUILayout> drawRequests = new List<OnGUILayout>();
//------------------------------------------------------------------------/
// Messages
//------------------------------------------------------------------------/
protected override void OnAwake()
{
this.Reset();
StratusScene.onSceneChanged += this.OnSceneChanged;
}
private void Update()
{
if (showFPS)
{
this.fpsCounter.Update();
}
}
private void OnGUI()
{
this.Draw();
}
//------------------------------------------------------------------------/
// Methods: Static
//------------------------------------------------------------------------/
/// <summary>
/// Keeps watch of a given property/field
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="varExpr">An expression of a given variable of the form: '(()=> foo')</param>
/// <param name="behaviour">The owner object of this variable</param>
/// <example>Overlay.Watch(()=> foo, this);</example>
public static void Watch<T>(Expression<Func<T>> varExpr, string description = null, MonoBehaviour behaviour = null)
{
StratusMemberReference variableRef = StratusReflection.GetReference(varExpr);
Watcher watcher = new Watcher(variableRef, description, behaviour);
instance.Windows.Watch.Add(watcher);
}
/// <summary>
/// Adds a button to the overlay which invokes a function with no parameters.
/// </summary>
/// <param name="description">What description to use for the button</param>
/// <param name="onButtonDown">The function to be invoked when the button is pressed</param>
public static void AddButton(string description, Button.Callback onButtonDown)
{
Button button = new Button(description, onButtonDown);
instance.Windows.Buttons.Add(button);
}
/// <summary>
/// Adds a button to the overlay which invokes a function with no parameters
/// </summary>
/// <param name="onButtonDown"></param>
public static void AddButton(Button.Callback onButtonDown)
{
Button button = new Button(onButtonDown.Method.Name, onButtonDown);
instance.Windows.Buttons.Add(button);
}
/// <summary>
/// Adds a button to the overlay which invokes a function with any parameters.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="description">What description to use for the button</param>
/// <param name="onButtonDown">The function to be invoked when the button is pressed, using a lambda expresion to pass it: '()=>Foo(7)</param>
public static void AddButton<T>(string description, Button<T>.Callback onButtonDown)
{
Button<T> button = new Button<T>(description, onButtonDown);
instance.Windows.Buttons.Add(button);
}
public static void GUILayoutArea(Anchor anchor, Vector2 size, System.Action<Rect> onGUI)
{
Rect rect = StratusGUI.CalculateAnchoredPositionOnScreen(anchor, size);
UnityEngine.GUILayout.BeginArea(rect);
onGUI(rect);
UnityEngine.GUILayout.EndArea();
}
public static void GUILayoutArea(Anchor anchor, Vector2 size, GUIContent content, System.Action<Rect> onGUI)
{
Rect rect = StratusGUI.CalculateAnchoredPositionOnScreen(anchor, size);
UnityEngine.GUILayout.BeginArea(rect, content);
onGUI(rect);
UnityEngine.GUILayout.EndArea();
}
public static void GUILayoutArea(Anchor anchor, Vector2 size, GUIContent content, GUIStyle style, System.Action<Rect> onGUI)
{
Rect rect = StratusGUI.CalculateAnchoredPositionOnScreen(anchor, size);
UnityEngine.GUILayout.BeginArea(rect, content, style);
onGUI(rect);
UnityEngine.GUILayout.EndArea();
}
public static void GUILayoutArea(Anchor anchor, Vector2 size, GUIStyle style, System.Action<Rect> onGUI)
{
Rect rect = StratusGUI.CalculateAnchoredPositionOnScreen(anchor, size);
UnityEngine.GUILayout.BeginArea(rect, style);
onGUI(rect);
UnityEngine.GUILayout.EndArea();
}
public static void GUIBox(Rect rect, Color tint, GUIStyle style)
{
Color currentColor = GUI.color;
GUI.color = tint;
GUI.Box(rect, string.Empty, style);
GUI.color = currentColor;
}
public static void GUIBox(Rect rect, Color tint)
{
Color currentColor = GUI.color;
GUI.color = tint;
GUI.Box(rect, string.Empty);
GUI.color = currentColor;
}
//------------------------------------------------------------------------/
// Methods: Private
//------------------------------------------------------------------------/
/// <summary>
/// Resets all windows to their defaults
/// </summary>
private void Reset()
{
this.Windows.Watch = new Window("Watch", new Vector2(0.2f, 0.5f), Color.grey, Anchor.TopRight);
this.Windows.Buttons = new Window("Buttons", new Vector2(0.3f, 0.4f), Color.grey, Anchor.BottomRight);
}
/// <summary>
/// When the scene changes, reset all windows!
/// </summary>
private void OnSceneChanged()
{
this.Reset();
}
/// <summary>
/// Draws all overlay elements
/// </summary>
private void Draw()
{
// Draw all the innate windows
this.Windows.Watch.Draw();
this.Windows.Buttons.Draw();
// Draw all custom windows
foreach (KeyValuePair<string, Window> window in this.CustomWindows)
{
window.Value.Draw();
}
// Draw all custom content
// Show FPS
if (showFPS)
{
this.DisplayFPS();
}
}
private void DisplayFPS()
{
}
}
}
| |
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.Xml;
using System.Xml.Linq;
using Palmmedia.ReportGenerator.Core.Common;
using Palmmedia.ReportGenerator.Core.Logging;
using Palmmedia.ReportGenerator.Core.Parser.Filtering;
using Palmmedia.ReportGenerator.Core.Parser.Preprocessing;
using Palmmedia.ReportGenerator.Core.Properties;
namespace Palmmedia.ReportGenerator.Core.Parser
{
/// <summary>
/// Initiates the corresponding parser to the given report file.
/// </summary>
public class CoverageReportParser
{
/// <summary>
/// The Logger.
/// </summary>
private static readonly ILogger Logger = LoggerFactory.GetLogger(typeof(CoverageReportParser));
/// <summary>
/// The number reports that are parsed and processed in parallel.
/// </summary>
private readonly int numberOfReportsParsedInParallel;
/// <summary>
/// The number reports that are merged in parallel.
/// </summary>
private readonly int numberOfReportsMergedInParallel;
/// <summary>
/// Indicates whether test projects should be included.
/// </summary>
private readonly bool excludeTestProjects;
/// <summary>
/// The source directories.
/// </summary>
private readonly IEnumerable<string> sourceDirectories;
/// <summary>
/// The assembly filter.
/// </summary>
private readonly IFilter assemblyFilter;
/// <summary>
/// The class filter.
/// </summary>
private readonly IFilter classFilter;
/// <summary>
/// The file filter.
/// </summary>
private readonly IFilter fileFilter;
/// <summary>
/// The current merge count.
/// </summary>
private int mergeCount;
/// <summary>
/// Initializes a new instance of the <see cref="CoverageReportParser" /> class.
/// </summary>
/// <param name="numberOfReportsParsedInParallel">The number reports that are parsed and processed in parallel.</param>
/// <param name="numberOfReportsMergedInParallel">The number reports that are merged in parallel.</param>
/// <param name="sourceDirectories">The source directories.</param>
/// <param name="assemblyFilter">The assembly filter.</param>
/// <param name="classFilter">The class filter.</param>
/// <param name="fileFilter">The file filter.</param>
public CoverageReportParser(int numberOfReportsParsedInParallel, int numberOfReportsMergedInParallel, IEnumerable<string> sourceDirectories, IFilter assemblyFilter, IFilter classFilter, IFilter fileFilter)
{
this.numberOfReportsParsedInParallel = Math.Max(1, numberOfReportsParsedInParallel);
this.numberOfReportsMergedInParallel = Math.Max(1, numberOfReportsMergedInParallel);
this.sourceDirectories = sourceDirectories ?? throw new ArgumentNullException(nameof(sourceDirectories));
this.assemblyFilter = assemblyFilter ?? throw new ArgumentNullException(nameof(assemblyFilter));
this.classFilter = classFilter ?? throw new ArgumentNullException(nameof(classFilter));
this.fileFilter = fileFilter ?? throw new ArgumentNullException(nameof(fileFilter));
}
/// <summary>
/// Initializes a new instance of the <see cref="CoverageReportParser" /> class.
/// </summary>
/// <param name="numberOfReportsParsedInParallel">The number reports that are parsed and processed in parallel.</param>
/// <param name="numberOfReportsMergedInParallel">The number reports that are merged in parallel.</param>
/// <param name="excludeTestProjects">Indicates whether test projects should be included.</param>
/// <param name="sourceDirectories">The source directories.</param>
/// <param name="assemblyFilter">The assembly filter.</param>
/// <param name="classFilter">The class filter.</param>
/// <param name="fileFilter">The file filter.</param>
public CoverageReportParser(int numberOfReportsParsedInParallel, int numberOfReportsMergedInParallel, bool excludeTestProjects, IEnumerable<string> sourceDirectories, IFilter assemblyFilter, IFilter classFilter, IFilter fileFilter)
{
this.numberOfReportsParsedInParallel = Math.Max(1, numberOfReportsParsedInParallel);
this.numberOfReportsMergedInParallel = Math.Max(1, numberOfReportsMergedInParallel);
this.excludeTestProjects = excludeTestProjects;
this.sourceDirectories = sourceDirectories ?? throw new ArgumentNullException(nameof(sourceDirectories));
this.assemblyFilter = assemblyFilter ?? throw new ArgumentNullException(nameof(assemblyFilter));
this.classFilter = classFilter ?? throw new ArgumentNullException(nameof(classFilter));
this.fileFilter = fileFilter ?? throw new ArgumentNullException(nameof(fileFilter));
}
/// <summary>
/// Tries to initiate the correct parsers for the given reports.
/// </summary>
/// <param name="reportFiles">The report files to parse.</param>
/// <returns>
/// The IParser instance.
/// </returns>
public ParserResult ParseFiles(IReadOnlyCollection<string> reportFiles)
{
if (reportFiles == null)
{
throw new ArgumentNullException(nameof(reportFiles));
}
List<Task<ParserResult>> consumers = new List<Task<ParserResult>>();
try
{
using (BlockingCollection<ParserResult> blockingCollection = new BlockingCollection<ParserResult>())
{
foreach (var item in Enumerable.Range(0, this.numberOfReportsMergedInParallel))
{
consumers.Add(this.CreateConsumer(blockingCollection));
}
Task producer = this.CreateProducer(reportFiles, blockingCollection);
Task.WaitAll(consumers.Concat(new[] { producer }).ToArray());
}
}
catch (AggregateException ae)
{
foreach (var e in ae.Flatten().InnerExceptions)
{
if (e is UnsupportedParserException)
{
throw e;
}
}
throw;
}
List<ParserResult> results = consumers.Select(t => t.Result).ToList();
ParserResult finalResult = results.First();
foreach (ParserResult toBeMerged in results.Skip(1))
{
this.MergeResults(finalResult, toBeMerged);
}
return finalResult;
}
/// <summary>
/// Creates the consumer which merges the results.
/// </summary>
/// <param name="collection">The collection to pick results from.</param>
/// <returns>The task containing merged results or null in case this consumer has not merged any result.</returns>
private Task<ParserResult> CreateConsumer(BlockingCollection<ParserResult> collection)
{
return Task.Factory.StartNew(() =>
{
ParserResult result = new ParserResult();
foreach (ParserResult parserResult in collection.GetConsumingEnumerable())
{
this.MergeResults(result, parserResult);
}
return result;
});
}
/// <summary>
/// Merges the result1 with the result2.
/// </summary>
/// <param name="result1">The first result.</param>
/// <param name="result2">The second result.</param>
private void MergeResults(ParserResult result1, ParserResult result2)
{
Interlocked.Increment(ref this.mergeCount);
int currentProgress = this.mergeCount;
Logger.DebugFormat(Resources.StartingMergingResult, currentProgress);
result1.Merge(result2);
Logger.DebugFormat(Resources.FinishedMergingResult, currentProgress);
}
/// <summary>
/// Creates the producer which parses the files in parallel and creates parser results out of it.
/// </summary>
/// <param name="reportFiles">The files to parse.</param>
/// <param name="collection">The block collection to add the parsed results to.</param>
/// <returns>The Task.</returns>
private Task CreateProducer(IReadOnlyCollection<string> reportFiles, BlockingCollection<ParserResult> collection)
{
return Task.Factory.StartNew(() =>
{
try
{
int counter = 0;
Parallel.ForEach(
reportFiles,
new ParallelOptions { MaxDegreeOfParallelism = this.numberOfReportsParsedInParallel },
reportFile =>
{
int number = Interlocked.Increment(ref counter);
Logger.DebugFormat(Resources.LoadingReport, reportFile, number, reportFiles.Count);
try
{
bool isXml = false;
using (var sr = File.OpenText(reportFile))
{
// We need to read first non-space char in the file
var buf = new char[120];
while (sr.Read(buf, 0, buf.Length) > 0)
{
string block = new string(buf).TrimStart();
if (block.Length > 0)
{
isXml = block.StartsWith("<");
break;
}
}
}
List<ParserResult> parserResults = isXml
? this.ParseXmlFile(reportFile).ToList()
: this.ParseTextFile(File.ReadAllLines(reportFile)).ToList();
foreach (ParserResult parserResult in parserResults)
{
collection.Add(parserResult);
}
if (!parserResults.Any() && reportFile.EndsWith(".coverage", StringComparison.OrdinalIgnoreCase))
{
Logger.WarnFormat(Resources.ErrorCoverageFormat, reportFile);
}
Logger.DebugFormat(Resources.FinishedParsingFile, reportFile, number, reportFiles.Count);
}
catch (Exception ex) when (!(ex is UnsupportedParserException))
{
Logger.ErrorFormat(Resources.ErrorDuringReadingReport, reportFile, GetHumanReadableFileSize(reportFile), ex.GetExceptionMessageForDisplay());
}
});
}
finally
{
Logger.DebugFormat(Resources.ParsingCompleted, reportFiles.Count);
collection.CompleteAdding();
}
});
}
/// <summary>
/// Load elements in memory balanced manner.
/// </summary>
/// <param name="filePath">The filepath of the covergae file to load.</param>
/// <param name="elementName">The name of the elemens to load.</param>
/// <returns>The elements matchig the name.</returns>
private IEnumerable<XElement> GetXElements(string filePath, string elementName)
{
var readerSettings = new XmlReaderSettings() { DtdProcessing = DtdProcessing.Parse, XmlResolver = null };
using (XmlReader reader = XmlReader.Create(filePath, readerSettings))
{
while (reader.Read())
{
if (reader.NodeType == XmlNodeType.Element &&
reader.Name == elementName)
{
if (XNode.ReadFrom(reader) is XElement element)
{
yield return element;
}
}
}
}
}
/// <summary>
/// Tries to initiate the correct parsers for the given XML report. The result is merged into the given result.
/// The report may contain several reports. For every report an extra parser is initiated.
/// </summary>
/// <param name="filePath">The report file path to parse.</param>
/// <returns>The parser result.</returns>
private IEnumerable<ParserResult> ParseXmlFile(string filePath)
{
if (this.GetXElements(filePath, "PartCoverReport").Any())
{
throw new UnsupportedParserException(Resources.ErrorPartCover);
}
var elements = this.GetXElements(filePath, "CoverageSession").ToArray();
if (elements.Length > 0)
{
foreach (var item in elements)
{
Logger.Debug(Resources.PreprocessingReport);
new OpenCoverReportPreprocessor().Execute(item);
Logger.DebugFormat(Resources.InitiatingParser, "OpenCover");
yield return new OpenCoverParser(this.assemblyFilter, this.classFilter, this.fileFilter).Parse(item);
}
yield break;
}
elements = this.GetXElements(filePath, "Root").Where(e => e.Attribute("ReportType") != null).ToArray();
if (elements.Length > 0)
{
foreach (var item in elements)
{
Logger.Debug(Resources.PreprocessingReport);
new DotCoverReportPreprocessor().Execute(item);
Logger.DebugFormat(Resources.InitiatingParser, "dotCover");
yield return new DotCoverParser(this.assemblyFilter, this.classFilter, this.fileFilter).Parse(item);
}
yield break;
}
elements = this.GetXElements(filePath, "report").Where(e => e.Attribute("name") != null).ToArray();
if (elements.Length > 0)
{
foreach (var item in elements)
{
Logger.Debug(Resources.PreprocessingReport);
new JaCoCoReportPreprocessor(this.sourceDirectories).Execute(item);
Logger.DebugFormat(Resources.InitiatingParser, "JaCoCo");
var result = new JaCoCoParser(this.assemblyFilter, this.classFilter, this.fileFilter).Parse(item);
foreach (var sourceDirectory in this.sourceDirectories)
{
result.AddSourceDirectory(sourceDirectory);
}
yield return result;
}
yield break;
}
elements = this.GetXElements(filePath, "coverage").ToArray();
if (elements.Length > 0)
{
foreach (var item in elements)
{
if (item.Attribute("profilerVersion") != null)
{
Logger.DebugFormat(Resources.InitiatingParser, "NCover");
yield return new NCoverParser(this.assemblyFilter, this.classFilter, this.fileFilter).Parse(item);
}
else if (item.Attribute("clover") != null || item.Attribute("generated") != null)
{
Logger.Debug(Resources.PreprocessingReport);
new CloverReportPreprocessor(this.sourceDirectories).Execute(item);
Logger.DebugFormat(Resources.InitiatingParser, "Clover");
var result = new CloverParser(this.assemblyFilter, this.classFilter, this.fileFilter, this.excludeTestProjects).Parse(item);
foreach (var sourceDirectory in this.sourceDirectories)
{
result.AddSourceDirectory(sourceDirectory);
}
yield return result;
}
else if (item.Attributes().Count() > 1)
{
Logger.Debug(Resources.PreprocessingReport);
new CoberturaReportPreprocessor().Execute(item);
Logger.DebugFormat(Resources.InitiatingParser, "Cobertura");
yield return new CoberturaParser(this.assemblyFilter, this.classFilter, this.fileFilter).Parse(item);
}
else
{
Logger.DebugFormat(Resources.InitiatingParser, "mprof");
yield return new MProfParser(this.assemblyFilter, this.classFilter, this.fileFilter).Parse(item);
}
}
yield break;
}
elements = this.GetXElements(filePath, "CoverageDSPriv").ToArray();
if (elements.Length > 0)
{
foreach (var item in elements)
{
Logger.DebugFormat(Resources.InitiatingParser, "Visual Studio");
new VisualStudioReportPreprocessor().Execute(item);
yield return new VisualStudioParser(this.assemblyFilter, this.classFilter, this.fileFilter).Parse(item);
}
yield break;
}
elements = this.GetXElements(filePath, "results").ToArray();
if (elements.Length > 0)
{
foreach (var item in elements)
{
if (item.Element("modules") != null)
{
Logger.DebugFormat(Resources.InitiatingParser, "Dynamic Code Coverage");
new DynamicCodeCoverageReportPreprocessor().Execute(item);
yield return new DynamicCodeCoverageParser(this.assemblyFilter, this.classFilter, this.fileFilter).Parse(item);
}
}
yield break;
}
}
/// <summary>
/// Tries to initiate the correct parsers for the given text based report. The result is merged into the given result.
/// The report may contain several reports. For every report an extra parser is initiated.
/// </summary>
/// <param name="lines">The file's lines.</param>
/// <returns>The parser result.</returns>
private IEnumerable<ParserResult> ParseTextFile(string[] lines)
{
if (lines.Length == 0)
{
yield break;
}
if (lines[0].StartsWith("TN:") || lines[0].StartsWith("SF:"))
{
Logger.DebugFormat(Resources.InitiatingParser, "LCov");
yield return new LCovParser(this.assemblyFilter, this.classFilter, this.fileFilter).Parse(lines);
}
else if (lines[0].Contains(GCovParser.SourceElementInFirstLine))
{
Logger.Debug(Resources.PreprocessingReport);
new GCovReportPreprocessor(this.sourceDirectories).Execute(lines);
Logger.DebugFormat(Resources.InitiatingParser, "GCov");
var result = new GCovParser(this.assemblyFilter, this.classFilter, this.fileFilter).Parse(lines);
foreach (var sourceDirectory in this.sourceDirectories)
{
result.AddSourceDirectory(sourceDirectory);
}
yield return result;
}
}
/// <summary>
/// Get the file size in human readable format.
/// If size information is not available (e.g. IOException), '-' is returned.
/// </summary>
/// <param name="fileName">The name of the file.</param>
/// <returns>The file size.</returns>
private static string GetHumanReadableFileSize(string fileName)
{
try
{
long byteCount = new FileInfo(fileName).Length;
string[] suffixes = { "B", "KB", "MB", "GB", "TB", "PB", "EB" };
if (byteCount == 0)
{
return "0" + suffixes[0];
}
long bytes = Math.Abs(byteCount);
int place = Convert.ToInt32(Math.Floor(Math.Log(bytes, 1024)));
double num = Math.Round(bytes / Math.Pow(1024, place), 1);
return (Math.Sign(byteCount) * num).ToString() + suffixes[place];
}
catch (Exception)
{
return "-";
}
}
}
}
| |
using ClosedXML.Excel;
using System;
namespace ClosedXML_Examples
{
public class CFColorScaleLowMidHigh : IXLExample
{
public void Create(String filePath)
{
var workbook = new XLWorkbook();
var ws = workbook.AddWorksheet("Sheet1");
ws.FirstCell().SetValue(1)
.CellBelow().SetValue(1)
.CellBelow().SetValue(2)
.CellBelow().SetValue(3);
ws.RangeUsed().AddConditionalFormat().ColorScale()
.LowestValue(XLColor.Red)
.Midpoint(XLCFContentType.Percent, "50", XLColor.Yellow)
.HighestValue(XLColor.Green);
workbook.SaveAs(filePath);
}
}
public class CFColorScaleLowHigh : IXLExample
{
public void Create(String filePath)
{
var workbook = new XLWorkbook();
var ws = workbook.AddWorksheet("Sheet1");
ws.FirstCell().SetValue(1)
.CellBelow().SetValue(1)
.CellBelow().SetValue(2)
.CellBelow().SetValue(3);
ws.RangeUsed().AddConditionalFormat().ColorScale()
.Minimum(XLCFContentType.Number, "2", XLColor.Red)
.Maximum(XLCFContentType.Percentile, "90", XLColor.Green);
workbook.SaveAs(filePath);
}
}
public class CFColorScaleMinimumMaximum : IXLExample
{
public void Create(String filePath)
{
var workbook = new XLWorkbook();
var ws = workbook.AddWorksheet("Sheet1");
ws.FirstCell().SetValue(1)
.CellBelow().SetValue(1)
.CellBelow().SetValue(2)
.CellBelow().SetValue(3);
ws.RangeUsed().AddConditionalFormat().ColorScale()
.LowestValue(XLColor.FromHtml("#FFFF7128"))
.HighestValue(XLColor.FromHtml("#FFFFEF9C"));
workbook.SaveAs(filePath);
}
}
public class CFStartsWith : IXLExample
{
public void Create(String filePath)
{
var workbook = new XLWorkbook();
var ws = workbook.AddWorksheet("Sheet1");
ws.FirstCell().SetValue("Hello")
.CellBelow().SetValue("Hellos")
.CellBelow().SetValue("Hell")
.CellBelow().SetValue("Holl");
ws.RangeUsed().AddConditionalFormat().WhenStartsWith("Hell")
.Fill.SetBackgroundColor(XLColor.Red)
.Border.SetOutsideBorder(XLBorderStyleValues.Thick)
.Border.SetOutsideBorderColor(XLColor.Blue)
.Font.SetBold();
workbook.SaveAs(filePath);
}
}
public class CFEndsWith : IXLExample
{
public void Create(String filePath)
{
var workbook = new XLWorkbook();
var ws = workbook.AddWorksheet("Sheet1");
ws.FirstCell().SetValue("Hello")
.CellBelow().SetValue("Hellos")
.CellBelow().SetValue("Hell")
.CellBelow().SetValue("Holl");
ws.RangeUsed().AddConditionalFormat().WhenEndsWith("ll")
.Fill.SetBackgroundColor(XLColor.Red);
workbook.SaveAs(filePath);
}
}
public class CFIsBlank : IXLExample
{
public void Create(String filePath)
{
var workbook = new XLWorkbook();
var ws = workbook.AddWorksheet("Sheet1");
ws.FirstCell().SetValue("Hello")
.CellBelow().SetValue("")
.CellBelow().SetValue("")
.CellBelow().SetValue("Holl");
ws.RangeUsed().AddConditionalFormat().WhenIsBlank()
.Fill.SetBackgroundColor(XLColor.Red);
workbook.SaveAs(filePath);
}
}
public class CFNotBlank : IXLExample
{
public void Create(String filePath)
{
var workbook = new XLWorkbook();
var ws = workbook.AddWorksheet("Sheet1");
ws.FirstCell().SetValue("Hello")
.CellBelow().SetValue("")
.CellBelow().SetValue("")
.CellBelow().SetValue("Holl");
ws.RangeUsed().AddConditionalFormat().WhenNotBlank()
.Fill.SetBackgroundColor(XLColor.Red);
workbook.SaveAs(filePath);
}
}
public class CFIsError : IXLExample
{
public void Create(String filePath)
{
var workbook = new XLWorkbook();
var ws = workbook.AddWorksheet("Sheet1");
ws.FirstCell().SetValue("Hello")
.CellBelow().SetFormulaA1("1/0")
.CellBelow().SetFormulaA1("1/0")
.CellBelow().SetValue("Holl");
ws.RangeUsed().AddConditionalFormat().WhenIsError()
.Fill.SetBackgroundColor(XLColor.Red);
workbook.SaveAs(filePath);
}
}
public class CFNotError : IXLExample
{
public void Create(String filePath)
{
var workbook = new XLWorkbook();
var ws = workbook.AddWorksheet("Sheet1");
ws.FirstCell().SetValue("Hello")
.CellBelow().SetFormulaA1("1/0")
.CellBelow().SetFormulaA1("1/0")
.CellBelow().SetValue("Holl");
ws.RangeUsed().AddConditionalFormat().WhenNotError()
.Fill.SetBackgroundColor(XLColor.Red);
workbook.SaveAs(filePath);
}
}
public class CFContains : IXLExample
{
public void Create(String filePath)
{
var workbook = new XLWorkbook();
var ws = workbook.AddWorksheet("Sheet1");
ws.FirstCell().SetValue("Hello")
.CellBelow().SetValue("Hellos")
.CellBelow().SetValue("Hell")
.CellBelow().SetValue("Holl");
ws.RangeUsed().AddConditionalFormat().WhenContains("Hell")
.Fill.SetBackgroundColor(XLColor.Red);
workbook.SaveAs(filePath);
}
}
public class CFNotContains : IXLExample
{
public void Create(String filePath)
{
var workbook = new XLWorkbook();
var ws = workbook.AddWorksheet("Sheet1");
ws.FirstCell().SetValue("Hello")
.CellBelow().SetValue("Hellos")
.CellBelow().SetValue("Hell")
.CellBelow().SetValue("Holl");
ws.RangeUsed().AddConditionalFormat().WhenNotContains("Hell")
.Fill.SetBackgroundColor(XLColor.Red);
workbook.SaveAs(filePath);
}
}
public class CFEqualsString : IXLExample
{
public void Create(String filePath)
{
var workbook = new XLWorkbook();
var ws = workbook.AddWorksheet("Sheet1");
ws.FirstCell().SetValue("Hello")
.CellBelow().SetValue("Hellos")
.CellBelow().SetValue("Hell")
.CellBelow().SetValue("Holl");
ws.RangeUsed().AddConditionalFormat().WhenEquals("Hell")
.Fill.SetBackgroundColor(XLColor.Red);
workbook.SaveAs(filePath);
}
}
public class CFEqualsNumber : IXLExample
{
public void Create(String filePath)
{
var workbook = new XLWorkbook();
var ws = workbook.AddWorksheet("Sheet1");
ws.FirstCell().SetValue(1)
.CellBelow().SetValue(1)
.CellBelow().SetValue(2)
.CellBelow().SetValue(3);
ws.RangeUsed().AddConditionalFormat().WhenEquals(2)
.Fill.SetBackgroundColor(XLColor.Red);
workbook.SaveAs(filePath);
}
}
public class CFNotEqualsString : IXLExample
{
public void Create(String filePath)
{
var workbook = new XLWorkbook();
var ws = workbook.AddWorksheet("Sheet1");
ws.FirstCell().SetValue("Hello")
.CellBelow().SetValue("Hellos")
.CellBelow().SetValue("Hell")
.CellBelow().SetValue("Holl");
ws.RangeUsed().AddConditionalFormat().WhenNotEquals("Hell")
.Fill.SetBackgroundColor(XLColor.Red);
workbook.SaveAs(filePath);
}
}
public class CFNotEqualsNumber : IXLExample
{
public void Create(String filePath)
{
var workbook = new XLWorkbook();
var ws = workbook.AddWorksheet("Sheet1");
ws.FirstCell().SetValue(1)
.CellBelow().SetValue(1)
.CellBelow().SetValue(2)
.CellBelow().SetValue(3);
ws.RangeUsed().AddConditionalFormat().WhenNotEquals(2)
.Fill.SetBackgroundColor(XLColor.Red);
workbook.SaveAs(filePath);
}
}
public class CFGreaterThan : IXLExample
{
public void Create(String filePath)
{
var workbook = new XLWorkbook();
var ws = workbook.AddWorksheet("Sheet1");
ws.FirstCell().SetValue(1)
.CellBelow().SetValue(1)
.CellBelow().SetValue(2)
.CellBelow().SetValue(3);
ws.RangeUsed().AddConditionalFormat().WhenGreaterThan("2")
.Fill.SetBackgroundColor(XLColor.Red);
workbook.SaveAs(filePath);
}
}
public class CFEqualOrGreaterThan : IXLExample
{
public void Create(String filePath)
{
var workbook = new XLWorkbook();
var ws = workbook.AddWorksheet("Sheet1");
ws.FirstCell().SetValue(1)
.CellBelow().SetValue(1)
.CellBelow().SetValue(2)
.CellBelow().SetValue(3);
ws.RangeUsed().AddConditionalFormat().WhenEqualOrGreaterThan("2")
.Fill.SetBackgroundColor(XLColor.Red);
workbook.SaveAs(filePath);
}
}
public class CFLessThan : IXLExample
{
public void Create(String filePath)
{
var workbook = new XLWorkbook();
var ws = workbook.AddWorksheet("Sheet1");
ws.FirstCell().SetValue(1)
.CellBelow().SetValue(1)
.CellBelow().SetValue(2)
.CellBelow().SetValue(3);
ws.RangeUsed().AddConditionalFormat().WhenLessThan("2")
.Fill.SetBackgroundColor(XLColor.Red);
workbook.SaveAs(filePath);
}
}
public class CFEqualOrLessThan : IXLExample
{
public void Create(String filePath)
{
var workbook = new XLWorkbook();
var ws = workbook.AddWorksheet("Sheet1");
ws.FirstCell().SetValue(1)
.CellBelow().SetValue(1)
.CellBelow().SetValue(2)
.CellBelow().SetValue(3);
ws.RangeUsed().AddConditionalFormat().WhenEqualOrLessThan("2")
.Fill.SetBackgroundColor(XLColor.Red);
workbook.SaveAs(filePath);
}
}
public class CFBetween : IXLExample
{
public void Create(String filePath)
{
var workbook = new XLWorkbook();
var ws = workbook.AddWorksheet("Sheet1");
ws.FirstCell().SetValue(1)
.CellBelow().SetValue(1)
.CellBelow().SetValue(2)
.CellBelow().SetValue(3);
ws.RangeUsed().AddConditionalFormat().WhenBetween("2", "3")
.Fill.SetBackgroundColor(XLColor.Red);
workbook.SaveAs(filePath);
}
}
public class CFNotBetween : IXLExample
{
public void Create(String filePath)
{
var workbook = new XLWorkbook();
var ws = workbook.AddWorksheet("Sheet1");
ws.FirstCell().SetValue(1)
.CellBelow().SetValue(1)
.CellBelow().SetValue(2)
.CellBelow().SetValue(3);
ws.RangeUsed().AddConditionalFormat().WhenNotBetween("2", "3")
.Fill.SetBackgroundColor(XLColor.Red);
workbook.SaveAs(filePath);
}
}
public class CFUnique : IXLExample
{
public void Create(String filePath)
{
var workbook = new XLWorkbook();
var ws = workbook.AddWorksheet("Sheet1");
ws.FirstCell().SetValue(1)
.CellBelow().SetValue(1)
.CellBelow().SetValue(2)
.CellBelow().SetValue(3);
ws.RangeUsed().AddConditionalFormat().WhenIsUnique()
.Fill.SetBackgroundColor(XLColor.Red);
workbook.SaveAs(filePath);
}
}
public class CFDuplicate : IXLExample
{
public void Create(String filePath)
{
var workbook = new XLWorkbook();
var ws = workbook.AddWorksheet("Sheet1");
ws.FirstCell().SetValue(1)
.CellBelow().SetValue(1)
.CellBelow().SetValue(2)
.CellBelow().SetValue(3);
ws.RangeUsed().AddConditionalFormat().WhenIsDuplicate()
.Fill.SetBackgroundColor(XLColor.Red);
workbook.SaveAs(filePath);
}
}
public class CFIsTrue : IXLExample
{
public void Create(String filePath)
{
var workbook = new XLWorkbook();
var ws = workbook.AddWorksheet("Sheet1");
ws.FirstCell().SetValue(1)
.CellBelow().SetValue(1)
.CellBelow().SetValue(2)
.CellBelow().SetValue(3);
ws.RangeUsed().AddConditionalFormat().WhenIsTrue("TRUE")
.Fill.SetBackgroundColor(XLColor.Red);
workbook.SaveAs(filePath);
}
}
public class CFTop : IXLExample
{
public void Create(String filePath)
{
var workbook = new XLWorkbook();
var ws = workbook.AddWorksheet("Sheet1");
ws.FirstCell().SetValue(1)
.CellBelow().SetValue(1)
.CellBelow().SetValue(2)
.CellBelow().SetValue(3);
ws.RangeUsed().AddConditionalFormat().WhenIsTop(2)
.Fill.SetBackgroundColor(XLColor.Red);
workbook.SaveAs(filePath);
}
}
public class CFBottom : IXLExample
{
public void Create(String filePath)
{
var workbook = new XLWorkbook();
var ws = workbook.AddWorksheet("Sheet1");
ws.FirstCell().SetValue(1)
.CellBelow().SetValue(1)
.CellBelow().SetValue(2)
.CellBelow().SetValue(3);
ws.RangeUsed().AddConditionalFormat().WhenIsBottom(10, XLTopBottomType.Percent)
.Fill.SetBackgroundColor(XLColor.Red);
workbook.SaveAs(filePath);
}
}
public class CFDataBar : IXLExample
{
public void Create(String filePath)
{
var workbook = new XLWorkbook();
var ws = workbook.AddWorksheet("Sheet1");
ws.FirstCell().SetValue(1)
.CellBelow().SetValue(1)
.CellBelow().SetValue(2)
.CellBelow().SetValue(3);
ws.RangeUsed().AddConditionalFormat().DataBar(XLColor.Red, true)
.LowestValue()
.Maximum(XLCFContentType.Percent, "100");
workbook.SaveAs(filePath);
}
}
public class CFDataBarNegative : IXLExample
{
public void Create(String filePath)
{
var workbook = new XLWorkbook();
var ws = workbook.AddWorksheet("Sheet1");
ws.Cell(1, 1).SetValue(-1)
.CellBelow().SetValue(1)
.CellBelow().SetValue(2)
.CellBelow().SetValue(3);
ws.Range(ws.Cell(1, 1), ws.Cell(4, 1))
.AddConditionalFormat()
.DataBar(XLColor.Green, XLColor.Red, showBarOnly: false)
.LowestValue()
.HighestValue();
ws.Cell(1,3).SetValue(-20)
.CellBelow().SetValue(40)
.CellBelow().SetValue(-60)
.CellBelow().SetValue(30);
ws.Range(ws.Cell(1, 3), ws.Cell(4, 3))
.AddConditionalFormat()
.DataBar(XLColor.Green, XLColor.Red, showBarOnly: true)
.Minimum(XLCFContentType.Number, -100)
.Maximum(XLCFContentType.Number, 100);
workbook.SaveAs(filePath);
}
}
public class CFIconSet : IXLExample
{
public void Create(String filePath)
{
var workbook = new XLWorkbook();
var ws = workbook.AddWorksheet("Sheet1");
ws.FirstCell().SetValue(1)
.CellBelow().SetValue(1)
.CellBelow().SetValue(2)
.CellBelow().SetValue(3);
ws.RangeUsed().AddConditionalFormat().IconSet(XLIconSetStyle.ThreeTrafficLights2, true, true)
.AddValue(XLCFIconSetOperator.EqualOrGreaterThan, "0", XLCFContentType.Number)
.AddValue(XLCFIconSetOperator.EqualOrGreaterThan, "2", XLCFContentType.Number)
.AddValue(XLCFIconSetOperator.EqualOrGreaterThan, "3", XLCFContentType.Number);
workbook.SaveAs(filePath);
}
}
public class CFTwoConditions : IXLExample
{
public void Create(String filePath)
{
var workbook = new XLWorkbook();
var ws = workbook.AddWorksheet("Sheet1");
ws.FirstCell().SetValue(1)
.CellBelow().SetValue(1)
.CellBelow().SetValue(2)
.CellBelow().SetValue(3);
ws.RangeUsed().AddConditionalFormat().IconSet(XLIconSetStyle.ThreeTrafficLights2, true, true)
.AddValue(XLCFIconSetOperator.EqualOrGreaterThan, "0", XLCFContentType.Number)
.AddValue(XLCFIconSetOperator.EqualOrGreaterThan, "2", XLCFContentType.Number)
.AddValue(XLCFIconSetOperator.EqualOrGreaterThan, "3", XLCFContentType.Number);
ws.RangeUsed().AddConditionalFormat().WhenContains("1")
.Fill.SetBackgroundColor(XLColor.Red);
workbook.SaveAs(filePath);
}
}
public class CFInsertRows : IXLExample
{
public void Create(String filePath)
{
var workbook = new XLWorkbook();
var ws = workbook.AddWorksheet("Sheet1");
ws.Cell(2, 1).SetValue(1)
.CellRight().SetValue(1)
.CellRight().SetValue(2)
.CellRight().SetValue(3);
var range = ws.RangeUsed();
range.AddConditionalFormat().WhenEquals("1").Font.SetBold();
range.InsertRowsAbove(1);
workbook.SaveAs(filePath);
}
}
public class CFTest : IXLExample
{
public void Create(String filePath)
{
var workbook = new XLWorkbook();
var ws = workbook.AddWorksheet("Sheet1");
ws.FirstCell().SetValue(1)
.CellBelow().SetValue(1)
.CellBelow().SetValue(2)
.CellBelow().SetValue(3)
.CellBelow().SetValue(4);
ws.RangeUsed().AddConditionalFormat().DataBar(XLColor.Red, XLColor.Green)
.LowestValue()
.HighestValue();
workbook.SaveAs(filePath);
}
}
public class CFMultipleConditions : IXLExample
{
public void Create(String filePath)
{
var workbook = new XLWorkbook();
var ws = workbook.AddWorksheet("Sheet1");
using (var range = ws.Range("A1:A10"))
{
range.AddConditionalFormat().WhenEquals("3")
.Fill.SetBackgroundColor(XLColor.Blue);
range.AddConditionalFormat().WhenEquals("2")
.Fill.SetBackgroundColor(XLColor.Green);
range.AddConditionalFormat().WhenEquals("1")
.Fill.SetBackgroundColor(XLColor.Red);
}
workbook.SaveAs(filePath);
}
}
}
| |
#region License
/*
* All content copyright Terracotta, Inc., unless otherwise indicated. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy
* of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*
*/
#endregion
using Quartz.Util;
using System;
using System.Globalization;
using System.Runtime.Serialization;
using System.Security;
namespace Quartz.Impl.Calendar
{
/// <summary>
/// This implementation of the Calendar excludes a set of days of the month. You
/// may use it to exclude every 1. of each month for example. But you may define
/// any day of a month.
/// </summary>
/// <seealso cref="ICalendar" />
/// <seealso cref="BaseCalendar" />
/// <author>Juergen Donnerstag</author>
/// <author>Marko Lahma (.NET)</author>
[Serializable]
public class MonthlyCalendar : BaseCalendar
{
private const int MaxDaysInMonth = 31;
// An array to store a months days which are to be excluded.
// Day as index.
private bool[] excludeDays = new bool[MaxDaysInMonth];
// Will be set to true, if all week days are excluded
private bool excludeAll;
/// <summary>
/// Initializes a new instance of the <see cref="MonthlyCalendar"/> class.
/// </summary>
public MonthlyCalendar()
{
Init();
}
/// <summary>
/// Constructor
/// </summary>
/// <param name="baseCalendar">The base calendar.</param>
public MonthlyCalendar(ICalendar baseCalendar) : base(baseCalendar)
{
Init();
}
/// <summary>
/// Serialization constructor.
/// </summary>
/// <param name="info"></param>
/// <param name="context"></param>
protected MonthlyCalendar(SerializationInfo info, StreamingContext context) : base(info, context)
{
int version;
try
{
version = info.GetInt32("version");
}
catch
{
version = 0;
}
switch (version)
{
case 0:
case 1:
excludeDays = (bool[]) info.GetValue("excludeDays", typeof (bool[]));
excludeAll = (bool) info.GetValue("excludeAll", typeof (bool));
break;
default:
throw new NotSupportedException("Unknown serialization version");
}
}
[SecurityCritical]
public override void GetObjectData(SerializationInfo info, StreamingContext context)
{
base.GetObjectData(info, context);
info.AddValue("version", 1);
info.AddValue("excludeDays", excludeDays);
info.AddValue("excludeAll", excludeAll);
}
/// <summary>
/// Initialize internal variables
/// </summary>
private void Init()
{
// all days are included by default
excludeAll = AreAllDaysExcluded();
}
/// <summary>
/// Get or set the array which defines the exclude-value of each day of month
/// Setting will redefine the array of days excluded. The array must of size greater or
/// equal 31.
/// </summary>
public virtual bool[] DaysExcluded
{
get { return excludeDays; }
set
{
if (value == null)
{
return;
}
excludeDays = value;
excludeAll = AreAllDaysExcluded();
}
}
/// <summary>
/// Return true, if day is defined to be excluded.
/// </summary>
public virtual bool IsDayExcluded(int day)
{
if ((day < 1) || (day > MaxDaysInMonth))
{
throw new ArgumentException(
string.Format(CultureInfo.InvariantCulture, "The day parameter must be in the range of 1 to {0}", MaxDaysInMonth));
}
return excludeDays[day - 1];
}
/// <summary>
/// Redefine a certain day of the month to be excluded (true) or included
/// (false).
/// </summary>
public virtual void SetDayExcluded(int day, bool exclude)
{
excludeDays[day - 1] = exclude;
excludeAll = AreAllDaysExcluded();
}
/// <summary>
/// Check if all days are excluded. That is no day is included.
/// </summary>
/// <returns> boolean
/// </returns>
public virtual bool AreAllDaysExcluded()
{
for (int i = 1; i <= 31; i++)
{
if (IsDayExcluded(i) == false)
{
return false;
}
}
return true;
}
/// <summary>
/// Determine whether the given time (in milliseconds) is 'included' by the
/// Calendar.
/// <para>
/// Note that this Calendar is only has full-day precision.
/// </para>
/// </summary>
public override bool IsTimeIncluded(DateTimeOffset timeStampUtc)
{
if (excludeAll)
{
return false;
}
// Test the base calendar first. Only if the base calendar not already
// excludes the time/date, continue evaluating this calendar instance.
if (!base.IsTimeIncluded(timeStampUtc))
{
return false;
}
timeStampUtc = TimeZoneUtil.ConvertTime(timeStampUtc, this.TimeZone); //apply the timezone
int day = timeStampUtc.Day;
return !(IsDayExcluded(day));
}
/// <summary>
/// Determine the next time (in milliseconds) that is 'included' by the
/// Calendar after the given time. Return the original value if timeStamp is
/// included. Return DateTime.MinValue if all days are excluded.
/// <para>
/// Note that this Calendar is only has full-day precision.
/// </para>
/// </summary>
public override DateTimeOffset GetNextIncludedTimeUtc(DateTimeOffset timeUtc)
{
if (excludeAll)
{
return DateTimeOffset.MinValue;
}
// Call base calendar implementation first
DateTimeOffset baseTime = base.GetNextIncludedTimeUtc(timeUtc);
if ((baseTime != DateTimeOffset.MinValue) && (baseTime > timeUtc))
{
timeUtc = baseTime;
}
//apply the timezone
timeUtc = TimeZoneUtil.ConvertTime(timeUtc, this.TimeZone);
// Get timestamp for 00:00:00, in the correct timezone offset
DateTimeOffset newTimeStamp = new DateTimeOffset(timeUtc.Date, timeUtc.Offset);
int day = newTimeStamp.Day;
if (!IsDayExcluded(day))
{
return newTimeStamp;
} // return the original value with the correct offset time.
while (IsDayExcluded(day))
{
newTimeStamp = newTimeStamp.AddDays(1);
day = newTimeStamp.Day;
}
return newTimeStamp;
}
/// <summary>
/// Creates a new object that is a copy of the current instance.
/// </summary>
/// <returns>A new object that is a copy of this instance.</returns>
public override object Clone()
{
MonthlyCalendar clone = (MonthlyCalendar) base.Clone();
bool[] excludeCopy = new bool[excludeDays.Length];
Array.Copy(excludeDays, excludeCopy, excludeDays.Length);
clone.excludeDays = excludeCopy;
return clone;
}
public override int GetHashCode()
{
int baseHash = 0;
if (GetBaseCalendar() != null)
{
baseHash = GetBaseCalendar().GetHashCode();
}
return DaysExcluded.GetHashCode() + 5*baseHash;
}
public bool Equals(MonthlyCalendar obj)
{
//a little trick here : Monthly calendar knows nothing
//about the precise month it is dealing with, so
//FebruaryCalendars will be only equal if their
//31st days are equally included
//but that's not going to be a problem since
//there's no need to redefine default value of false
//for such days
if (obj == null)
{
return false;
}
bool baseEqual = GetBaseCalendar() == null || GetBaseCalendar().Equals(obj.GetBaseCalendar());
return baseEqual && (ArraysEqualElementsOnEqualPlaces(DaysExcluded, obj.DaysExcluded)
);
}
public override bool Equals(object obj)
{
if (!(obj is MonthlyCalendar))
{
return false;
}
else
{
return Equals((MonthlyCalendar) obj);
}
}
}
}
| |
///////////////////////////////////////////////////////////////////////////////////
//// Paint.NET (MIT,from version 3.36.7, see=> https://github.com/rivy/OpenPDN //
//// Copyright (C) dotPDN LLC, Rick Brewster, Tom Jackson, and contributors. //
//// Portions Copyright (C) Microsoft Corporation. All Rights Reserved. //
//// See src/Resources/Files/License.txt for full licensing and attribution //
//// details. //
//// . //
///////////////////////////////////////////////////////////////////////////////////
//#include "GeneratedCodeWarning.h"
//using System;
//// The generalized alpha compositing formula, "B OVER A" is:
//// C(A,a,B,b) = bB + aA - baA
//// where:
//// A = background color value
//// a = background alpha value
//// B = foreground color value
//// b = foreground alpha value
////
//// However, we need a general formula for composition based on any type of
//// blend operation and not just for 'normal' blending. We want multiplicative,
//// additive, etc. blend operations.
////
//// The generalized alpha compositing formula w.r.t. a replaceable blending
//// function is:
////
//// G(A,a,B,b,F) = (a - ab)A + (b - ab)B + abF(A, B)
////
//// Where F is a function of A and B, or F(A,B), that results in another color
//// value. For A OVER B blending, we simply use F(A,B) = B. It can be easily
//// shown that the two formulas simplify to the same expression when this F is
//// used.
////
//// G can be generalized even further to take a function for the other input
//// values. This can be useful if one wishes to implement something like
//// (1 - B) OVER A blending.
////
//// In this reality, F(A,B) is really F(A,B,r). The syntax "r = F(A,B)" is
//// the same as "F(A,B,r)" where r is essentially an 'out' parameter.
//// Multiplies a and b, which are [0,255] as if they were scaled to [0,1], and returns the result in r
//// a and b are evaluated once. r is evaluated multiple times.
//#define INT_SCALE_MULT(a, b) ((a) * (b) + 0x80)
//#define INT_SCALE_DIV(r) ((((r) >> 8) + (r)) >> 8)
//#define INT_SCALE(a, b, r) { r = INT_SCALE_MULT(a, b); r = INT_SCALE_DIV(r); }
//#define COMPUTE_ALPHA(a, b, r) { INT_SCALE(a, 255 - (b), r); r += (b); }
//// F(A,B) = blending function for the pixel values
//// h(a) = function for loading lhs.A, usually just ID
//// j(a) = function for loading rhs.A, usually just ID
//#define BLEND(lhs, rhs, F, h, j) \
// int lhsA; \
// h((lhs).A, lhsA); \
// int rhsA; \
// j((rhs).A, rhsA); \
// int y; \
// INT_SCALE(lhsA, 255 - rhsA, y); \
// int totalA = y + rhsA; \
// uint ret; \
// \
// if (totalA == 0) \
// { \
// ret = 0; \
// } \
// else \
// { \
// int fB; \
// int fG; \
// int fR; \
// \
// F((lhs).B, (rhs).B, fB); \
// F((lhs).G, (rhs).G, fG); \
// F((lhs).R, (rhs).R, fR); \
// \
// int x; \
// INT_SCALE(lhsA, rhsA, x); \
// int z = rhsA - x; \
// \
// int masIndex = totalA * 3; \
// uint taM = masTable[masIndex]; \
// uint taA = masTable[masIndex + 1]; \
// uint taS = masTable[masIndex + 2]; \
// \
// uint b = (uint)(((((long)((((lhs).B * y) + ((rhs).B * z) + (fB * x)))) * taM) + taA) >> (int)taS); \
// uint g = (uint)(((((long)((((lhs).G * y) + ((rhs).G * z) + (fG * x)))) * taM) + taA) >> (int)taS); \
// uint r = (uint)(((((long)((((lhs).R * y) + ((rhs).R * z) + (fR * x)))) * taM) + taA) >> (int)taS); \
// int a; \
// COMPUTE_ALPHA(lhsA, rhsA, a); \
// \
// ret = b + (g << 8) + (r << 16) + ((uint)a << 24); \
// } \
//#define IMPLEMENT_INSTANCE_FUNCTIONS(F, h, j) \
// public override ColorBgra Apply(ColorBgra lhs, ColorBgra rhs) \
// { \
// BLEND(lhs, rhs, F, h, j); \
// return ColorBgra.FromUInt32(ret); \
// } \
// \
// public unsafe override void Apply(ColorBgra *dst, ColorBgra *src, int length) \
// { \
// while (length > 0) \
// { \
// BLEND(*dst, *src, F, h, j); \
// dst->Bgra = ret; \
// ++dst; \
// ++src; \
// --length; \
// } \
// } \
// \
// public unsafe override void Apply(ColorBgra *dst, ColorBgra *lhs, ColorBgra *rhs, int length) \
// { \
// while (length > 0) \
// { \
// BLEND(*lhs, *rhs, F, h, j); \
// dst->Bgra = ret; \
// ++dst; \
// ++lhs; \
// ++rhs; \
// --length; \
// } \
// }
//#define IMPLEMENT_STATIC_FUNCTIONS(F, h, j) \
// public static ColorBgra ApplyStatic(ColorBgra lhs, ColorBgra rhs) \
// { \
// BLEND(lhs, rhs, F, h, j); \
// return ColorBgra.FromUInt32(ret); \
// }
//#define IMPLEMENT_OP_STATICNAME(NAME) \
// public static string StaticName \
// { \
// get \
// { \
// return PdnResources.GetString("UserBlendOps." + #NAME + "BlendOp.Name"); \
// } \
// } \
//#define ID(x, r) { r = (x); }
//#define ALPHA_WITH_OPACITY(a, r) INT_SCALE(a, this.opacity, r)
//#define APPLY_OPACITY_ADAPTER(a, r) { r = ApplyOpacity(a); }
//#define DEFINE_OP(NAME, PROTECTION, F, h, j) \
// \
// PROTECTION sealed class NAME##BlendOp \
// : UserBlendOp \
// { \
// IMPLEMENT_OP_STATICNAME(NAME) \
// IMPLEMENT_INSTANCE_FUNCTIONS(F, h, j) \
// IMPLEMENT_STATIC_FUNCTIONS(F, h, j) \
// \
// public override UserBlendOp CreateWithOpacity(int opacity) \
// { \
// return new NAME##BlendOpWithOpacity(opacity); \
// } \
// \
// private sealed class NAME##BlendOpWithOpacity \
// : UserBlendOp \
// { \
// private int opacity; \
// \
// private byte ApplyOpacity(byte a) \
// { \
// int r; \
// j(a, r); \
// ALPHA_WITH_OPACITY(r, r); \
// return (byte)r; \
// } \
// \
// IMPLEMENT_OP_STATICNAME(NAME) \
// \
// IMPLEMENT_INSTANCE_FUNCTIONS(F, h, APPLY_OPACITY_ADAPTER) \
// \
// public NAME##BlendOpWithOpacity(int opacity) \
// { \
// if (this.opacity < 0 || this.opacity > 255) \
// { \
// throw new ArgumentOutOfRangeException(); \
// } \
// \
// this.opacity = opacity; \
// } \
// } \
// }
//#define DEFINE_STANDARD_OP(NAME, F) DEFINE_OP(NAME, public, F, ID, ID)
//#define OVER(A, B, r) \
//{ \
// r = (B); \
//}
//#define MULTIPLY(A, B, r) \
//{ \
// INT_SCALE((A), (B), r); \
//}
//#define MIN(A, B, r) \
//{ \
// r = Math.Min(A, B); \
//}
//#define MAX(A, B, r) \
//{ \
// r = Math.Max(A, B); \
//}
//#define SATURATE(A, B, r) \
//{ \
// r = Math.Min(255, (A) + (B)); \
//}
//// n DIV d
//#define INT_DIV(n, d, r) \
//{ \
// int i = (d) * 3; \
// uint M = masTable[i]; \
// uint A = masTable[i + 1]; \
// uint S = masTable[i + 2]; \
// r = (int)(((n * M) + A) >> (int)S); \
//}
////{ r = (((B) == 0) ? 0 : Math.Max(0, (255 - (((255 - (A)) * 255) / (B))))); }
//#define COLORBURN(A, B, r) \
//{ \
// if ((B) == 0) \
// { \
// r = 0; \
// } \
// else \
// { \
// INT_DIV(((255 - (A)) * 255), (B), r); \
// r = 255 - r; \
// r = Math.Max(0, r); \
// } \
//}
//// { r = ((B) == 255 ? 255 : Math.Min(255, ((A) * 255) / (255 - (B)))); }
//#define COLORDODGE(A, B, r) \
//{ \
// if ((B) == 255) \
// { \
// r = 255; \
// } \
// else \
// { \
// INT_DIV(((A) * 255), (255 - (B)), r); \
// r = Math.Min(255, r); \
// } \
//}
//// r = { (((B) == 255) ? 255 : Math.Min(255, ((A) * (A)) / (255 - (B)))); }
//#define REFLECT(A, B, r) \
//{ \
// if ((B) == 255) \
// { \
// r = 255; \
// } \
// else \
// { \
// INT_DIV((A) * (A), 255 - (B), r); \
// r = Math.Min(255, r); \
// } \
//}
//#define GLOW(A, B, r) REFLECT(B, A, r)
//#define OVERLAY(A, B, r) \
//{ \
// if ((A) < 128) \
// { \
// INT_SCALE(2 * (A), (B), r); \
// } \
// else \
// { \
// INT_SCALE(2 * (255 - (A)), 255 - (B), r); \
// r = 255 - r; \
// } \
//}
//#define DIFFERENCE(A, B, r) \
//{ \
// r = Math.Abs((B) - (A)); \
//}
//#define NEGATION(A, B, r) \
//{ \
// r = (255 - Math.Abs(255 - (A) - (B))); \
//}
////{ r = ((B) + (A) - (((B) * (A)) / 255)); }
//#define SCREEN(A, B, r) \
//{ \
// INT_SCALE((B), (A), r); \
// r = (B) + (A) - r; \
//}
//#define XOR(A, B, r) \
//{ \
// r = ((A) ^ (B)); \
//}
//namespace PixelFarm.Drawing
//{
// partial class UserBlendOps
// {
// // i = z * 3;
// // (x / z) = ((x * masTable[i]) + masTable[i + 1]) >> masTable[i + 2)
// private static readonly uint[] masTable =
// {
// 0x00000000, 0x00000000, 0, // 0
// 0x00000001, 0x00000000, 0, // 1
// 0x00000001, 0x00000000, 1, // 2
// 0xAAAAAAAB, 0x00000000, 33, // 3
// 0x00000001, 0x00000000, 2, // 4
// 0xCCCCCCCD, 0x00000000, 34, // 5
// 0xAAAAAAAB, 0x00000000, 34, // 6
// 0x49249249, 0x49249249, 33, // 7
// 0x00000001, 0x00000000, 3, // 8
// 0x38E38E39, 0x00000000, 33, // 9
// 0xCCCCCCCD, 0x00000000, 35, // 10
// 0xBA2E8BA3, 0x00000000, 35, // 11
// 0xAAAAAAAB, 0x00000000, 35, // 12
// 0x4EC4EC4F, 0x00000000, 34, // 13
// 0x49249249, 0x49249249, 34, // 14
// 0x88888889, 0x00000000, 35, // 15
// 0x00000001, 0x00000000, 4, // 16
// 0xF0F0F0F1, 0x00000000, 36, // 17
// 0x38E38E39, 0x00000000, 34, // 18
// 0xD79435E5, 0xD79435E5, 36, // 19
// 0xCCCCCCCD, 0x00000000, 36, // 20
// 0xC30C30C3, 0xC30C30C3, 36, // 21
// 0xBA2E8BA3, 0x00000000, 36, // 22
// 0xB21642C9, 0x00000000, 36, // 23
// 0xAAAAAAAB, 0x00000000, 36, // 24
// 0x51EB851F, 0x00000000, 35, // 25
// 0x4EC4EC4F, 0x00000000, 35, // 26
// 0x97B425ED, 0x97B425ED, 36, // 27
// 0x49249249, 0x49249249, 35, // 28
// 0x8D3DCB09, 0x00000000, 36, // 29
// 0x88888889, 0x00000000, 36, // 30
// 0x42108421, 0x42108421, 35, // 31
// 0x00000001, 0x00000000, 5, // 32
// 0x3E0F83E1, 0x00000000, 35, // 33
// 0xF0F0F0F1, 0x00000000, 37, // 34
// 0x75075075, 0x75075075, 36, // 35
// 0x38E38E39, 0x00000000, 35, // 36
// 0x6EB3E453, 0x6EB3E453, 36, // 37
// 0xD79435E5, 0xD79435E5, 37, // 38
// 0x69069069, 0x69069069, 36, // 39
// 0xCCCCCCCD, 0x00000000, 37, // 40
// 0xC7CE0C7D, 0x00000000, 37, // 41
// 0xC30C30C3, 0xC30C30C3, 37, // 42
// 0x2FA0BE83, 0x00000000, 35, // 43
// 0xBA2E8BA3, 0x00000000, 37, // 44
// 0x5B05B05B, 0x5B05B05B, 36, // 45
// 0xB21642C9, 0x00000000, 37, // 46
// 0xAE4C415D, 0x00000000, 37, // 47
// 0xAAAAAAAB, 0x00000000, 37, // 48
// 0x5397829D, 0x00000000, 36, // 49
// 0x51EB851F, 0x00000000, 36, // 50
// 0xA0A0A0A1, 0x00000000, 37, // 51
// 0x4EC4EC4F, 0x00000000, 36, // 52
// 0x9A90E7D9, 0x9A90E7D9, 37, // 53
// 0x97B425ED, 0x97B425ED, 37, // 54
// 0x94F2094F, 0x94F2094F, 37, // 55
// 0x49249249, 0x49249249, 36, // 56
// 0x47DC11F7, 0x47DC11F7, 36, // 57
// 0x8D3DCB09, 0x00000000, 37, // 58
// 0x22B63CBF, 0x00000000, 35, // 59
// 0x88888889, 0x00000000, 37, // 60
// 0x4325C53F, 0x00000000, 36, // 61
// 0x42108421, 0x42108421, 36, // 62
// 0x41041041, 0x41041041, 36, // 63
// 0x00000001, 0x00000000, 6, // 64
// 0xFC0FC0FD, 0x00000000, 38, // 65
// 0x3E0F83E1, 0x00000000, 36, // 66
// 0x07A44C6B, 0x00000000, 33, // 67
// 0xF0F0F0F1, 0x00000000, 38, // 68
// 0x76B981DB, 0x00000000, 37, // 69
// 0x75075075, 0x75075075, 37, // 70
// 0xE6C2B449, 0x00000000, 38, // 71
// 0x38E38E39, 0x00000000, 36, // 72
// 0x381C0E07, 0x381C0E07, 36, // 73
// 0x6EB3E453, 0x6EB3E453, 37, // 74
// 0x1B4E81B5, 0x00000000, 35, // 75
// 0xD79435E5, 0xD79435E5, 38, // 76
// 0x3531DEC1, 0x00000000, 36, // 77
// 0x69069069, 0x69069069, 37, // 78
// 0xCF6474A9, 0x00000000, 38, // 79
// 0xCCCCCCCD, 0x00000000, 38, // 80
// 0xCA4587E7, 0x00000000, 38, // 81
// 0xC7CE0C7D, 0x00000000, 38, // 82
// 0x3159721F, 0x00000000, 36, // 83
// 0xC30C30C3, 0xC30C30C3, 38, // 84
// 0xC0C0C0C1, 0x00000000, 38, // 85
// 0x2FA0BE83, 0x00000000, 36, // 86
// 0x2F149903, 0x00000000, 36, // 87
// 0xBA2E8BA3, 0x00000000, 38, // 88
// 0xB81702E1, 0x00000000, 38, // 89
// 0x5B05B05B, 0x5B05B05B, 37, // 90
// 0x2D02D02D, 0x2D02D02D, 36, // 91
// 0xB21642C9, 0x00000000, 38, // 92
// 0xB02C0B03, 0x00000000, 38, // 93
// 0xAE4C415D, 0x00000000, 38, // 94
// 0x2B1DA461, 0x2B1DA461, 36, // 95
// 0xAAAAAAAB, 0x00000000, 38, // 96
// 0xA8E83F57, 0xA8E83F57, 38, // 97
// 0x5397829D, 0x00000000, 37, // 98
// 0xA57EB503, 0x00000000, 38, // 99
// 0x51EB851F, 0x00000000, 37, // 100
// 0xA237C32B, 0xA237C32B, 38, // 101
// 0xA0A0A0A1, 0x00000000, 38, // 102
// 0x9F1165E7, 0x9F1165E7, 38, // 103
// 0x4EC4EC4F, 0x00000000, 37, // 104
// 0x27027027, 0x27027027, 36, // 105
// 0x9A90E7D9, 0x9A90E7D9, 38, // 106
// 0x991F1A51, 0x991F1A51, 38, // 107
// 0x97B425ED, 0x97B425ED, 38, // 108
// 0x2593F69B, 0x2593F69B, 36, // 109
// 0x94F2094F, 0x94F2094F, 38, // 110
// 0x24E6A171, 0x24E6A171, 36, // 111
// 0x49249249, 0x49249249, 37, // 112
// 0x90FDBC09, 0x90FDBC09, 38, // 113
// 0x47DC11F7, 0x47DC11F7, 37, // 114
// 0x8E78356D, 0x8E78356D, 38, // 115
// 0x8D3DCB09, 0x00000000, 38, // 116
// 0x23023023, 0x23023023, 36, // 117
// 0x22B63CBF, 0x00000000, 36, // 118
// 0x44D72045, 0x00000000, 37, // 119
// 0x88888889, 0x00000000, 38, // 120
// 0x8767AB5F, 0x8767AB5F, 38, // 121
// 0x4325C53F, 0x00000000, 37, // 122
// 0x85340853, 0x85340853, 38, // 123
// 0x42108421, 0x42108421, 37, // 124
// 0x10624DD3, 0x00000000, 35, // 125
// 0x41041041, 0x41041041, 37, // 126
// 0x10204081, 0x10204081, 35, // 127
// 0x00000001, 0x00000000, 7, // 128
// 0x0FE03F81, 0x00000000, 35, // 129
// 0xFC0FC0FD, 0x00000000, 39, // 130
// 0xFA232CF3, 0x00000000, 39, // 131
// 0x3E0F83E1, 0x00000000, 37, // 132
// 0xF6603D99, 0x00000000, 39, // 133
// 0x07A44C6B, 0x00000000, 34, // 134
// 0xF2B9D649, 0x00000000, 39, // 135
// 0xF0F0F0F1, 0x00000000, 39, // 136
// 0x077975B9, 0x00000000, 34, // 137
// 0x76B981DB, 0x00000000, 38, // 138
// 0x75DED953, 0x00000000, 38, // 139
// 0x75075075, 0x75075075, 38, // 140
// 0x3A196B1F, 0x00000000, 37, // 141
// 0xE6C2B449, 0x00000000, 39, // 142
// 0xE525982B, 0x00000000, 39, // 143
// 0x38E38E39, 0x00000000, 37, // 144
// 0xE1FC780F, 0x00000000, 39, // 145
// 0x381C0E07, 0x381C0E07, 37, // 146
// 0xDEE95C4D, 0x00000000, 39, // 147
// 0x6EB3E453, 0x6EB3E453, 38, // 148
// 0xDBEB61EF, 0x00000000, 39, // 149
// 0x1B4E81B5, 0x00000000, 36, // 150
// 0x36406C81, 0x00000000, 37, // 151
// 0xD79435E5, 0xD79435E5, 39, // 152
// 0xD62B80D7, 0x00000000, 39, // 153
// 0x3531DEC1, 0x00000000, 37, // 154
// 0xD3680D37, 0x00000000, 39, // 155
// 0x69069069, 0x69069069, 38, // 156
// 0x342DA7F3, 0x00000000, 37, // 157
// 0xCF6474A9, 0x00000000, 39, // 158
// 0xCE168A77, 0xCE168A77, 39, // 159
// 0xCCCCCCCD, 0x00000000, 39, // 160
// 0xCB8727C1, 0x00000000, 39, // 161
// 0xCA4587E7, 0x00000000, 39, // 162
// 0xC907DA4F, 0x00000000, 39, // 163
// 0xC7CE0C7D, 0x00000000, 39, // 164
// 0x634C0635, 0x00000000, 38, // 165
// 0x3159721F, 0x00000000, 37, // 166
// 0x621B97C3, 0x00000000, 38, // 167
// 0xC30C30C3, 0xC30C30C3, 39, // 168
// 0x60F25DEB, 0x00000000, 38, // 169
// 0xC0C0C0C1, 0x00000000, 39, // 170
// 0x17F405FD, 0x17F405FD, 36, // 171
// 0x2FA0BE83, 0x00000000, 37, // 172
// 0xBD691047, 0xBD691047, 39, // 173
// 0x2F149903, 0x00000000, 37, // 174
// 0x5D9F7391, 0x00000000, 38, // 175
// 0xBA2E8BA3, 0x00000000, 39, // 176
// 0x5C90A1FD, 0x5C90A1FD, 38, // 177
// 0xB81702E1, 0x00000000, 39, // 178
// 0x5B87DDAD, 0x5B87DDAD, 38, // 179
// 0x5B05B05B, 0x5B05B05B, 38, // 180
// 0xB509E68B, 0x00000000, 39, // 181
// 0x2D02D02D, 0x2D02D02D, 37, // 182
// 0xB30F6353, 0x00000000, 39, // 183
// 0xB21642C9, 0x00000000, 39, // 184
// 0x1623FA77, 0x1623FA77, 36, // 185
// 0xB02C0B03, 0x00000000, 39, // 186
// 0xAF3ADDC7, 0x00000000, 39, // 187
// 0xAE4C415D, 0x00000000, 39, // 188
// 0x15AC056B, 0x15AC056B, 36, // 189
// 0x2B1DA461, 0x2B1DA461, 37, // 190
// 0xAB8F69E3, 0x00000000, 39, // 191
// 0xAAAAAAAB, 0x00000000, 39, // 192
// 0x15390949, 0x00000000, 36, // 193
// 0xA8E83F57, 0xA8E83F57, 39, // 194
// 0x15015015, 0x15015015, 36, // 195
// 0x5397829D, 0x00000000, 38, // 196
// 0xA655C439, 0xA655C439, 39, // 197
// 0xA57EB503, 0x00000000, 39, // 198
// 0x5254E78F, 0x00000000, 38, // 199
// 0x51EB851F, 0x00000000, 38, // 200
// 0x028C1979, 0x00000000, 33, // 201
// 0xA237C32B, 0xA237C32B, 39, // 202
// 0xA16B312F, 0x00000000, 39, // 203
// 0xA0A0A0A1, 0x00000000, 39, // 204
// 0x4FEC04FF, 0x00000000, 38, // 205
// 0x9F1165E7, 0x9F1165E7, 39, // 206
// 0x27932B49, 0x00000000, 37, // 207
// 0x4EC4EC4F, 0x00000000, 38, // 208
// 0x9CC8E161, 0x00000000, 39, // 209
// 0x27027027, 0x27027027, 37, // 210
// 0x9B4C6F9F, 0x00000000, 39, // 211
// 0x9A90E7D9, 0x9A90E7D9, 39, // 212
// 0x99D722DB, 0x00000000, 39, // 213
// 0x991F1A51, 0x991F1A51, 39, // 214
// 0x4C346405, 0x00000000, 38, // 215
// 0x97B425ED, 0x97B425ED, 39, // 216
// 0x4B809701, 0x4B809701, 38, // 217
// 0x2593F69B, 0x2593F69B, 37, // 218
// 0x12B404AD, 0x12B404AD, 36, // 219
// 0x94F2094F, 0x94F2094F, 39, // 220
// 0x25116025, 0x25116025, 37, // 221
// 0x24E6A171, 0x24E6A171, 37, // 222
// 0x24BC44E1, 0x24BC44E1, 37, // 223
// 0x49249249, 0x49249249, 38, // 224
// 0x91A2B3C5, 0x00000000, 39, // 225
// 0x90FDBC09, 0x90FDBC09, 39, // 226
// 0x905A3863, 0x905A3863, 39, // 227
// 0x47DC11F7, 0x47DC11F7, 38, // 228
// 0x478BBCED, 0x00000000, 38, // 229
// 0x8E78356D, 0x8E78356D, 39, // 230
// 0x46ED2901, 0x46ED2901, 38, // 231
// 0x8D3DCB09, 0x00000000, 39, // 232
// 0x2328A701, 0x2328A701, 37, // 233
// 0x23023023, 0x23023023, 37, // 234
// 0x45B81A25, 0x45B81A25, 38, // 235
// 0x22B63CBF, 0x00000000, 37, // 236
// 0x08A42F87, 0x08A42F87, 35, // 237
// 0x44D72045, 0x00000000, 38, // 238
// 0x891AC73B, 0x00000000, 39, // 239
// 0x88888889, 0x00000000, 39, // 240
// 0x10FEF011, 0x00000000, 36, // 241
// 0x8767AB5F, 0x8767AB5F, 39, // 242
// 0x86D90545, 0x00000000, 39, // 243
// 0x4325C53F, 0x00000000, 38, // 244
// 0x85BF3761, 0x85BF3761, 39, // 245
// 0x85340853, 0x85340853, 39, // 246
// 0x10953F39, 0x10953F39, 36, // 247
// 0x42108421, 0x42108421, 38, // 248
// 0x41CC9829, 0x41CC9829, 38, // 249
// 0x10624DD3, 0x00000000, 36, // 250
// 0x828CBFBF, 0x00000000, 39, // 251
// 0x41041041, 0x41041041, 38, // 252
// 0x81848DA9, 0x00000000, 39, // 253
// 0x10204081, 0x10204081, 36, // 254
// 0x80808081, 0x00000000, 39 // 255
// };
// DEFINE_STANDARD_OP(Normal, OVER)
// DEFINE_STANDARD_OP(Multiply, MULTIPLY)
// DEFINE_STANDARD_OP(Additive, SATURATE)
// DEFINE_STANDARD_OP(ColorBurn, COLORBURN)
// DEFINE_STANDARD_OP(ColorDodge, COLORDODGE)
// DEFINE_STANDARD_OP(Reflect, REFLECT)
// DEFINE_STANDARD_OP(Glow, GLOW)
// DEFINE_STANDARD_OP(Overlay, OVERLAY)
// DEFINE_STANDARD_OP(Difference, DIFFERENCE)
// DEFINE_STANDARD_OP(Negation, NEGATION)
// DEFINE_STANDARD_OP(Lighten, MAX)
// DEFINE_STANDARD_OP(Darken, MIN)
// DEFINE_STANDARD_OP(Screen, SCREEN)
// DEFINE_STANDARD_OP(Xor, XOR)
// }
//}
| |
// Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
using gax = Google.Api.Gax;
using gagr = Google.Api.Gax.ResourceNames;
using gcbsv = Google.Cloud.BigQuery.Storage.V1;
using sys = System;
namespace Google.Cloud.BigQuery.Storage.V1
{
/// <summary>Resource name for the <c>Table</c> resource.</summary>
public sealed partial class TableName : gax::IResourceName, sys::IEquatable<TableName>
{
/// <summary>The possible contents of <see cref="TableName"/>.</summary>
public enum ResourceNameType
{
/// <summary>An unparsed resource name.</summary>
Unparsed = 0,
/// <summary>
/// A resource name with pattern <c>projects/{project}/datasets/{dataset}/tables/{table}</c>.
/// </summary>
ProjectDatasetTable = 1,
}
private static gax::PathTemplate s_projectDatasetTable = new gax::PathTemplate("projects/{project}/datasets/{dataset}/tables/{table}");
/// <summary>Creates a <see cref="TableName"/> containing an unparsed resource name.</summary>
/// <param name="unparsedResourceName">The unparsed resource name. Must not be <c>null</c>.</param>
/// <returns>
/// A new instance of <see cref="TableName"/> containing the provided <paramref name="unparsedResourceName"/>.
/// </returns>
public static TableName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) =>
new TableName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName)));
/// <summary>
/// Creates a <see cref="TableName"/> with the pattern <c>projects/{project}/datasets/{dataset}/tables/{table}</c>
/// .
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="datasetId">The <c>Dataset</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="tableId">The <c>Table</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>A new instance of <see cref="TableName"/> constructed from the provided ids.</returns>
public static TableName FromProjectDatasetTable(string projectId, string datasetId, string tableId) =>
new TableName(ResourceNameType.ProjectDatasetTable, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), datasetId: gax::GaxPreconditions.CheckNotNullOrEmpty(datasetId, nameof(datasetId)), tableId: gax::GaxPreconditions.CheckNotNullOrEmpty(tableId, nameof(tableId)));
/// <summary>
/// Formats the IDs into the string representation of this <see cref="TableName"/> with pattern
/// <c>projects/{project}/datasets/{dataset}/tables/{table}</c>.
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="datasetId">The <c>Dataset</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="tableId">The <c>Table</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="TableName"/> with pattern
/// <c>projects/{project}/datasets/{dataset}/tables/{table}</c>.
/// </returns>
public static string Format(string projectId, string datasetId, string tableId) =>
FormatProjectDatasetTable(projectId, datasetId, tableId);
/// <summary>
/// Formats the IDs into the string representation of this <see cref="TableName"/> with pattern
/// <c>projects/{project}/datasets/{dataset}/tables/{table}</c>.
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="datasetId">The <c>Dataset</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="tableId">The <c>Table</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="TableName"/> with pattern
/// <c>projects/{project}/datasets/{dataset}/tables/{table}</c>.
/// </returns>
public static string FormatProjectDatasetTable(string projectId, string datasetId, string tableId) =>
s_projectDatasetTable.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), gax::GaxPreconditions.CheckNotNullOrEmpty(datasetId, nameof(datasetId)), gax::GaxPreconditions.CheckNotNullOrEmpty(tableId, nameof(tableId)));
/// <summary>Parses the given resource name string into a new <see cref="TableName"/> instance.</summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item><description><c>projects/{project}/datasets/{dataset}/tables/{table}</c></description></item>
/// </list>
/// </remarks>
/// <param name="tableName">The resource name in string form. Must not be <c>null</c>.</param>
/// <returns>The parsed <see cref="TableName"/> if successful.</returns>
public static TableName Parse(string tableName) => Parse(tableName, false);
/// <summary>
/// Parses the given resource name string into a new <see cref="TableName"/> instance; optionally allowing an
/// unparseable resource name.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item><description><c>projects/{project}/datasets/{dataset}/tables/{table}</c></description></item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="tableName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="allowUnparsed">
/// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/>
/// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is
/// specified.
/// </param>
/// <returns>The parsed <see cref="TableName"/> if successful.</returns>
public static TableName Parse(string tableName, bool allowUnparsed) =>
TryParse(tableName, allowUnparsed, out TableName result) ? result : throw new sys::ArgumentException("The given resource-name matches no pattern.");
/// <summary>
/// Tries to parse the given resource name string into a new <see cref="TableName"/> instance.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item><description><c>projects/{project}/datasets/{dataset}/tables/{table}</c></description></item>
/// </list>
/// </remarks>
/// <param name="tableName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="result">
/// When this method returns, the parsed <see cref="TableName"/>, or <c>null</c> if parsing failed.
/// </param>
/// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns>
public static bool TryParse(string tableName, out TableName result) => TryParse(tableName, false, out result);
/// <summary>
/// Tries to parse the given resource name string into a new <see cref="TableName"/> instance; optionally
/// allowing an unparseable resource name.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item><description><c>projects/{project}/datasets/{dataset}/tables/{table}</c></description></item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="tableName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="allowUnparsed">
/// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/>
/// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is
/// specified.
/// </param>
/// <param name="result">
/// When this method returns, the parsed <see cref="TableName"/>, or <c>null</c> if parsing failed.
/// </param>
/// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns>
public static bool TryParse(string tableName, bool allowUnparsed, out TableName result)
{
gax::GaxPreconditions.CheckNotNull(tableName, nameof(tableName));
gax::TemplatedResourceName resourceName;
if (s_projectDatasetTable.TryParseName(tableName, out resourceName))
{
result = FromProjectDatasetTable(resourceName[0], resourceName[1], resourceName[2]);
return true;
}
if (allowUnparsed)
{
if (gax::UnparsedResourceName.TryParse(tableName, out gax::UnparsedResourceName unparsedResourceName))
{
result = FromUnparsed(unparsedResourceName);
return true;
}
}
result = null;
return false;
}
private TableName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string datasetId = null, string projectId = null, string tableId = null)
{
Type = type;
UnparsedResource = unparsedResourceName;
DatasetId = datasetId;
ProjectId = projectId;
TableId = tableId;
}
/// <summary>
/// Constructs a new instance of a <see cref="TableName"/> class from the component parts of pattern
/// <c>projects/{project}/datasets/{dataset}/tables/{table}</c>
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="datasetId">The <c>Dataset</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="tableId">The <c>Table</c> ID. Must not be <c>null</c> or empty.</param>
public TableName(string projectId, string datasetId, string tableId) : this(ResourceNameType.ProjectDatasetTable, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), datasetId: gax::GaxPreconditions.CheckNotNullOrEmpty(datasetId, nameof(datasetId)), tableId: gax::GaxPreconditions.CheckNotNullOrEmpty(tableId, nameof(tableId)))
{
}
/// <summary>The <see cref="ResourceNameType"/> of the contained resource name.</summary>
public ResourceNameType Type { get; }
/// <summary>
/// The contained <see cref="gax::UnparsedResourceName"/>. Only non-<c>null</c> if this instance contains an
/// unparsed resource name.
/// </summary>
public gax::UnparsedResourceName UnparsedResource { get; }
/// <summary>
/// The <c>Dataset</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string DatasetId { get; }
/// <summary>
/// The <c>Project</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string ProjectId { get; }
/// <summary>
/// The <c>Table</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string TableId { get; }
/// <summary>Whether this instance contains a resource name with a known pattern.</summary>
public bool IsKnownPattern => Type != ResourceNameType.Unparsed;
/// <summary>The string representation of the resource name.</summary>
/// <returns>The string representation of the resource name.</returns>
public override string ToString()
{
switch (Type)
{
case ResourceNameType.Unparsed: return UnparsedResource.ToString();
case ResourceNameType.ProjectDatasetTable: return s_projectDatasetTable.Expand(ProjectId, DatasetId, TableId);
default: throw new sys::InvalidOperationException("Unrecognized resource-type.");
}
}
/// <summary>Returns a hash code for this resource name.</summary>
public override int GetHashCode() => ToString().GetHashCode();
/// <inheritdoc/>
public override bool Equals(object obj) => Equals(obj as TableName);
/// <inheritdoc/>
public bool Equals(TableName other) => ToString() == other?.ToString();
/// <inheritdoc/>
public static bool operator ==(TableName a, TableName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false);
/// <inheritdoc/>
public static bool operator !=(TableName a, TableName b) => !(a == b);
}
public partial class CreateReadSessionRequest
{
/// <summary>
/// <see cref="gagr::ProjectName"/>-typed view over the <see cref="Parent"/> resource name property.
/// </summary>
public gagr::ProjectName ParentAsProjectName
{
get => string.IsNullOrEmpty(Parent) ? null : gagr::ProjectName.Parse(Parent, allowUnparsed: true);
set => Parent = value?.ToString() ?? "";
}
}
public partial class ReadRowsRequest
{
/// <summary>
/// <see cref="ReadStreamName"/>-typed view over the <see cref="ReadStream"/> resource name property.
/// </summary>
public ReadStreamName ReadStreamAsReadStreamName
{
get => string.IsNullOrEmpty(ReadStream) ? null : ReadStreamName.Parse(ReadStream, allowUnparsed: true);
set => ReadStream = value?.ToString() ?? "";
}
}
public partial class SplitReadStreamRequest
{
/// <summary>
/// <see cref="gcbsv::ReadStreamName"/>-typed view over the <see cref="Name"/> resource name property.
/// </summary>
public gcbsv::ReadStreamName ReadStreamName
{
get => string.IsNullOrEmpty(Name) ? null : gcbsv::ReadStreamName.Parse(Name, allowUnparsed: true);
set => Name = value?.ToString() ?? "";
}
}
public partial class CreateWriteStreamRequest
{
/// <summary><see cref="TableName"/>-typed view over the <see cref="Parent"/> resource name property.</summary>
public TableName ParentAsTableName
{
get => string.IsNullOrEmpty(Parent) ? null : TableName.Parse(Parent, allowUnparsed: true);
set => Parent = value?.ToString() ?? "";
}
}
public partial class AppendRowsRequest
{
/// <summary>
/// <see cref="WriteStreamName"/>-typed view over the <see cref="WriteStream"/> resource name property.
/// </summary>
public WriteStreamName WriteStreamAsWriteStreamName
{
get => string.IsNullOrEmpty(WriteStream) ? null : WriteStreamName.Parse(WriteStream, allowUnparsed: true);
set => WriteStream = value?.ToString() ?? "";
}
}
public partial class GetWriteStreamRequest
{
/// <summary>
/// <see cref="gcbsv::WriteStreamName"/>-typed view over the <see cref="Name"/> resource name property.
/// </summary>
public gcbsv::WriteStreamName WriteStreamName
{
get => string.IsNullOrEmpty(Name) ? null : gcbsv::WriteStreamName.Parse(Name, allowUnparsed: true);
set => Name = value?.ToString() ?? "";
}
}
public partial class FinalizeWriteStreamRequest
{
/// <summary>
/// <see cref="gcbsv::WriteStreamName"/>-typed view over the <see cref="Name"/> resource name property.
/// </summary>
public gcbsv::WriteStreamName WriteStreamName
{
get => string.IsNullOrEmpty(Name) ? null : gcbsv::WriteStreamName.Parse(Name, allowUnparsed: true);
set => Name = value?.ToString() ?? "";
}
}
public partial class FlushRowsRequest
{
/// <summary>
/// <see cref="WriteStreamName"/>-typed view over the <see cref="WriteStream"/> resource name property.
/// </summary>
public WriteStreamName WriteStreamAsWriteStreamName
{
get => string.IsNullOrEmpty(WriteStream) ? null : WriteStreamName.Parse(WriteStream, allowUnparsed: true);
set => WriteStream = value?.ToString() ?? "";
}
}
}
| |
using System;
using System.Drawing;
using System.Runtime.InteropServices;
using System.Windows.Forms;
namespace Dwm
{
#region Enumerations
/// <summary>
/// Rendering policies for the non client area of the window
/// </summary>
public enum NonClientRenderingPolicy
{
/// <summary>
/// Use default rendering
/// </summary>
UseWindowStyle,
/// <summary>
/// Disable rendering of the non client area
/// </summary>
Disabled,
/// <summary>
/// Enable rendering of the non client area
/// </summary>
Enabled
}
/// <summary>
/// Flip 3D policies
/// </summary>
public enum Flip3DPolicy
{
/// <summary>
/// Default behaviour
/// </summary>
Default,
/// <summary>
/// Excludes the window from Flip 3D, showing it below the other windows
/// </summary>
ExcludeBelow,
/// <summary>
/// Excludes the window from Flip 3D, showing it above the other windows
/// </summary>
ExcludeAbove
}
// Window attribute values that determine the attribute retrieved by DwmGetWindowAttribute
// or set by DwmSetWindowAttribute
internal enum WindowAttribute
{
NcRenderingEnabled = 1, // Non client rendering enabled
NcRenderingPolicy, // Non client rendering policy
TransitionsForceDisabled, // Transitions force disabled
AllowNcPaint, // Allow non client paint
CaptionButtonBounds, // Bounds of caption buttons
NonClientRtlLayout, // Non client right-to-left layout
ForceIconicRepresentation, // Force iconic representation instead of thumbnail
Flip3DPolicy, // Flip 3D policy
ExtendedFrameBounds // Bounds of extended frame
}
#endregion
/// <summary>
/// Provides methods do retrieve/modify the attributes of a form
/// </summary>
public class FormAttributes
{
// Form handle
private IntPtr hwndForm;
/// <summary>
/// Creates a new instance of FormAttributes from a given handle
/// </summary>
/// <param name="hwndForm">Handle of a form</param>
public FormAttributes(IntPtr hwndForm)
{
this.hwndForm = hwndForm;
}
/// <summary>
/// Creates a new instance of FormAttributes from a given form
/// </summary>
/// <param name="form">Form</param>
public FormAttributes(Form form)
: this(form.Handle)
{
}
// Gets a boolean value for the specified attribute
private bool GetBoolValue(WindowAttribute attribute)
{
// Stores the result
bool result;
// Native API call
DwmGetWindowAttribute(hwndForm, attribute, out result, sizeof(int));
return result;
}
// Sets a boolean value for the specified attribute
private void SetBoolValue(WindowAttribute attribute, ref bool value)
{
// Native API call
DwmSetWindowAttribute(hwndForm, attribute, ref value, sizeof(int));
}
// Sets an int value for the specified attribute
private void SetIntValue(WindowAttribute attribute, ref int value)
{
// Native API call
DwmSetWindowAttribute(hwndForm, attribute, ref value, sizeof(int));
}
// Gets a rectangle value for the given attribute
private Rectangle GetRectangleValue(WindowAttribute attribute)
{
// Stores the result
Rectangle result = new Rectangle();
// Native API call
DwmGetWindowAttribute(hwndForm, attribute, out result, Marshal.SizeOf(result));
return result;
}
/// <summary>
/// Gets a value indicating whether non client rendering is enabled
/// </summary>
public bool NonClientRendering
{
get
{
return GetBoolValue(WindowAttribute.NcRenderingEnabled);
}
}
/// <summary>
/// Sets the rendering policy of the non client area of the form
/// </summary>
/// <param name="policy">Non client rendering policy</param>
public void SetNonClientRenderingPolicy(NonClientRenderingPolicy policy)
{
int value = (int)policy;
SetIntValue(WindowAttribute.NcRenderingPolicy, ref value);
}
/// <summary>
/// Enables or disables force transitions for the form
/// </summary>
/// <param name="disable">True to disable transitions</param>
public void ForceDisableTransitions(bool disable)
{
SetBoolValue(WindowAttribute.TransitionsForceDisabled, ref disable);
}
/// <summary>
/// Enables or disables painting of the non client area or the form
/// </summary>
/// <param name="allow">True to allow painting of the non client area</param>
public void SetNonClientPaint(bool allow)
{
SetBoolValue(WindowAttribute.AllowNcPaint, ref allow);
}
/// <summary>
/// Enables or disables right-to-left layout for the non client area of the form
/// </summary>
/// <param name="rtl">True to activate right-to-left layout</param>
public void SetNonClientRtlLayout(bool rtl)
{
SetBoolValue(WindowAttribute.NonClientRtlLayout, ref rtl);
}
/// <summary>
/// Enables or disables iconic representation of the form in thumbnails
/// </summary>
/// <param name="force">True to force iconic representation</param>
public void ForceIconicRepresentation(bool force)
{
SetBoolValue(WindowAttribute.ForceIconicRepresentation, ref force);
}
/// <summary>
/// Sets the Flip 3D policy of the form
/// </summary>
/// <param name="policy">Flip 3D policy to apply</param>
public void SetFlip3DPolicy(Flip3DPolicy policy)
{
int value = (int)policy;
SetIntValue(WindowAttribute.Flip3DPolicy, ref value);
}
/// <summary>
/// Gets the bounds of the caption buttons
/// </summary>
/// <returns>Rectangle structure containing the bounds of the caption buttons</returns>
public Rectangle GetCaptionButtonBounds()
{
return GetRectangleValue(WindowAttribute.CaptionButtonBounds);
}
/// <summary>
/// Gets the bounds of the extended frame
/// </summary>
/// <returns>Rectangle structure containing the bounds of the extended frame</returns>
public Rectangle GetExtendedFrameBounds()
{
return GetRectangleValue(WindowAttribute.ExtendedFrameBounds);
}
#region API imports
[DllImport("dwmapi.dll", PreserveSig = false)]
private static extern void DwmGetWindowAttribute(IntPtr hwnd, WindowAttribute attribute, out bool attributeValue, int attributeSize);
[DllImport("dwmapi.dll", PreserveSig = false)]
private static extern void DwmGetWindowAttribute(IntPtr hwnd, WindowAttribute attribute, out Rectangle attributeValue, int attributeSize);
[DllImport("dwmapi.dll", PreserveSig = false)]
private static extern void DwmSetWindowAttribute(IntPtr hwnd, WindowAttribute attribute, ref bool attributeValue, int attributeSize);
[DllImport("dwmapi.dll", PreserveSig = false)]
private static extern void DwmSetWindowAttribute(IntPtr hwnd, WindowAttribute attribute, ref int attributeValue, int attributeSize);
#endregion
}
}
| |
using System;
using Csla;
using Csla.Data;
using DalEf;
using Csla.Serialization;
using System.ComponentModel.DataAnnotations;
using BusinessObjects.Properties;
using System.Linq;
using Csla.Security;
namespace BusinessObjects.MDSubjects
{
[Serializable]
public partial class cMDSubjects_Employee: cMDSubjects_Subject<cMDSubjects_Employee>
{
#region Business Methods
private static readonly PropertyInfo<bool?> isAdminProperty = RegisterProperty<bool?>(p => p.IsAdmin, string.Empty, (bool?)null);
public bool? IsAdmin
{
get { return GetProperty(isAdminProperty); }
set { SetProperty(isAdminProperty, value); }
}
private static readonly PropertyInfo<System.String> firstNameProperty = RegisterProperty<System.String>(p => p.FirstName, string.Empty);
[System.ComponentModel.DataAnnotations.StringLength(50, ErrorMessageResourceName = "ErrorMessageMaxLength", ErrorMessageResourceType = typeof(Resources))]
[Required(ErrorMessageResourceName = "ErrorMessageRequired", ErrorMessageResourceType = typeof(Resources))]
public System.String FirstName
{
get { return GetProperty(firstNameProperty); }
set { SetProperty(firstNameProperty, (value ?? "").Trim()); }
}
private static readonly PropertyInfo<System.String> lastNameProperty = RegisterProperty<System.String>(p => p.LastName, string.Empty);
[System.ComponentModel.DataAnnotations.StringLength(50, ErrorMessageResourceName = "ErrorMessageMaxLength", ErrorMessageResourceType = typeof(Resources))]
[Required(ErrorMessageResourceName = "ErrorMessageRequired", ErrorMessageResourceType = typeof(Resources))]
public System.String LastName
{
get { return GetProperty(lastNameProperty); }
set { SetProperty(lastNameProperty, (value ?? "").Trim()); }
}
private static readonly PropertyInfo<System.String> homePhoneProperty = RegisterProperty<System.String>(p => p.HomePhone, string.Empty, (System.String)null);
public System.String HomePhone
{
get { return GetProperty(homePhoneProperty); }
set { SetProperty(homePhoneProperty, (value ?? "").Trim()); }
}
private static readonly PropertyInfo<System.String> mobileProperty = RegisterProperty<System.String>(p => p.Mobile, string.Empty, (System.String)null);
public System.String Mobile
{
get { return GetProperty(mobileProperty); }
set { SetProperty(mobileProperty, (value ?? "").Trim()); }
}
private static readonly PropertyInfo<System.Int32?> mDPlaces_Enums_OgranizationalUnitIdProperty = RegisterProperty<System.Int32?>(p => p.MDPlaces_Enums_OgranizationalUnitId, string.Empty, (System.Int32?)null);
public System.Int32? MDPlaces_Enums_OgranizationalUnitId
{
get { return GetProperty(mDPlaces_Enums_OgranizationalUnitIdProperty); }
set { SetProperty(mDPlaces_Enums_OgranizationalUnitIdProperty, value); }
}
private static readonly PropertyInfo<System.Int32?> mDSubjects_Enums_FunctionIdProperty = RegisterProperty<System.Int32?>(p => p.MDSubjects_Enums_FunctionId, string.Empty, (System.Int32?)null);
public System.Int32? MDSubjects_Enums_FunctionId
{
get { return GetProperty(mDSubjects_Enums_FunctionIdProperty); }
set { SetProperty(mDSubjects_Enums_FunctionIdProperty, value); }
}
private static readonly PropertyInfo<System.Int32?> mDSubjects_Enums_EducationDegreeIdProperty = RegisterProperty<System.Int32?>(p => p.MDSubjects_Enums_EducationDegreeId, string.Empty, (System.Int32?)null);
public System.Int32? MDSubjects_Enums_EducationDegreeId
{
get { return GetProperty(mDSubjects_Enums_EducationDegreeIdProperty); }
set { SetProperty(mDSubjects_Enums_EducationDegreeIdProperty, value); }
}
private static readonly PropertyInfo<System.Decimal?> billingRatePerHourProperty = RegisterProperty<System.Decimal?>(p => p.BillingRatePerHour, string.Empty, (System.Decimal?)null);
public System.Decimal? BillingRatePerHour
{
get { return GetProperty(billingRatePerHourProperty); }
set { SetProperty(billingRatePerHourProperty, value); }
}
private static readonly PropertyInfo<System.String> userNameProperty = RegisterProperty<System.String>(p => p.UserName, string.Empty);
[System.ComponentModel.DataAnnotations.StringLength(50, ErrorMessageResourceName = "ErrorMessageMaxLength", ErrorMessageResourceType = typeof(Resources))]
//[Required(ErrorMessageResourceName = "ErrorMessageRequired", ErrorMessageResourceType = typeof(Resources))]
public System.String UserName
{
get { return GetProperty(userNameProperty); }
set { SetProperty(userNameProperty, (value ?? "").Trim()); }
}
private static readonly PropertyInfo<System.String> passwordProperty = RegisterProperty<System.String>(p => p.Password, string.Empty);
[System.ComponentModel.DataAnnotations.StringLength(50, ErrorMessageResourceName = "ErrorMessageMaxLength", ErrorMessageResourceType = typeof(Resources))]
//[Required(ErrorMessageResourceName = "ErrorMessageRequired", ErrorMessageResourceType = typeof(Resources))]
public System.String Password
{
get { return GetProperty(passwordProperty); }
set { SetProperty(passwordProperty, (value ?? "").Trim()); }
}
private static readonly PropertyInfo<bool?> incomingInvoiceProperty = RegisterProperty<bool?>(p => p.IncomingInvoice, string.Empty, (bool?)null);
public bool? IncomingInvoice
{
get { return GetProperty(incomingInvoiceProperty); }
set { SetProperty(incomingInvoiceProperty, value); }
}
private static readonly PropertyInfo<bool?> invoiceProperty = RegisterProperty<bool?>(p => p.Invoice, string.Empty, (bool?)null);
public bool? Invoice
{
get { return GetProperty(invoiceProperty); }
set { SetProperty(invoiceProperty, value); }
}
private static readonly PropertyInfo<bool?> offerProperty = RegisterProperty<bool?>(p => p.Offer, string.Empty, (bool?)null);
public bool? Offer
{
get { return GetProperty(offerProperty); }
set { SetProperty(offerProperty, value); }
}
private static readonly PropertyInfo<bool?> quoteProperty = RegisterProperty<bool?>(p => p.Quote, string.Empty, (bool?)null);
public bool? Quote
{
get { return GetProperty(quoteProperty); }
set { SetProperty(quoteProperty, value); }
}
private static readonly PropertyInfo<bool?> travelOrderProperty = RegisterProperty<bool?>(p => p.TravelOrder, string.Empty, (bool?)null);
public bool? TravelOrder
{
get { return GetProperty(travelOrderProperty); }
set { SetProperty(travelOrderProperty, value); }
}
private static readonly PropertyInfo<bool?> workOrderProperty = RegisterProperty<bool?>(p => p.WorkOrder, string.Empty, (bool?)null);
public bool? WorkOrder
{
get { return GetProperty(workOrderProperty); }
set { SetProperty(workOrderProperty, value); }
}
private static readonly PropertyInfo<bool?> priceListProperty = RegisterProperty<bool?>(p => p.PriceList, string.Empty, (bool?)null);
public bool? PriceList
{
get { return GetProperty(priceListProperty); }
set { SetProperty(priceListProperty, value); }
}
private static readonly PropertyInfo<bool?> paymentProperty = RegisterProperty<bool?>(p => p.Payment, string.Empty, (bool?)null);
public bool? Payment
{
get { return GetProperty(paymentProperty); }
set { SetProperty(paymentProperty, value); }
}
private static readonly PropertyInfo<bool?> firstPageProperty = RegisterProperty<bool?>(p => p.FirstPage, string.Empty, (bool?)true);
public bool? FirstPage
{
get { return GetProperty(firstPageProperty); }
set { SetProperty(firstPageProperty, value); }
}
// dodano zbog fiskalizacije
private static readonly PropertyInfo<System.String> CashierCodeProperty = RegisterProperty<System.String>(p => p.CashierCode, string.Empty);
[System.ComponentModel.DataAnnotations.StringLength(11, ErrorMessageResourceName = "ErrorMessageMaxLength", ErrorMessageResourceType = typeof(Resources))]
//[Required(ErrorMessageResourceName = "ErrorMessageRequired", ErrorMessageResourceType = typeof(Resources))]
public System.String CashierCode
{
get { return GetProperty(CashierCodeProperty); }
set { SetProperty(CashierCodeProperty, (value ?? "").Trim()); }
}
private static readonly PropertyInfo<bool?> fiscalModeProperty = RegisterProperty<bool?>(p => p.FiscalMode, string.Empty, (bool?)null);
public bool? FiscalMode
{
get { return GetProperty(fiscalModeProperty); }
set { SetProperty(fiscalModeProperty, value); }
}
#endregion
#region Factory Methods
public static cMDSubjects_Employee NewMDSubjects_Employee()
{
return DataPortal.Create<cMDSubjects_Employee>();
}
public static cMDSubjects_Employee GetMDSubjects_Employee(int uniqueId)
{
return DataPortal.Fetch<cMDSubjects_Employee>(new SingleCriteria<cMDSubjects_Employee, int>(uniqueId));
}
public static cMDSubjects_Employee GetMDSubjects_Employee(string username)
{
return DataPortal.Fetch<cMDSubjects_Employee>(new SingleCriteria<cMDSubjects_Employee, string>(username));
}
public static cMDSubjects_Employee GetMDSubjects_Employee(UsernameCriteria criteria)
{
return DataPortal.Fetch<cMDSubjects_Employee>(criteria);
}
internal static cMDSubjects_Employee GetMDSubjects_Employee(MDSubjects_Employee data)
{
return DataPortal.Fetch<cMDSubjects_Employee>(data);
}
public static void DeleteMDSubjects_Employee(int uniqueId)
{
DataPortal.Delete<cMDSubjects_Employee>(new SingleCriteria<cMDSubjects_Employee, int>(uniqueId));
}
#endregion
#region Data Access
[RunLocal]
protected override void DataPortal_Create()
{
BusinessRules.CheckRules();
}
private void DataPortal_Fetch(UsernameCriteria criteria)
{
using (var ctx = ObjectContextManager<MDSubjectsEntities>.GetManager("MDSubjectsEntities"))
{
var data = ctx.ObjectContext.MDSubjects_Subject.OfType<MDSubjects_Employee>().First(p => p.UserName == criteria.Username && p.Password == criteria.Password);
Fetch(data);
BusinessRules.CheckRules();
}
}
private void DataPortal_Fetch(SingleCriteria<cMDSubjects_Employee, string> criteria)
{
using (var ctx = ObjectContextManager<MDSubjectsEntities>.GetManager("MDSubjectsEntities"))
{
var data = ctx.ObjectContext.MDSubjects_Subject.OfType<MDSubjects_Employee>().First(p => p.UserName == criteria.Value);
Fetch(data);
LoadProperty<cMDSubjects_Subject_AccountsCol>(MDSubjects_Subject_AccountsColProperty, cMDSubjects_Subject_AccountsCol.GetcMDSubjects_Subject_AccountsCol(data.MDSubjects_Subject_AccountsCol));
LoadProperty<cMDSubjects_Subject_ContactsCol>(MDSubjects_Subject_ContactsColProperty, cMDSubjects_Subject_ContactsCol.GetcMDSubjects_Subject_ContactsCol(data.MDSubjects_Subject_ContactsCol));
LoadProperty<cMDSubjects_Subject_PermissionsForClientsCol>(MDSubjects_Subject_PermissionsForClientsColProperty, cMDSubjects_Subject_PermissionsForClientsCol.GetcMDSubjects_Subject_PermissionsForClientsCol(data.MDSubjects_Subject_PermissionsForClientsCol));
BusinessRules.CheckRules();
}
}
private void DataPortal_Fetch(SingleCriteria<cMDSubjects_Employee, int> criteria)
{
using (var ctx = ObjectContextManager<MDSubjectsEntities>.GetManager("MDSubjectsEntities"))
{
var data = ctx.ObjectContext.MDSubjects_Subject.OfType<MDSubjects_Employee>().First(p => p.Id == criteria.Value);
Fetch(data);
LoadProperty<cMDSubjects_Subject_AccountsCol>(MDSubjects_Subject_AccountsColProperty, cMDSubjects_Subject_AccountsCol.GetcMDSubjects_Subject_AccountsCol(data.MDSubjects_Subject_AccountsCol));
LoadProperty<cMDSubjects_Subject_ContactsCol>(MDSubjects_Subject_ContactsColProperty, cMDSubjects_Subject_ContactsCol.GetcMDSubjects_Subject_ContactsCol(data.MDSubjects_Subject_ContactsCol));
LoadProperty<cMDSubjects_Subject_PermissionsForClientsCol>(MDSubjects_Subject_PermissionsForClientsColProperty, cMDSubjects_Subject_PermissionsForClientsCol.GetcMDSubjects_Subject_PermissionsForClientsCol(data.MDSubjects_Subject_PermissionsForClientsCol));
BusinessRules.CheckRules();
}
}
private void Fetch(MDSubjects_Employee data)
{
LoadProperty<int>(IdProperty, data.Id);
LoadProperty<byte[]>(EntityKeyDataProperty, Serialize(data.EntityKey));
LoadProperty<int>(companyUsingServiceIdProperty, data.CompanyUsingServiceId);
LoadProperty<Guid>(GUIDProperty, data.GUID);
LoadProperty<short>(subjectTypeProperty, data.SubjectType);
LoadProperty<string>(nameProperty, data.Name);
LoadProperty<string>(longNameProperty, data.LongName);
LoadProperty<bool>(residentProperty, data.Resident);
LoadProperty<bool?>(isCustomerProperty, data.IsCustomer);
LoadProperty<bool?>(isContractorProperty, data.IsContractor);
LoadProperty<bool>(inactiveProperty, data.Inactive);
LoadProperty<DateTime>(lastActivityDateProperty, data.LastActivityDate);
LoadProperty<int>(employeeWhoLastChanedItIdProperty, data.EmployeeWhoLastChanedItId);
LoadProperty<int?>(homeAddress_PlaceIdProperty, data.HomeAddress_PlaceId);
LoadProperty<string>(homeAddress_StreetProperty, data.HomeAddress_Street);
LoadProperty<string>(homeAddress_NumberProperty, data.HomeAddress_Number);
LoadProperty<string>(homeAddress_DescriptionProperty, data.HomeAddress_Description);
LoadProperty<string>(oIBProperty, data.OIB);
LoadProperty<bool?>(isAdminProperty, data.IsAdmin);
LoadProperty<string>(firstNameProperty, data.FirstName);
LoadProperty<string>(lastNameProperty, data.LastName);
LoadProperty<string>(homePhoneProperty, data.HomePhone);
LoadProperty<string>(mobileProperty, data.Mobile);
LoadProperty<int?>(mDPlaces_Enums_OgranizationalUnitIdProperty, data.MDPlaces_Enums_OgranizationalUnitId);
LoadProperty<int?>(mDSubjects_Enums_FunctionIdProperty, data.MDSubjects_Enums_FunctionId);
LoadProperty<int?>(mDSubjects_Enums_EducationDegreeIdProperty, data.MDSubjects_Enums_EducationDegreeId);
LoadProperty<decimal?>(billingRatePerHourProperty, data.BillingRatePerHour);
LoadProperty<string>(userNameProperty, data.UserName);
LoadProperty<string>(passwordProperty, data.Password);
LoadProperty<bool?>(incomingInvoiceProperty, data.IncomingInvoice);
LoadProperty<bool?>(invoiceProperty, data.Invoice);
LoadProperty<bool?>(offerProperty, data.Offer);
LoadProperty<bool?>(quoteProperty, data.Quote);
LoadProperty<bool?>(travelOrderProperty, data.TravelOrder);
LoadProperty<bool?>(workOrderProperty, data.WorkOrder);
LoadProperty<bool?>(priceListProperty, data.PriceList);
LoadProperty<bool?>(paymentProperty, data.Payment);
LoadProperty<bool?>(firstPageProperty, data.FirstPage);
LoadProperty<string>(CashierCodeProperty, data.CashierCode);
LoadProperty<bool?>(fiscalModeProperty, data.FiscalMode);
LastChanged = data.LastChanged;
}
[Transactional(TransactionalTypes.TransactionScope)]
protected override void DataPortal_Insert()
{
using (var ctx = ObjectContextManager<MDSubjectsEntities>.GetManager("MDSubjectsEntities"))
{
var data = new MDSubjects_Employee();
data.CompanyUsingServiceId = ReadProperty<int>(companyUsingServiceIdProperty);
data.GUID = ReadProperty<Guid>(GUIDProperty);
data.SubjectType = (short)Common.SubjectType.Employee;
data.Name = ReadProperty<string>(nameProperty);
data.LongName = ReadProperty<string>(longNameProperty);
data.Resident = ReadProperty<bool>(residentProperty);
data.IsCustomer = ReadProperty<bool?>(isCustomerProperty);
data.IsContractor = ReadProperty<bool?>(isContractorProperty);
data.Inactive = ReadProperty<bool>(inactiveProperty);
data.LastActivityDate = ReadProperty<DateTime>(lastActivityDateProperty);
data.EmployeeWhoLastChanedItId = ReadProperty<int>(employeeWhoLastChanedItIdProperty);
data.HomeAddress_PlaceId = ReadProperty<int?>(homeAddress_PlaceIdProperty);
data.HomeAddress_Street = ReadProperty<string>(homeAddress_StreetProperty);
data.HomeAddress_Number = ReadProperty<string>(homeAddress_NumberProperty);
data.HomeAddress_Description = ReadProperty<string>(homeAddress_DescriptionProperty);
data.OIB = ReadProperty<string>(oIBProperty);
data.IsAdmin = ReadProperty<bool?>(isAdminProperty);
data.FirstName = ReadProperty<string>(firstNameProperty);
data.LastName = ReadProperty<string>(lastNameProperty);
data.HomePhone = ReadProperty<string>(homePhoneProperty);
data.Mobile = ReadProperty<string>(mobileProperty);
data.MDPlaces_Enums_OgranizationalUnitId = ReadProperty<int?>(mDPlaces_Enums_OgranizationalUnitIdProperty);
data.MDSubjects_Enums_FunctionId = ReadProperty<int?>(mDSubjects_Enums_FunctionIdProperty);
data.MDSubjects_Enums_EducationDegreeId = ReadProperty<int?>(mDSubjects_Enums_EducationDegreeIdProperty);
data.BillingRatePerHour = ReadProperty<decimal?>(billingRatePerHourProperty);
data.UserName = ReadProperty<string>(userNameProperty);
data.Password = ReadProperty<string>(passwordProperty);
data.IncomingInvoice = ReadProperty<bool?>(incomingInvoiceProperty);
data.Invoice = ReadProperty<bool?>(invoiceProperty);
data.Offer = ReadProperty<bool?>(offerProperty);
data.Quote = ReadProperty<bool?>(quoteProperty);
data.TravelOrder = ReadProperty<bool?>(travelOrderProperty);
data.WorkOrder = ReadProperty<bool?>(workOrderProperty);
data.PriceList = ReadProperty<bool?>(priceListProperty);
data.Payment = ReadProperty<bool?>(paymentProperty);
data.FirstPage = ReadProperty<bool?>(firstPageProperty);
data.CashierCode= ReadProperty<string>(CashierCodeProperty);
data.FiscalMode= ReadProperty<bool?>(fiscalModeProperty);
ctx.ObjectContext.AddToMDSubjects_Subject(data);
DataPortal.UpdateChild(ReadProperty<cMDSubjects_Subject_AccountsCol>(MDSubjects_Subject_AccountsColProperty), data);
DataPortal.UpdateChild(ReadProperty<cMDSubjects_Subject_ContactsCol>(MDSubjects_Subject_ContactsColProperty), data);
DataPortal.UpdateChild(ReadProperty<cMDSubjects_Subject_PermissionsForClientsCol>(MDSubjects_Subject_PermissionsForClientsColProperty), data);
ctx.ObjectContext.SaveChanges();
//Get New id
int newId = data.Id;
//Load New Id into object
LoadProperty(IdProperty, newId);
//Load New EntityKey into Object
LoadProperty(EntityKeyDataProperty, Serialize(data.EntityKey));
}
}
[Transactional(TransactionalTypes.TransactionScope)]
protected override void DataPortal_Update()
{
using (var ctx = ObjectContextManager<MDSubjectsEntities>.GetManager("MDSubjectsEntities"))
{
var data = new MDSubjects_Employee();
data.Id = ReadProperty<int>(IdProperty);
data.EntityKey = Deserialize(ReadProperty(EntityKeyDataProperty)) as System.Data.EntityKey;
ctx.ObjectContext.Attach(data);
data.CompanyUsingServiceId = ReadProperty<int>(companyUsingServiceIdProperty);
data.GUID = ReadProperty<Guid>(GUIDProperty);
data.SubjectType = ReadProperty<short>(subjectTypeProperty);
data.Name = ReadProperty<string>(nameProperty);
data.LongName = ReadProperty<string>(longNameProperty);
data.Resident = ReadProperty<bool>(residentProperty);
data.IsCustomer = ReadProperty<bool?>(isCustomerProperty);
data.IsContractor = ReadProperty<bool?>(isContractorProperty);
data.Inactive = ReadProperty<bool>(inactiveProperty);
data.LastActivityDate = ReadProperty<DateTime>(lastActivityDateProperty);
data.EmployeeWhoLastChanedItId = ReadProperty<int>(employeeWhoLastChanedItIdProperty);
data.HomeAddress_PlaceId = ReadProperty<int?>(homeAddress_PlaceIdProperty);
data.HomeAddress_Street = ReadProperty<string>(homeAddress_StreetProperty);
data.HomeAddress_Number = ReadProperty<string>(homeAddress_NumberProperty);
data.HomeAddress_Description = ReadProperty<string>(homeAddress_DescriptionProperty);
data.OIB = ReadProperty<string>(oIBProperty);
data.IsAdmin = ReadProperty<bool?>(isAdminProperty);
data.FirstName = ReadProperty<string>(firstNameProperty);
data.LastName = ReadProperty<string>(lastNameProperty);
data.HomePhone = ReadProperty<string>(homePhoneProperty);
data.Mobile = ReadProperty<string>(mobileProperty);
data.MDPlaces_Enums_OgranizationalUnitId = ReadProperty<int?>(mDPlaces_Enums_OgranizationalUnitIdProperty);
data.MDSubjects_Enums_FunctionId = ReadProperty<int?>(mDSubjects_Enums_FunctionIdProperty);
data.MDSubjects_Enums_EducationDegreeId = ReadProperty<int?>(mDSubjects_Enums_EducationDegreeIdProperty);
data.BillingRatePerHour = ReadProperty<decimal?>(billingRatePerHourProperty);
data.UserName = ReadProperty<string>(userNameProperty);
data.Password = ReadProperty<string>(passwordProperty);
data.IncomingInvoice = ReadProperty<bool?>(incomingInvoiceProperty);
data.Invoice = ReadProperty<bool?>(invoiceProperty);
data.Offer = ReadProperty<bool?>(offerProperty);
data.Quote = ReadProperty<bool?>(quoteProperty);
data.TravelOrder = ReadProperty<bool?>(travelOrderProperty);
data.WorkOrder = ReadProperty<bool?>(workOrderProperty);
data.PriceList = ReadProperty<bool?>(priceListProperty);
data.Payment = ReadProperty<bool?>(paymentProperty);
data.FirstPage = ReadProperty<bool?>(firstPageProperty);
data.CashierCode = ReadProperty<string>(CashierCodeProperty);
data.FiscalMode = ReadProperty<bool?>(fiscalModeProperty);
DataPortal.UpdateChild(ReadProperty<cMDSubjects_Subject_AccountsCol>(MDSubjects_Subject_AccountsColProperty), data);
DataPortal.UpdateChild(ReadProperty<cMDSubjects_Subject_ContactsCol>(MDSubjects_Subject_ContactsColProperty), data);
DataPortal.UpdateChild(ReadProperty<cMDSubjects_Subject_PermissionsForClientsCol>(MDSubjects_Subject_PermissionsForClientsColProperty), data);
ctx.ObjectContext.SaveChanges();
}
}
[Transactional(TransactionalTypes.TransactionScope)]
private void DataPortal_Delete(SingleCriteria<cMDSubjects_Employee, int> criteria)
{
using (var ctx = ObjectContextManager<MDSubjectsEntities>.GetManager("MDSubjectsEntities"))
{
var data = ctx.ObjectContext.MDSubjects_Subject.OfType<MDSubjects_Employee>().First(p => p.Id == criteria.Value);
ctx.ObjectContext.MDSubjects_Subject.DeleteObject(data);
ctx.ObjectContext.SaveChanges();
}
}
#endregion
}
}
| |
//------------------------------------------------------------------------------
//
// <copyright file="VisualProxy.cs" company="Microsoft">
// Copyright (C) Microsoft Corporation. All rights reserved.
// </copyright>
//
// Description:
// Mapping between a visual and its handles on different channels.
//
//------------------------------------------------------------------------------
namespace System.Windows.Media.Composition
{
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Windows;
using System.Windows.Media;
/// <summary>
/// Mapping between a visual and its handles on different channels.
/// </summary>
internal struct VisualProxy
{
// --------------------------------------------------------------------
//
// Private Types
//
// --------------------------------------------------------------------
#region Private Types
/// <summary>
/// Tuple binding a channel to a set of flags and a resource handle.
/// </summary>
/// <remarks>
/// Note that DUCE.Channel is a reference type.
/// </remarks>
private struct Proxy
{
internal DUCE.Channel Channel;
internal VisualProxyFlags Flags;
internal DUCE.ResourceHandle Handle;
}
#endregion Private Types
// --------------------------------------------------------------------
//
// Internal Properties
//
// --------------------------------------------------------------------
#region Internal Properties
/// <summary>
/// Returns the number of channels this resource is marshaled to.
/// </summary>
internal int Count
{
get
{
if (_tail == null)
{
return _head.Channel == null ? 0 : 1;
}
else
{
//
// The logic here is simple: we keep at most one entry
// in the tail free. Heads has to be occupied and adds one.
//
int tailLength = _tail.Length;
bool lastTailIsEmpty =
_tail[tailLength - 1].Channel == null;
return 1 + tailLength - (lastTailIsEmpty ? 1 : 0);
}
}
}
/// <summary>
/// Returns true if the parent resource is marshaled to at least
/// one channel.
/// </summary>
internal bool IsOnAnyChannel
{
get
{
return Count != 0;
}
}
#endregion Internal Properties
// --------------------------------------------------------------------
//
// Internal Methods
//
// --------------------------------------------------------------------
#region Internal Methods
/// <summary>
/// Returns true if the visual is marshaled to the
/// specified channel.
/// </summary>
internal bool IsOnChannel(DUCE.Channel channel)
{
int index = Find(channel);
if (index == PROXY_NOT_FOUND)
{
return false;
}
else if (index == PROXY_STORED_INLINE)
{
return !_head.Handle.IsNull;
}
else
{
return !_tail[index].Handle.IsNull;
}
}
/// <summary>
/// If the visual is on channel, its reference count is increased.
/// Otherwise, a new resource is created on that channel.
/// </summary>
internal bool CreateOrAddRefOnChannel(
object instance,
DUCE.Channel channel,
DUCE.ResourceType resourceType)
{
int index = Find(channel);
int count = Count;
if (index == PROXY_NOT_FOUND)
{
//
// This is the case where we have to create a new resource.
//
if (_head.Channel == null)
{
//
// We're adding the first proxy.
//
// Before: [empty]
// After insert: [ head]
//
Debug.Assert(count == 0);
_head.Channel = channel;
_head.Flags = VisualProxyFlags.None;
channel.CreateOrAddRefOnChannel(
instance,
ref _head.Handle,
resourceType);
}
else
{
if (_tail == null)
{
//
// We're adding the second proxy.
//
// Before: [head]
// After resize: [head] [ empty] [empty]
// After insert: [head] [tail 0] [empty]
// ----------------
Debug.Assert(count == 1);
_tail = new Proxy[2];
}
else if (count > _tail.Length)
{
//
// Increase the tail size by 2.
//
// Before: [head] [tail 0] ... [tail c-2]
// After resize: [head] [tail 0] ... [tail c-2] [ empty] [empty]
// After insert: [head] [tail 0] ... [tail c-3] [tail c-2] [empty]
// ------------------------------------------
//
ResizeTail(2);
}
//
// Now that we have a tail, fill in the first free element.
//
Proxy proxy;
proxy.Channel = channel;
proxy.Flags = VisualProxyFlags.None;
proxy.Handle = DUCE.ResourceHandle.Null;
channel.CreateOrAddRefOnChannel(
instance,
ref proxy.Handle,
resourceType);
_tail[count - 1] = proxy;
}
return /* created */ true;
}
else if (index == PROXY_STORED_INLINE)
{
//
// We simply need to increase the reference count on head...
//
channel.CreateOrAddRefOnChannel(
instance,
ref _head.Handle,
resourceType);
}
else
{
//
// Increase the reference count on one of the tail proxies...
//
channel.CreateOrAddRefOnChannel(
instance,
ref _tail[index].Handle,
resourceType);
}
return /* not created */ false;
}
/// <summary>
/// If visual is on channel, its reference count is increased.
/// Otherwise, a new resource is created on that channel.
/// </summary>
internal bool ReleaseOnChannel(DUCE.Channel channel)
{
int index = Find(channel);
bool proxyRemoved = false;
int count = Count;
if (index == PROXY_STORED_INLINE)
{
if (channel.ReleaseOnChannel(_head.Handle))
{
//
// Need to move the last of the non-empty tail to head
// or clear the head. Erase the head if that was the last
// proxy.
//
if (count == 1)
{
_head = new Proxy();
}
else
{
_head = _tail[count - 2];
}
proxyRemoved = true;
}
}
else if (index >= 0)
{
if (channel.ReleaseOnChannel(_tail[index].Handle))
{
//
// Need to move the last of the non-empty tail to the
// removed index. Avoid in-place copying.
//
if (index != count - 2)
{
_tail[index] = _tail[count - 2];
}
proxyRemoved = true;
}
}
else
{
Debug.Assert(index != PROXY_NOT_FOUND);
return false;
}
if (proxyRemoved)
{
if (_tail != null)
{
//
// Keep the tail short. We allow for one extra free element
// in tail to avoid constant allocations / reallocations.
//
if (count == 2)
{
// ------------------
// Before removal: [head] [tail c-1] [empty]
// Here and now: [head] [ deleted] [empty]
// After removal: [head]
//
_tail = null;
}
else if (count == _tail.Length)
{
// ---------------------------------------------------
// Before removal: [head] [tail 0] [tail 1] ... [tail c-3] [tail c-2] [empty]
// Here and now: [head] [tail 0] [tail 1] ... [tail c-3] [ deleted] [empty]
// After removal: [head] [tail 0] [tail 1] ... [tail c-3]
//
ResizeTail(-2);
}
else
{
// ------------------------------------------------------
// Before removal: [head] [tail 0] [tail 1] ... [tail c-4] [tail c-3] [tail c-2]
// Here and now: [head] [tail 0] [tail 1] ... [tail c-4] [tail c-3] [ deleted]
// After removal: [head] [tail 0] [tail 1] ... [tail c-4] [tail c-3] [ empty]
//
_tail[count - 2] = new Proxy();
}
}
}
return proxyRemoved;
}
/// <summary>
/// Returns the channel that the n-th proxy connects to.
/// </summary>
internal DUCE.Channel GetChannel(int index)
{
Debug.Assert(index >= 0 && index < Count);
if (index < Count)
{
if (index == 0)
{
return _head.Channel;
}
else if (index > 0)
{
return _tail[index - 1].Channel;
}
}
return null;
}
#endregion Internal Methods
// ----------------------------------------------------------------
//
// Internal Methods: resource handle getters
//
// ----------------------------------------------------------------
#region Internal Methods: resource handle getters
/// <summary>
/// Returns the handle the visual has on a specific channel.
/// </summary>
internal DUCE.ResourceHandle GetHandle(DUCE.Channel channel)
{
return GetHandle(Find(channel) + 1); // Find's results are -1 based, adjust by one.
}
/// <summary>
/// Returns the handle the visual has on the n-th channel.
/// </summary>
internal DUCE.ResourceHandle GetHandle(int index)
{
Debug.Assert(index >= 0 && index < Count);
if (index < Count)
{
if (index == 0)
{
return _head.Handle;
}
else if (index > 0)
{
return _tail[index - 1].Handle;
}
}
return DUCE.ResourceHandle.Null;
}
#endregion Internal Methods: resource handle getters
// ----------------------------------------------------------------
//
// Internal Methods: visual proxy flags
//
// ----------------------------------------------------------------
#region Internal Methods: visual proxy flags
/// <summary>
/// Returns the flags the visual has on a specific channel.
/// </summary>
internal VisualProxyFlags GetFlags(DUCE.Channel channel)
{
return GetFlags(Find(channel) + 1); // Find's results are -1 based, adjust by one.
}
/// <summary>
/// Returns the handle the visual has on n-th channel.
/// </summary>
internal VisualProxyFlags GetFlags(int index)
{
if (index < Count)
{
if (index == 0)
{
return _head.Flags;
}
else if (index > 0)
{
return _tail[index - 1].Flags;
}
}
return VisualProxyFlags.None;
}
/// <summary>
/// Sets the flags the visual has on a specific channel.
/// </summary>
internal void SetFlags(
DUCE.Channel channel,
bool value,
VisualProxyFlags flags)
{
SetFlags(Find(channel) + 1, value, flags); // Find's results are -1 based, adjust by one.
}
/// <summary>
/// Sets the flags the visual has on the n-th channel.
/// </summary>
internal void SetFlags(
int index,
bool value,
VisualProxyFlags flags)
{
Debug.Assert(index >= 0 && index < Count);
if (index < Count)
{
if (index == 0)
{
_head.Flags =
value ? (_head.Flags | flags) : (_head.Flags & ~flags);
}
else if (index > 0)
{
_tail[index - 1].Flags =
value ? (_tail[index - 1].Flags | flags) : (_tail[index - 1].Flags & ~flags);
}
}
}
/// <summary>
/// Sets the flags on all channels the visual is marshaled to.
/// </summary>
internal void SetFlagsOnAllChannels(
bool value,
VisualProxyFlags flags)
{
if (_head.Channel != null)
{
_head.Flags =
value ? (_head.Flags | flags) : (_head.Flags & ~flags);
for (int i = 0, limit = Count - 1; i < limit; i++)
{
_tail[i].Flags =
value ? (_tail[i].Flags | flags) : (_tail[i].Flags & ~flags);
}
}
}
/// <summary>
/// Returns true if the given flags are set for every proxy or if
/// the visual is not being marshaled.
/// </summary>
internal bool CheckFlagsOnAllChannels(
VisualProxyFlags conjunctionFlags)
{
if (_head.Channel != null)
{
if ((_head.Flags & conjunctionFlags) != conjunctionFlags)
return false;
for (int i = 0, limit = Count - 1; i < limit; i++)
{
if ((_tail[i].Flags & conjunctionFlags) != conjunctionFlags)
return false;
}
}
return true;
}
#endregion Internal Methods: visual proxy flags
// --------------------------------------------------------------------
//
// Private Methods
//
// --------------------------------------------------------------------
#region Private Methods
/// <summary>
/// Looks for the given channel in the proxies list.
/// </summary>
private int Find(DUCE.Channel channel)
{
if (_head.Channel == channel)
{
return PROXY_STORED_INLINE;
}
else if (_tail != null)
{
for (int i = 0, limit = Count - 1; i < limit; i++)
{
if (_tail[i].Channel == channel)
{
return i;
}
}
}
return PROXY_NOT_FOUND;
}
/// <summary>
/// Grows or shrinks the tail by a given size.
/// </summary>
private void ResizeTail(int delta)
{
int newLength = _tail.Length + delta;
Debug.Assert(delta % 2 == 0 && newLength >= 2);
Proxy[] reallocatedTail = new Proxy[newLength];
Array.Copy(_tail, reallocatedTail, Math.Min(_tail.Length, newLength));
_tail = reallocatedTail;
}
#endregion Private Methods
// --------------------------------------------------------------------
//
// Private Fields
//
// --------------------------------------------------------------------
#region Private Fields
/// <summary>
/// Returned by the Find method to denote that a proxy for the given
/// channel has not been found.
/// </summary>
private const int PROXY_NOT_FOUND = -2;
/// <summary>
/// Returned by the Find method to denote that a proxy for the given
/// channel has been found in the inline storage.
/// </summary>
private const int PROXY_STORED_INLINE = -1;
/// <summary>
/// This data structure is optimized for single entry. _head is
/// the one entry that we inline into the struct for that purpose.
/// </summary>
private Proxy _head;
/// <summary>
/// All the other entries end up in this array.
/// </summary>
private Proxy[] _tail;
#endregion Private Fields
}
}
| |
// NpgsqlTypes.NpgsqlTypesHelper.cs
//
// Author:
// Glen Parker <[email protected]>
//
// Copyright (C) 2004 The Npgsql Development Team
// [email protected]
// http://gborg.postgresql.org/project/npgsql/projdisplay.php
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
// This file provides data type converters between PostgreSQL representations
// and .NET objects.
using System;
using System.Collections;
using System.Globalization;
using System.Text;
using System.IO;
using System.Text.RegularExpressions;
using Npgsql;
namespace NpgsqlTypes
{
/// <summary>
/// Provide event handlers to convert all native supported basic data types from their backend
/// text representation to a .NET object.
/// </summary>
internal abstract class BasicBackendToNativeTypeConverter
{
private static readonly String[] DateFormats = new String[]
{
"yyyy-MM-dd",
};
private static readonly String[] TimeFormats = new String[]
{
"HH:mm:ss.ffffff",
"HH:mm:ss.fffff",
"HH:mm:ss.ffff",
"HH:mm:ss.fff",
"HH:mm:ss.ff",
"HH:mm:ss.f",
"HH:mm:ss",
"HH:mm:ss.ffffffzz",
"HH:mm:ss.fffffzz",
"HH:mm:ss.ffffzz",
"HH:mm:ss.fffzz",
"HH:mm:ss.ffzz",
"HH:mm:ss.fzz",
"HH:mm:sszz"
};
private static readonly String[] DateTimeFormats = new String[]
{
"yyyy-MM-dd HH:mm:ss.ffffff",
"yyyy-MM-dd HH:mm:ss.fffff",
"yyyy-MM-dd HH:mm:ss.ffff",
"yyyy-MM-dd HH:mm:ss.fff",
"yyyy-MM-dd HH:mm:ss.ff",
"yyyy-MM-dd HH:mm:ss.f",
"yyyy-MM-dd HH:mm:ss",
"yyyy-MM-dd HH:mm:ss.ffffffzz",
"yyyy-MM-dd HH:mm:ss.fffffzz",
"yyyy-MM-dd HH:mm:ss.ffffzz",
"yyyy-MM-dd HH:mm:ss.fffzz",
"yyyy-MM-dd HH:mm:ss.ffzz",
"yyyy-MM-dd HH:mm:ss.fzz",
"yyyy-MM-dd HH:mm:sszz"
};
/// <summary>
/// Binary data.
/// </summary>
internal static Object ToBinary(NpgsqlBackendTypeInfo TypeInfo, String BackendData, Int16 TypeSize, Int32 TypeModifier)
{
Int32 octalValue = 0;
Int32 byteAPosition = 0;
Int32 byteAStringLength = BackendData.Length;
MemoryStream ms = new MemoryStream();
while (byteAPosition < byteAStringLength)
{
// The IsDigit is necessary in case we receive a \ as the octal value and not
// as the indicator of a following octal value in decimal format.
// i.e.: \201\301P\A
if (BackendData[byteAPosition] == '\\') {
if (byteAPosition + 1 == byteAStringLength)
{
octalValue = '\\';
byteAPosition++;
}
else if (Char.IsDigit(BackendData[byteAPosition + 1]))
{
octalValue = (Byte.Parse(BackendData[byteAPosition + 1].ToString()) << 6);
octalValue |= (Byte.Parse(BackendData[byteAPosition + 2].ToString()) << 3);
octalValue |= Byte.Parse(BackendData[byteAPosition + 3].ToString());
byteAPosition += 4;
}
else
{
octalValue = '\\';
byteAPosition += 2;
}
} else {
octalValue = (Byte)BackendData[byteAPosition];
byteAPosition++;
}
ms.WriteByte((Byte)octalValue);
}
return ms.ToArray();
}
/// <summary>
/// Convert a postgresql boolean to a System.Boolean.
/// </summary>
internal static Object ToBoolean(NpgsqlBackendTypeInfo TypeInfo, String BackendData, Int16 TypeSize, Int32 TypeModifier)
{
return (BackendData.ToLower() == "t" ? true : false);
}
/// <summary>
/// Convert a postgresql datetime to a System.DateTime.
/// </summary>
internal static Object ToDateTime(NpgsqlBackendTypeInfo TypeInfo, String BackendData, Int16 TypeSize, Int32 TypeModifier)
{
// Get the date time parsed in all expected formats for timestamp.
return DateTime.ParseExact(BackendData,
DateTimeFormats,
DateTimeFormatInfo.InvariantInfo,
DateTimeStyles.NoCurrentDateDefault | DateTimeStyles.AllowWhiteSpaces);
}
/// <summary>
/// Convert a postgresql date to a System.DateTime.
/// </summary>
internal static Object ToDate(NpgsqlBackendTypeInfo TypeInfo, String BackendData, Int16 TypeSize, Int32 TypeModifier)
{
return DateTime.ParseExact(BackendData,
DateFormats,
DateTimeFormatInfo.InvariantInfo,
DateTimeStyles.AllowWhiteSpaces);
}
/// <summary>
/// Convert a postgresql time to a System.DateTime.
/// </summary>
internal static Object ToTime(NpgsqlBackendTypeInfo TypeInfo, String BackendData, Int16 TypeSize, Int32 TypeModifier)
{
return DateTime.ParseExact(BackendData,
TimeFormats,
DateTimeFormatInfo.InvariantInfo,
DateTimeStyles.NoCurrentDateDefault | DateTimeStyles.AllowWhiteSpaces);
}
/// <summary>
/// Convert a postgresql money to a System.Decimal.
/// </summary>
internal static Object ToMoney(NpgsqlBackendTypeInfo TypeInfo, String BackendData, Int16 TypeSize, Int32 TypeModifier)
{
// It's a number with a $ on the beginning...
return Convert.ToDecimal(BackendData.Substring(1, BackendData.Length - 1), CultureInfo.InvariantCulture);
}
}
/// <summary>
/// Provide event handlers to convert the basic native supported data types from
/// native form to backend representation.
/// </summary>
internal abstract class BasicNativeToBackendTypeConverter
{
/// <summary>
/// Binary data.
/// </summary>
internal static String ToBinary(NpgsqlNativeTypeInfo TypeInfo, Object NativeData)
{
Byte[] byteArray = (Byte[])NativeData;
int len = byteArray.Length;
char[] res = new char[len * 5];
for (int i = 0, o = 0; i < len; ++i, o += 5)
{
byte item = byteArray[i];
res[o] = res[o + 1] = '\\';
res[o + 2] = (char)('0' + (7 & (item >> 6)));
res[o + 3] = (char)('0' + (7 & (item >> 3)));
res[o + 4] = (char)('0' + (7 & item));
}
return new String(res);
}
/// <summary>
/// Convert to a postgresql boolean.
/// </summary>
internal static String ToBoolean(NpgsqlNativeTypeInfo TypeInfo, Object NativeData)
{
return ((bool)NativeData) ? "TRUE" : "FALSE";
}
/// <summary>
/// Convert to a postgresql timestamp.
/// </summary>
internal static String ToDateTime(NpgsqlNativeTypeInfo TypeInfo, Object NativeData)
{
return ((DateTime)NativeData).ToString("yyyy-MM-dd HH:mm:ss.ffffff", DateTimeFormatInfo.InvariantInfo);
}
/// <summary>
/// Convert to a postgresql date.
/// </summary>
internal static String ToDate(NpgsqlNativeTypeInfo TypeInfo, Object NativeData)
{
return ((DateTime)NativeData).ToString("yyyy-MM-dd", DateTimeFormatInfo.InvariantInfo);
}
/// <summary>
/// Convert to a postgresql time.
/// </summary>
internal static String ToTime(NpgsqlNativeTypeInfo TypeInfo, Object NativeData)
{
return ((DateTime)NativeData).ToString("HH:mm:ss.ffffff", DateTimeFormatInfo.InvariantInfo);
}
/// <summary>
/// Convert to a postgres money.
/// </summary>
internal static String ToMoney(NpgsqlNativeTypeInfo TypeInfo, Object NativeData)
{
return "$" + ((Decimal)NativeData).ToString(DateTimeFormatInfo.InvariantInfo);
}
}
/// <summary>
/// Provide event handlers to convert extended native supported data types from their backend
/// text representation to a .NET object.
/// </summary>
internal abstract class ExtendedBackendToNativeTypeConverter
{
private static readonly Regex pointRegex = new Regex(@"\((-?\d+.?\d*),(-?\d+.?\d*)\)");
private static readonly Regex boxlsegRegex = new Regex(@"\((-?\d+.?\d*),(-?\d+.?\d*)\),\((-?\d+.?\d*),(-?\d+.?\d*)\)");
private static readonly Regex pathpolygonRegex = new Regex(@"\((-?\d+.?\d*),(-?\d+.?\d*)\)");
private static readonly Regex circleRegex = new Regex(@"<\((-?\d+.?\d*),(-?\d+.?\d*)\),(\d+.?\d*)>");
/// <summary>
/// Convert a postgresql point to a System.NpgsqlPoint.
/// </summary>
internal static Object ToPoint(NpgsqlBackendTypeInfo TypeInfo, String BackendData, Int16 TypeSize, Int32 TypeModifier)
{
Match m = pointRegex.Match(BackendData);
return new NpgsqlPoint(Single.Parse(m.Groups[1].ToString()), Single.Parse(m.Groups[2].ToString()));
}
/// <summary>
/// Convert a postgresql point to a System.RectangleF.
/// </summary>
internal static Object ToBox(NpgsqlBackendTypeInfo TypeInfo, String BackendData, Int16 TypeSize, Int32 TypeModifier)
{
Match m = boxlsegRegex.Match(BackendData);
return new NpgsqlBox(new NpgsqlPoint(Single.Parse(m.Groups[1].ToString()), Single.Parse(m.Groups[2].ToString())),
new NpgsqlPoint(Single.Parse(m.Groups[3].ToString()), Single.Parse(m.Groups[4].ToString())));
}
/// <summary>
/// LDeg.
/// </summary>
internal static Object ToLSeg(NpgsqlBackendTypeInfo TypeInfo, String BackendData, Int16 TypeSize, Int32 TypeModifier)
{
Match m = boxlsegRegex.Match(BackendData);
return new NpgsqlLSeg(new NpgsqlPoint(Single.Parse(m.Groups[1].ToString()), Single.Parse(m.Groups[2].ToString())),
new NpgsqlPoint(Single.Parse(m.Groups[3].ToString()), Single.Parse(m.Groups[4].ToString())));
}
/// <summary>
/// Path.
/// </summary>
internal static Object ToPath(NpgsqlBackendTypeInfo TypeInfo, String BackendData, Int16 TypeSize, Int32 TypeModifier)
{
Match m = pathpolygonRegex.Match(BackendData);
Boolean open = (BackendData[0] == '[');
ArrayList points = new ArrayList();
while (m.Success)
{
if (open)
points.Add(new NpgsqlPoint(Single.Parse(m.Groups[1].ToString()), Single.Parse(m.Groups[2].ToString())));
else
{
// Here we have to do a little hack, because as of 2004-08-11 mono cvs version, the last group is returned with
// a trailling ')' only when the last character of the string is a ')' which is the case for closed paths
// returned by backend. This gives parsing exception when converting to single.
// I still don't know if this is a bug in mono or in my regular expression.
// Check if there is this character and remove it.
String group2 = m.Groups[2].ToString();
if (group2.EndsWith(")"))
group2 = group2.Remove(group2.Length - 1, 1);
points.Add(new NpgsqlPoint(Single.Parse(m.Groups[1].ToString()), Single.Parse(group2)));
}
m = m.NextMatch();
}
NpgsqlPath result = new NpgsqlPath((NpgsqlPoint[]) points.ToArray(typeof(NpgsqlPoint)));
result.IsOpen = open;
return result;
}
/// <summary>
/// Polygon.
/// </summary>
internal static Object ToPolygon(NpgsqlBackendTypeInfo TypeInfo, String BackendData, Int16 TypeSize, Int32 TypeModifier)
{
Match m = pathpolygonRegex.Match(BackendData);
ArrayList points = new ArrayList();
while (m.Success)
{
// Here we have to do a little hack, because as of 2004-08-11 mono cvs version, the last group is returned with
// a trailling ')' only when the last character of the string is a ')' which is the case for closed paths
// returned by backend. This gives parsing exception when converting to single.
// I still don't know if this is a bug in mono or in my regular expression.
// Check if there is this character and remove it.
String group2 = m.Groups[2].ToString();
if (group2.EndsWith(")"))
group2 = group2.Remove(group2.Length - 1, 1);
points.Add(new NpgsqlPoint(Single.Parse(m.Groups[1].ToString()), Single.Parse(group2)));
m = m.NextMatch();
}
return new NpgsqlPolygon((NpgsqlPoint[]) points.ToArray(typeof(NpgsqlPoint)));
}
/// <summary>
/// Circle.
/// </summary>
internal static Object ToCircle(NpgsqlBackendTypeInfo TypeInfo, String BackendData, Int16 TypeSize, Int32 TypeModifier)
{
Match m = circleRegex.Match(BackendData);
return new NpgsqlCircle(new NpgsqlPoint(Single.Parse(m.Groups[1].ToString()), Single.Parse(m.Groups[2].ToString())), Single.Parse(m.Groups[3].ToString()));
}
}
/// <summary>
/// Provide event handlers to convert extended native supported data types from
/// native form to backend representation.
/// </summary>
internal abstract class ExtendedNativeToBackendTypeConverter
{
/// <summary>
/// Point.
/// </summary>
internal static String ToPoint(NpgsqlNativeTypeInfo TypeInfo, Object NativeData)
{
if (NativeData is NpgsqlPoint)
{
NpgsqlPoint P = (NpgsqlPoint)NativeData;
return String.Format(CultureInfo.InvariantCulture, "({0},{1})", P.X, P.Y);
}
else
{
throw new InvalidCastException("Unable to cast data to NpgsqlPoint type");
}
}
/// <summary>
/// Box.
/// </summary>
internal static String ToBox(NpgsqlNativeTypeInfo TypeInfo, Object NativeData)
{
/*if (NativeData.GetType() == typeof(Rectangle)) {
Rectangle R = (Rectangle)NativeData;
return String.Format(CultureInfo.InvariantCulture, "({0},{1}),({2},{3})", R.Left, R.Top, R.Left + R.Width, R.Top + R.Height);
} else if (NativeData.GetType() == typeof(RectangleF)) {
RectangleF R = (RectangleF)NativeData;
return String.Format(CultureInfo.InvariantCulture, "({0},{1}),({2},{3})", R.Left, R.Top, R.Left + R.Width, R.Top + R.Height);*/
if (NativeData is NpgsqlBox)
{
NpgsqlBox box = (NpgsqlBox) NativeData;
return String.Format(CultureInfo.InvariantCulture, "({0},{1}),({2},{3})", box.LowerLeft.X, box.LowerLeft.Y, box.UpperRight.X, box.UpperRight.Y);
} else {
throw new InvalidCastException("Unable to cast data to Rectangle type");
}
}
/// <summary>
/// LSeg.
/// </summary>
internal static String ToLSeg(NpgsqlNativeTypeInfo TypeInfo, Object NativeData)
{
NpgsqlLSeg S = (NpgsqlLSeg)NativeData;
return String.Format(CultureInfo.InvariantCulture, "{0},{1},{2},{3}", S.Start.X, S.Start.Y, S.End.X, S.End.Y);
}
/// <summary>
/// Open path.
/// </summary>
internal static String ToPath(NpgsqlNativeTypeInfo TypeInfo, Object NativeData)
{
StringBuilder B = new StringBuilder();
foreach (NpgsqlPoint P in ((NpgsqlPath)NativeData).Points) {
B.AppendFormat(CultureInfo.InvariantCulture, "{0}({1},{2})", (B.Length > 0 ? "," : ""), P.X, P.Y);
}
return String.Format("[{0}]", B.ToString());
}
/// <summary>
/// Polygon.
/// </summary>
internal static String ToPolygon(NpgsqlNativeTypeInfo TypeInfo, Object NativeData)
{
StringBuilder B = new StringBuilder();
foreach (NpgsqlPoint P in ((NpgsqlPolygon)NativeData).Points) {
B.AppendFormat(CultureInfo.InvariantCulture, "{0}({1},{2})", (B.Length > 0 ? "," : ""), P.X, P.Y);
}
return String.Format("({0})", B.ToString());
}
/// <summary>
/// Circle.
/// </summary>
internal static String ToCircle(NpgsqlNativeTypeInfo TypeInfo, Object NativeData)
{
NpgsqlCircle C = (NpgsqlCircle)NativeData;
return String.Format(CultureInfo.InvariantCulture, "{0},{1},{2}", C.Center.X, C.Center.Y, C.Radius);
}
}
}
| |
using System;
using System.Collections;
using System.Text;
using System.Collections.Generic;
using System.Runtime.Serialization;
namespace DDay.iCal
{
/// <summary>
/// Represents a unique component, a component with a unique UID,
/// which can be used to uniquely identify the component.
/// </summary>
#if !SILVERLIGHT
[Serializable]
#endif
public class UniqueComponent :
CalendarComponent,
IUniqueComponent
{
// TODO: Add AddRelationship() public method.
// This method will add the UID of a related component
// to the Related_To property, along with any "RELTYPE"
// parameter ("PARENT", "CHILD", "SIBLING", or other)
// TODO: Add RemoveRelationship() public method.
#region Constructors
public UniqueComponent()
{
Initialize();
EnsureProperties();
}
public UniqueComponent(string name) : base(name)
{
Initialize();
EnsureProperties();
}
private void EnsureProperties()
{
if (string.IsNullOrEmpty(UID))
{
// Create a new UID for the component
UID = new UIDFactory().Build();
}
// NOTE: removed setting the 'CREATED' property here since it breaks serialization.
// See https://sourceforge.net/projects/dday-ical/forums/forum/656447/topic/3754354
if (DTStamp == null)
{
// Here, we don't simply set to DateTime.Now because DateTime.Now contains milliseconds, and
// the iCalendar standard doesn't care at all about milliseconds. Therefore, when comparing
// two calendars, one generated, and one loaded from file, they may be functionally identical,
// but be determined to be different due to millisecond differences.
DateTime now = DateTime.Now;
DTStamp = new iCalDateTime(now.Year, now.Month, now.Day, now.Hour, now.Minute, now.Second);
}
}
private void Initialize()
{
Properties.ItemAdded += new EventHandler<ObjectEventArgs<ICalendarProperty>>(Properties_ItemAdded);
Properties.ItemRemoved += new EventHandler<ObjectEventArgs<ICalendarProperty>>(Properties_ItemRemoved);
}
#endregion
#region Public Properties
virtual public IList<IAttendee> Attendees
{
get { return Properties.GetList<IAttendee>("ATTENDEE"); }
set { Properties.SetList("ATTENDEE", value); }
}
virtual public IList<string> Comments
{
get { return Properties.GetList<string>("COMMENT"); }
set { Properties.SetList("COMMENT", value); }
}
virtual public IDateTime DTStamp
{
get { return Properties.Get<IDateTime>("DTSTAMP"); }
set { Properties.Set("DTSTAMP", value); }
}
virtual public IOrganizer Organizer
{
get { return Properties.Get<IOrganizer>("ORGANIZER"); }
set { Properties.Set("ORGANIZER", value); }
}
virtual public IList<IRequestStatus> RequestStatuses
{
get { return Properties.GetList<IRequestStatus>("REQUEST-STATUS"); }
set { Properties.SetList("REQUEST-STATUS", value); }
}
virtual public Uri Url
{
get { return Properties.Get<Uri>("URL"); }
set { Properties.Set("URL", value); }
}
#endregion
#region Protected Methods
protected void OnUIDChanged(string oldUID, string newUID)
{
if (UIDChanged != null)
UIDChanged(this, oldUID, newUID);
}
#endregion
#region Event Handlers
void Properties_ItemRemoved(object sender, ObjectEventArgs<ICalendarProperty> e)
{
if (e.Object != null &&
e.Object.Name != null &&
string.Equals(e.Object.Name.ToUpper(), "UID"))
{
OnUIDChanged(e.Object.Value != null ? e.Object.Value.ToString() : null, null);
e.Object.ValueChanged -= new EventHandler<ValueChangedEventArgs>(UID_ValueChanged);
}
}
void Properties_ItemAdded(object sender, ObjectEventArgs<ICalendarProperty> e)
{
if (e.Object != null &&
e.Object.Name != null &&
string.Equals(e.Object.Name.ToUpper(), "UID"))
{
OnUIDChanged(null, e.Object.Value != null ? e.Object.Value.ToString() : null);
e.Object.ValueChanged += new EventHandler<ValueChangedEventArgs>(UID_ValueChanged);
}
}
void UID_ValueChanged(object sender, ValueChangedEventArgs e)
{
OnUIDChanged(
e.OldValue != null ? e.OldValue.ToString() : null,
e.NewValue != null ? e.NewValue.ToString() : null
);
}
#endregion
#region Overrides
protected override void OnDeserializing(StreamingContext context)
{
base.OnDeserializing(context);
Initialize();
}
protected override void OnDeserialized(StreamingContext context)
{
base.OnDeserialized(context);
EnsureProperties();
}
public override bool Equals(object obj)
{
if (obj is RecurringComponent &&
obj != this)
{
RecurringComponent r = (RecurringComponent)obj;
if (UID != null)
return UID.Equals(r.UID);
else return UID == r.UID;
}
return base.Equals(obj);
}
public override int GetHashCode()
{
if (UID != null)
return UID.GetHashCode();
return base.GetHashCode();
}
#endregion
#region IUniqueComponent Members
[field: NonSerialized]
public event UIDChangedEventHandler UIDChanged;
virtual public string UID
{
get { return Properties.Get<string>("UID"); }
set { Properties.Set("UID", value); }
}
#endregion
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
namespace System.Drawing.Imaging
{
using System.Runtime.InteropServices;
// sdkinc\imaging.h
/// <include file='doc\ImageCodecInfo.uex' path='docs/doc[@for="ImageCodecInfo"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public sealed class ImageCodecInfo
{
private Guid _clsid;
private Guid _formatID;
private string _codecName;
private string _dllName;
private string _formatDescription;
private string _filenameExtension;
private string _mimeType;
private ImageCodecFlags _flags;
private int _version;
private byte[][] _signaturePatterns;
private byte[][] _signatureMasks;
internal ImageCodecInfo()
{
}
/// <include file='doc\ImageCodecInfo.uex' path='docs/doc[@for="ImageCodecInfo.Clsid"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public Guid Clsid
{
get { return _clsid; }
set { _clsid = value; }
}
/// <include file='doc\ImageCodecInfo.uex' path='docs/doc[@for="ImageCodecInfo.FormatID"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public Guid FormatID
{
get { return _formatID; }
set { _formatID = value; }
}
/// <include file='doc\ImageCodecInfo.uex' path='docs/doc[@for="ImageCodecInfo.CodecName"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public string CodecName
{
get { return _codecName; }
set { _codecName = value; }
}
/// <include file='doc\ImageCodecInfo.uex' path='docs/doc[@for="ImageCodecInfo.DllName"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public string DllName
{
get
{
return _dllName;
}
set
{
_dllName = value;
}
}
/// <include file='doc\ImageCodecInfo.uex' path='docs/doc[@for="ImageCodecInfo.FormatDescription"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public string FormatDescription
{
get { return _formatDescription; }
set { _formatDescription = value; }
}
/// <include file='doc\ImageCodecInfo.uex' path='docs/doc[@for="ImageCodecInfo.FilenameExtension"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public string FilenameExtension
{
get { return _filenameExtension; }
set { _filenameExtension = value; }
}
/// <include file='doc\ImageCodecInfo.uex' path='docs/doc[@for="ImageCodecInfo.MimeType"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public string MimeType
{
get { return _mimeType; }
set { _mimeType = value; }
}
/// <include file='doc\ImageCodecInfo.uex' path='docs/doc[@for="ImageCodecInfo.Flags"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public ImageCodecFlags Flags
{
get { return _flags; }
set { _flags = value; }
}
/// <include file='doc\ImageCodecInfo.uex' path='docs/doc[@for="ImageCodecInfo.Version"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public int Version
{
get { return _version; }
set { _version = value; }
}
/// <include file='doc\ImageCodecInfo.uex' path='docs/doc[@for="ImageCodecInfo.SignaturePatterns"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
[CLSCompliant(false)]
public byte[][] SignaturePatterns
{
get { return _signaturePatterns; }
set { _signaturePatterns = value; }
}
/// <include file='doc\ImageCodecInfo.uex' path='docs/doc[@for="ImageCodecInfo.SignatureMasks"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
[CLSCompliant(false)]
public byte[][] SignatureMasks
{
get { return _signatureMasks; }
set { _signatureMasks = value; }
}
// Encoder/Decoder selection APIs
/// <include file='doc\ImageCodecInfo.uex' path='docs/doc[@for="ImageCodecInfo.GetImageDecoders"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public static ImageCodecInfo[] GetImageDecoders()
{
ImageCodecInfo[] imageCodecs;
int numDecoders;
int size;
int status = SafeNativeMethods.Gdip.GdipGetImageDecodersSize(out numDecoders, out size);
if (status != SafeNativeMethods.Gdip.Ok)
{
throw SafeNativeMethods.Gdip.StatusException(status);
}
IntPtr memory = Marshal.AllocHGlobal(size);
try
{
status = SafeNativeMethods.Gdip.GdipGetImageDecoders(numDecoders, size, memory);
if (status != SafeNativeMethods.Gdip.Ok)
{
throw SafeNativeMethods.Gdip.StatusException(status);
}
imageCodecs = ImageCodecInfo.ConvertFromMemory(memory, numDecoders);
}
finally
{
Marshal.FreeHGlobal(memory);
}
return imageCodecs;
}
/// <include file='doc\ImageCodecInfo.uex' path='docs/doc[@for="ImageCodecInfo.GetImageEncoders"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public static ImageCodecInfo[] GetImageEncoders()
{
ImageCodecInfo[] imageCodecs;
int numEncoders;
int size;
int status = SafeNativeMethods.Gdip.GdipGetImageEncodersSize(out numEncoders, out size);
if (status != SafeNativeMethods.Gdip.Ok)
{
throw SafeNativeMethods.Gdip.StatusException(status);
}
IntPtr memory = Marshal.AllocHGlobal(size);
try
{
status = SafeNativeMethods.Gdip.GdipGetImageEncoders(numEncoders, size, memory);
if (status != SafeNativeMethods.Gdip.Ok)
{
throw SafeNativeMethods.Gdip.StatusException(status);
}
imageCodecs = ImageCodecInfo.ConvertFromMemory(memory, numEncoders);
}
finally
{
Marshal.FreeHGlobal(memory);
}
return imageCodecs;
}
/* FxCop rule 'AvoidBuildingNonCallableCode' - Left here in case it is needed in the future.
internal static ImageCodecInfoPrivate ConvertToMemory(ImageCodecInfo imagecs)
{
ImageCodecInfoPrivate imagecsp = new ImageCodecInfoPrivate();
imagecsp.Clsid = imagecs.Clsid;
imagecsp.FormatID = imagecs.FormatID;
imagecsp.CodecName = Marshal.StringToHGlobalUni(imagecs.CodecName);
imagecsp.DllName = Marshal.StringToHGlobalUni(imagecs.DllName);
imagecsp.FormatDescription = Marshal.StringToHGlobalUni(imagecs.FormatDescription);
imagecsp.FilenameExtension = Marshal.StringToHGlobalUni(imagecs.FilenameExtension);
imagecsp.MimeType = Marshal.StringToHGlobalUni(imagecs.MimeType);
imagecsp.Flags = (int)imagecs.Flags;
imagecsp.Version = (int)imagecs.Version;
imagecsp.SigCount = imagecs.SignaturePatterns.Length;
imagecsp.SigSize = imagecs.SignaturePatterns[0].Length;
imagecsp.SigPattern = Marshal.AllocHGlobal(imagecsp.SigCount*imagecsp.SigSize);
imagecsp.SigMask = Marshal.AllocHGlobal(imagecsp.SigCount*imagecsp.SigSize);
for (int i=0; i<imagecsp.SigCount; i++)
{
Marshal.Copy(imagecs.SignaturePatterns[i],
0,
(IntPtr)((long)imagecsp.SigPattern + i*imagecsp.SigSize),
imagecsp.SigSize);
Marshal.Copy(imagecs.SignatureMasks[i],
0,
(IntPtr)((long)imagecsp.SigMask + i*imagecsp.SigSize),
imagecsp.SigSize);
}
return imagecsp;
}
internal static void FreeMemory(ImageCodecInfoPrivate imagecodecp)
{
Marshal.FreeHGlobal(imagecodecp.CodecName);
Marshal.FreeHGlobal(imagecodecp.FormatDescription);
Marshal.FreeHGlobal(imagecodecp.FilenameExtension);
Marshal.FreeHGlobal(imagecodecp.MimeType);
Marshal.FreeHGlobal(imagecodecp.SigPattern);
Marshal.FreeHGlobal(imagecodecp.SigMask);
}
*/
private static ImageCodecInfo[] ConvertFromMemory(IntPtr memoryStart, int numCodecs)
{
ImageCodecInfo[] codecs = new ImageCodecInfo[numCodecs];
int index;
for (index = 0; index < numCodecs; index++)
{
IntPtr curcodec = (IntPtr)((long)memoryStart + (int)Marshal.SizeOf(typeof(ImageCodecInfoPrivate)) * index);
ImageCodecInfoPrivate codecp = new ImageCodecInfoPrivate();
UnsafeNativeMethods.PtrToStructure(curcodec, codecp);
codecs[index] = new ImageCodecInfo();
codecs[index].Clsid = codecp.Clsid;
codecs[index].FormatID = codecp.FormatID;
codecs[index].CodecName = Marshal.PtrToStringUni(codecp.CodecName);
codecs[index].DllName = Marshal.PtrToStringUni(codecp.DllName);
codecs[index].FormatDescription = Marshal.PtrToStringUni(codecp.FormatDescription);
codecs[index].FilenameExtension = Marshal.PtrToStringUni(codecp.FilenameExtension);
codecs[index].MimeType = Marshal.PtrToStringUni(codecp.MimeType);
codecs[index].Flags = (ImageCodecFlags)codecp.Flags;
codecs[index].Version = (int)codecp.Version;
codecs[index].SignaturePatterns = new byte[codecp.SigCount][];
codecs[index].SignatureMasks = new byte[codecp.SigCount][];
for (int j = 0; j < codecp.SigCount; j++)
{
codecs[index].SignaturePatterns[j] = new byte[codecp.SigSize];
codecs[index].SignatureMasks[j] = new byte[codecp.SigSize];
Marshal.Copy((IntPtr)((long)codecp.SigMask + j * codecp.SigSize), codecs[index].SignatureMasks[j], 0, codecp.SigSize);
Marshal.Copy((IntPtr)((long)codecp.SigPattern + j * codecp.SigSize), codecs[index].SignaturePatterns[j], 0, codecp.SigSize);
}
}
return codecs;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Formatting;
using System.Net.Http.Headers;
using System.Web.Http.Description;
using System.Xml.Linq;
using Newtonsoft.Json;
namespace BlueYonder.Reservations.Areas.HelpPage
{
/// <summary>
/// This class will generate the samples for the help page.
/// </summary>
public class HelpPageSampleGenerator
{
/// <summary>
/// Initializes a new instance of the <see cref="HelpPageSampleGenerator"/> class.
/// </summary>
public HelpPageSampleGenerator()
{
ActualHttpMessageTypes = new Dictionary<HelpPageSampleKey, Type>();
ActionSamples = new Dictionary<HelpPageSampleKey, object>();
SampleObjects = new Dictionary<Type, object>();
SampleObjectFactories = new List<Func<HelpPageSampleGenerator, Type, object>>
{
DefaultSampleObjectFactory,
};
}
/// <summary>
/// Gets CLR types that are used as the content of <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/>.
/// </summary>
public IDictionary<HelpPageSampleKey, Type> ActualHttpMessageTypes { get; internal set; }
/// <summary>
/// Gets the objects that are used directly as samples for certain actions.
/// </summary>
public IDictionary<HelpPageSampleKey, object> ActionSamples { get; internal set; }
/// <summary>
/// Gets the objects that are serialized as samples by the supported formatters.
/// </summary>
public IDictionary<Type, object> SampleObjects { get; internal set; }
/// <summary>
/// Gets factories for the objects that the supported formatters will serialize as samples. Processed in order,
/// stopping when the factory successfully returns a non-<see langref="null"/> object.
/// </summary>
/// <remarks>
/// Collection includes just <see cref="ObjectGenerator.GenerateObject(Type)"/> initially. Use
/// <code>SampleObjectFactories.Insert(0, func)</code> to provide an override and
/// <code>SampleObjectFactories.Add(func)</code> to provide a fallback.</remarks>
[SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures",
Justification = "This is an appropriate nesting of generic types")]
public IList<Func<HelpPageSampleGenerator, Type, object>> SampleObjectFactories { get; private set; }
/// <summary>
/// Gets the request body samples for a given <see cref="ApiDescription"/>.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The samples keyed by media type.</returns>
public IDictionary<MediaTypeHeaderValue, object> GetSampleRequests(ApiDescription api)
{
return GetSample(api, SampleDirection.Request);
}
/// <summary>
/// Gets the response body samples for a given <see cref="ApiDescription"/>.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The samples keyed by media type.</returns>
public IDictionary<MediaTypeHeaderValue, object> GetSampleResponses(ApiDescription api)
{
return GetSample(api, SampleDirection.Response);
}
/// <summary>
/// Gets the request or response body samples.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param>
/// <returns>The samples keyed by media type.</returns>
public virtual IDictionary<MediaTypeHeaderValue, object> GetSample(ApiDescription api, SampleDirection sampleDirection)
{
if (api == null)
{
throw new ArgumentNullException("api");
}
string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName;
string actionName = api.ActionDescriptor.ActionName;
IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name);
Collection<MediaTypeFormatter> formatters;
Type type = ResolveType(api, controllerName, actionName, parameterNames, sampleDirection, out formatters);
var samples = new Dictionary<MediaTypeHeaderValue, object>();
// Use the samples provided directly for actions
var actionSamples = GetAllActionSamples(controllerName, actionName, parameterNames, sampleDirection);
foreach (var actionSample in actionSamples)
{
samples.Add(actionSample.Key.MediaType, WrapSampleIfString(actionSample.Value));
}
// Do the sample generation based on formatters only if an action doesn't return an HttpResponseMessage.
// Here we cannot rely on formatters because we don't know what's in the HttpResponseMessage, it might not even use formatters.
if (type != null && !typeof(HttpResponseMessage).IsAssignableFrom(type))
{
object sampleObject = GetSampleObject(type);
foreach (var formatter in formatters)
{
foreach (MediaTypeHeaderValue mediaType in formatter.SupportedMediaTypes)
{
if (!samples.ContainsKey(mediaType))
{
object sample = GetActionSample(controllerName, actionName, parameterNames, type, formatter, mediaType, sampleDirection);
// If no sample found, try generate sample using formatter and sample object
if (sample == null && sampleObject != null)
{
sample = WriteSampleObjectUsingFormatter(formatter, sampleObject, type, mediaType);
}
samples.Add(mediaType, WrapSampleIfString(sample));
}
}
}
}
return samples;
}
/// <summary>
/// Search for samples that are provided directly through <see cref="ActionSamples"/>.
/// </summary>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
/// <param name="type">The CLR type.</param>
/// <param name="formatter">The formatter.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param>
/// <returns>The sample that matches the parameters.</returns>
public virtual object GetActionSample(string controllerName, string actionName, IEnumerable<string> parameterNames, Type type, MediaTypeFormatter formatter, MediaTypeHeaderValue mediaType, SampleDirection sampleDirection)
{
object sample;
// First, try to get the sample provided for the specified mediaType, sampleDirection, controllerName, actionName and parameterNames.
// If not found, try to get the sample provided for the specified mediaType, sampleDirection, controllerName and actionName regardless of the parameterNames.
// If still not found, try to get the sample provided for the specified mediaType and type.
// Finally, try to get the sample provided for the specified mediaType.
if (ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, parameterNames), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, new[] { "*" }), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, type), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType), out sample))
{
return sample;
}
return null;
}
/// <summary>
/// Gets the sample object that will be serialized by the formatters.
/// First, it will look at the <see cref="SampleObjects"/>. If no sample object is found, it will try to create
/// one using <see cref="DefaultSampleObjectFactory"/> (which wraps an <see cref="ObjectGenerator"/>) and other
/// factories in <see cref="SampleObjectFactories"/>.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>The sample object.</returns>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes",
Justification = "Even if all items in SampleObjectFactories throw, problem will be visible as missing sample.")]
public virtual object GetSampleObject(Type type)
{
object sampleObject;
if (!SampleObjects.TryGetValue(type, out sampleObject))
{
// No specific object available, try our factories.
foreach (Func<HelpPageSampleGenerator, Type, object> factory in SampleObjectFactories)
{
if (factory == null)
{
continue;
}
try
{
sampleObject = factory(this, type);
if (sampleObject != null)
{
break;
}
}
catch
{
// Ignore any problems encountered in the factory; go on to the next one (if any).
}
}
}
return sampleObject;
}
/// <summary>
/// Resolves the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The type.</returns>
public virtual Type ResolveHttpRequestMessageType(ApiDescription api)
{
string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName;
string actionName = api.ActionDescriptor.ActionName;
IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name);
Collection<MediaTypeFormatter> formatters;
return ResolveType(api, controllerName, actionName, parameterNames, SampleDirection.Request, out formatters);
}
/// <summary>
/// Resolves the type of the action parameter or return value when <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/> is used.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or a response.</param>
/// <param name="formatters">The formatters.</param>
[SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", Justification = "This is only used in advanced scenarios.")]
public virtual Type ResolveType(ApiDescription api, string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection, out Collection<MediaTypeFormatter> formatters)
{
if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection))
{
throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection));
}
if (api == null)
{
throw new ArgumentNullException("api");
}
Type type;
if (ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, parameterNames), out type) ||
ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, new[] { "*" }), out type))
{
// Re-compute the supported formatters based on type
Collection<MediaTypeFormatter> newFormatters = new Collection<MediaTypeFormatter>();
foreach (var formatter in api.ActionDescriptor.Configuration.Formatters)
{
if (IsFormatSupported(sampleDirection, formatter, type))
{
newFormatters.Add(formatter);
}
}
formatters = newFormatters;
}
else
{
switch (sampleDirection)
{
case SampleDirection.Request:
ApiParameterDescription requestBodyParameter = api.ParameterDescriptions.FirstOrDefault(p => p.Source == ApiParameterSource.FromBody);
type = requestBodyParameter == null ? null : requestBodyParameter.ParameterDescriptor.ParameterType;
formatters = api.SupportedRequestBodyFormatters;
break;
case SampleDirection.Response:
default:
type = api.ResponseDescription.ResponseType ?? api.ResponseDescription.DeclaredType;
formatters = api.SupportedResponseFormatters;
break;
}
}
return type;
}
/// <summary>
/// Writes the sample object using formatter.
/// </summary>
/// <param name="formatter">The formatter.</param>
/// <param name="value">The value.</param>
/// <param name="type">The type.</param>
/// <param name="mediaType">Type of the media.</param>
/// <returns></returns>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as InvalidSample.")]
public virtual object WriteSampleObjectUsingFormatter(MediaTypeFormatter formatter, object value, Type type, MediaTypeHeaderValue mediaType)
{
if (formatter == null)
{
throw new ArgumentNullException("formatter");
}
if (mediaType == null)
{
throw new ArgumentNullException("mediaType");
}
object sample = String.Empty;
MemoryStream ms = null;
HttpContent content = null;
try
{
if (formatter.CanWriteType(type))
{
ms = new MemoryStream();
content = new ObjectContent(type, value, formatter, mediaType);
formatter.WriteToStreamAsync(type, value, ms, content, null).Wait();
ms.Position = 0;
StreamReader reader = new StreamReader(ms);
string serializedSampleString = reader.ReadToEnd();
if (mediaType.MediaType.ToUpperInvariant().Contains("XML"))
{
serializedSampleString = TryFormatXml(serializedSampleString);
}
else if (mediaType.MediaType.ToUpperInvariant().Contains("JSON"))
{
serializedSampleString = TryFormatJson(serializedSampleString);
}
sample = new TextSample(serializedSampleString);
}
else
{
sample = new InvalidSample(String.Format(
CultureInfo.CurrentCulture,
"Failed to generate the sample for media type '{0}'. Cannot use formatter '{1}' to write type '{2}'.",
mediaType,
formatter.GetType().Name,
type.Name));
}
}
catch (Exception e)
{
sample = new InvalidSample(String.Format(
CultureInfo.CurrentCulture,
"An exception has occurred while using the formatter '{0}' to generate sample for media type '{1}'. Exception message: {2}",
formatter.GetType().Name,
mediaType.MediaType,
UnwrapException(e).Message));
}
finally
{
if (ms != null)
{
ms.Dispose();
}
if (content != null)
{
content.Dispose();
}
}
return sample;
}
internal static Exception UnwrapException(Exception exception)
{
AggregateException aggregateException = exception as AggregateException;
if (aggregateException != null)
{
return aggregateException.Flatten().InnerException;
}
return exception;
}
// Default factory for sample objects
private static object DefaultSampleObjectFactory(HelpPageSampleGenerator sampleGenerator, Type type)
{
// Try to create a default sample object
ObjectGenerator objectGenerator = new ObjectGenerator();
return objectGenerator.GenerateObject(type);
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")]
private static string TryFormatJson(string str)
{
try
{
object parsedJson = JsonConvert.DeserializeObject(str);
return JsonConvert.SerializeObject(parsedJson, Formatting.Indented);
}
catch
{
// can't parse JSON, return the original string
return str;
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")]
private static string TryFormatXml(string str)
{
try
{
XDocument xml = XDocument.Parse(str);
return xml.ToString();
}
catch
{
// can't parse XML, return the original string
return str;
}
}
private static bool IsFormatSupported(SampleDirection sampleDirection, MediaTypeFormatter formatter, Type type)
{
switch (sampleDirection)
{
case SampleDirection.Request:
return formatter.CanReadType(type);
case SampleDirection.Response:
return formatter.CanWriteType(type);
}
return false;
}
private IEnumerable<KeyValuePair<HelpPageSampleKey, object>> GetAllActionSamples(string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection)
{
HashSet<string> parameterNamesSet = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase);
foreach (var sample in ActionSamples)
{
HelpPageSampleKey sampleKey = sample.Key;
if (String.Equals(controllerName, sampleKey.ControllerName, StringComparison.OrdinalIgnoreCase) &&
String.Equals(actionName, sampleKey.ActionName, StringComparison.OrdinalIgnoreCase) &&
(sampleKey.ParameterNames.SetEquals(new[] { "*" }) || parameterNamesSet.SetEquals(sampleKey.ParameterNames)) &&
sampleDirection == sampleKey.SampleDirection)
{
yield return sample;
}
}
}
private static object WrapSampleIfString(object sample)
{
string stringSample = sample as string;
if (stringSample != null)
{
return new TextSample(stringSample);
}
return sample;
}
}
}
| |
using System;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Windows.Forms;
using System.ComponentModel;
namespace WeifenLuo.WinFormsUI.Docking
{
internal class VS2005DockPaneStrip : DockPaneStripBase
{
private class TabVS2005 : Tab
{
public TabVS2005(IDockContent content)
: base(content)
{
}
private int m_tabX;
public int TabX
{
get { return m_tabX; }
set { m_tabX = value; }
}
private int m_tabWidth;
public int TabWidth
{
get { return m_tabWidth; }
set { m_tabWidth = value; }
}
private int m_maxWidth;
public int MaxWidth
{
get { return m_maxWidth; }
set { m_maxWidth = value; }
}
private bool m_flag;
protected internal bool Flag
{
get { return m_flag; }
set { m_flag = value; }
}
}
protected internal override DockPaneStripBase.Tab CreateTab(IDockContent content)
{
return new TabVS2005(content);
}
private sealed class InertButton : InertButtonBase
{
private Bitmap m_image0, m_image1;
public InertButton(Bitmap image0, Bitmap image1)
: base()
{
m_image0 = image0;
m_image1 = image1;
}
private int m_imageCategory = 0;
public int ImageCategory
{
get { return m_imageCategory; }
set
{
if (m_imageCategory == value)
return;
m_imageCategory = value;
Invalidate();
}
}
public override Bitmap Image
{
get { return ImageCategory == 0 ? m_image0 : m_image1; }
}
}
#region Constants
private const int _ToolWindowStripGapTop = 0;
private const int _ToolWindowStripGapBottom = 1;
private const int _ToolWindowStripGapLeft = 0;
private const int _ToolWindowStripGapRight = 0;
private const int _ToolWindowImageHeight = 16;
private const int _ToolWindowImageWidth = 16;
private const int _ToolWindowImageGapTop = 3;
private const int _ToolWindowImageGapBottom = 1;
private const int _ToolWindowImageGapLeft = 2;
private const int _ToolWindowImageGapRight = 0;
private const int _ToolWindowTextGapRight = 3;
private const int _ToolWindowTabSeperatorGapTop = 3;
private const int _ToolWindowTabSeperatorGapBottom = 3;
private const int _DocumentStripGapTop = 0;
private const int _DocumentStripGapBottom = 1;
private const int _DocumentTabMaxWidth = 200;
private const int _DocumentButtonGapTop = 4;
private const int _DocumentButtonGapBottom = 4;
private const int _DocumentButtonGapBetween = 0;
private const int _DocumentButtonGapRight = 3;
private const int _DocumentTabGapTop = 3;
private const int _DocumentTabGapLeft = 3;
private const int _DocumentTabGapRight = 3;
private const int _DocumentIconGapBottom = 2;
private const int _DocumentIconGapLeft = 8;
private const int _DocumentIconGapRight = 0;
private const int _DocumentIconHeight = 16;
private const int _DocumentIconWidth = 16;
private const int _DocumentTextGapRight = 3;
#endregion
#region Members
private ContextMenuStrip m_selectMenu;
private static Bitmap m_imageButtonClose;
private InertButton m_buttonClose;
private static Bitmap m_imageButtonWindowList;
private static Bitmap m_imageButtonWindowListOverflow;
private InertButton m_buttonWindowList;
private IContainer m_components;
private ToolTip m_toolTip;
private Font m_font;
private Font m_boldFont;
private int m_startDisplayingTab = 0;
private int m_endDisplayingTab = 0;
private int m_firstDisplayingTab = 0;
private bool m_documentTabsOverflow = false;
private static string m_toolTipSelect;
private static string m_toolTipClose;
private bool m_closeButtonVisible = false;
private int _selectMenuMargin = 5;
#endregion
#region Properties
private Rectangle TabStripRectangle
{
get
{
if (Appearance == DockPane.AppearanceStyle.Document)
return TabStripRectangle_Document;
else
return TabStripRectangle_ToolWindow;
}
}
private Rectangle TabStripRectangle_ToolWindow
{
get
{
Rectangle rect = ClientRectangle;
return new Rectangle(rect.X, rect.Top + ToolWindowStripGapTop, rect.Width, rect.Height - ToolWindowStripGapTop - ToolWindowStripGapBottom);
}
}
private Rectangle TabStripRectangle_Document
{
get
{
Rectangle rect = ClientRectangle;
return new Rectangle(rect.X, rect.Top + DocumentStripGapTop, rect.Width, rect.Height - DocumentStripGapTop - ToolWindowStripGapBottom);
}
}
private Rectangle TabsRectangle
{
get
{
if (Appearance == DockPane.AppearanceStyle.ToolWindow)
return TabStripRectangle;
Rectangle rectWindow = TabStripRectangle;
int x = rectWindow.X;
int y = rectWindow.Y;
int width = rectWindow.Width;
int height = rectWindow.Height;
x += DocumentTabGapLeft;
width -= DocumentTabGapLeft +
DocumentTabGapRight +
DocumentButtonGapRight +
ButtonClose.Width +
ButtonWindowList.Width +
2 * DocumentButtonGapBetween;
return new Rectangle(x, y, width, height);
}
}
private ContextMenuStrip SelectMenu
{
get { return m_selectMenu; }
}
public int SelectMenuMargin
{
get { return _selectMenuMargin; }
set { _selectMenuMargin = value; }
}
private static Bitmap ImageButtonClose
{
get
{
if (m_imageButtonClose == null)
m_imageButtonClose = Resources.DockPane_Close;
return m_imageButtonClose;
}
}
private InertButton ButtonClose
{
get
{
if (m_buttonClose == null)
{
m_buttonClose = new InertButton(ImageButtonClose, ImageButtonClose);
m_toolTip.SetToolTip(m_buttonClose, ToolTipClose);
m_buttonClose.Click += new EventHandler(Close_Click);
Controls.Add(m_buttonClose);
}
return m_buttonClose;
}
}
private static Bitmap ImageButtonWindowList
{
get
{
if (m_imageButtonWindowList == null)
m_imageButtonWindowList = Resources.DockPane_Option;
return m_imageButtonWindowList;
}
}
private static Bitmap ImageButtonWindowListOverflow
{
get
{
if (m_imageButtonWindowListOverflow == null)
m_imageButtonWindowListOverflow = Resources.DockPane_OptionOverflow;
return m_imageButtonWindowListOverflow;
}
}
private InertButton ButtonWindowList
{
get
{
if (m_buttonWindowList == null)
{
m_buttonWindowList = new InertButton(ImageButtonWindowList, ImageButtonWindowListOverflow);
m_toolTip.SetToolTip(m_buttonWindowList, ToolTipSelect);
m_buttonWindowList.Click += new EventHandler(WindowList_Click);
Controls.Add(m_buttonWindowList);
}
return m_buttonWindowList;
}
}
private static GraphicsPath GraphicsPath
{
get { return VS2005AutoHideStrip.GraphicsPath; }
}
private IContainer Components
{
get { return m_components; }
}
public Font TextFont
{
get { return DockPane.DockPanel.Skin.DockPaneStripSkin.TextFont; }
}
private Font BoldFont
{
get
{
if (IsDisposed)
return null;
if (m_boldFont == null)
{
m_font = TextFont;
m_boldFont = new Font(TextFont, FontStyle.Bold);
}
else if (m_font != TextFont)
{
m_boldFont.Dispose();
m_font = TextFont;
m_boldFont = new Font(TextFont, FontStyle.Bold);
}
return m_boldFont;
}
}
private int StartDisplayingTab
{
get { return m_startDisplayingTab; }
set
{
m_startDisplayingTab = value;
Invalidate();
}
}
private int EndDisplayingTab
{
get { return m_endDisplayingTab; }
set { m_endDisplayingTab = value; }
}
private int FirstDisplayingTab
{
get { return m_firstDisplayingTab; }
set { m_firstDisplayingTab = value; }
}
private bool DocumentTabsOverflow
{
set
{
if (m_documentTabsOverflow == value)
return;
m_documentTabsOverflow = value;
if (value)
ButtonWindowList.ImageCategory = 1;
else
ButtonWindowList.ImageCategory = 0;
}
}
#region Customizable Properties
private static int ToolWindowStripGapTop
{
get { return _ToolWindowStripGapTop; }
}
private static int ToolWindowStripGapBottom
{
get { return _ToolWindowStripGapBottom; }
}
private static int ToolWindowStripGapLeft
{
get { return _ToolWindowStripGapLeft; }
}
private static int ToolWindowStripGapRight
{
get { return _ToolWindowStripGapRight; }
}
private static int ToolWindowImageHeight
{
get { return _ToolWindowImageHeight; }
}
private static int ToolWindowImageWidth
{
get { return _ToolWindowImageWidth; }
}
private static int ToolWindowImageGapTop
{
get { return _ToolWindowImageGapTop; }
}
private static int ToolWindowImageGapBottom
{
get { return _ToolWindowImageGapBottom; }
}
private static int ToolWindowImageGapLeft
{
get { return _ToolWindowImageGapLeft; }
}
private static int ToolWindowImageGapRight
{
get { return _ToolWindowImageGapRight; }
}
private static int ToolWindowTextGapRight
{
get { return _ToolWindowTextGapRight; }
}
private static int ToolWindowTabSeperatorGapTop
{
get { return _ToolWindowTabSeperatorGapTop; }
}
private static int ToolWindowTabSeperatorGapBottom
{
get { return _ToolWindowTabSeperatorGapBottom; }
}
private static string ToolTipClose
{
get
{
if (m_toolTipClose == null)
m_toolTipClose = Strings.DockPaneStrip_ToolTipClose;
return m_toolTipClose;
}
}
private static string ToolTipSelect
{
get
{
if (m_toolTipSelect == null)
m_toolTipSelect = Strings.DockPaneStrip_ToolTipWindowList;
return m_toolTipSelect;
}
}
private TextFormatFlags ToolWindowTextFormat
{
get
{
TextFormatFlags textFormat = TextFormatFlags.EndEllipsis |
TextFormatFlags.HorizontalCenter |
TextFormatFlags.SingleLine |
TextFormatFlags.VerticalCenter;
if (RightToLeft == RightToLeft.Yes)
return textFormat | TextFormatFlags.RightToLeft | TextFormatFlags.Right;
else
return textFormat;
}
}
private static int DocumentStripGapTop
{
get { return _DocumentStripGapTop; }
}
private static int DocumentStripGapBottom
{
get { return _DocumentStripGapBottom; }
}
private TextFormatFlags DocumentTextFormat
{
get
{
TextFormatFlags textFormat = TextFormatFlags.EndEllipsis |
TextFormatFlags.SingleLine |
TextFormatFlags.VerticalCenter |
TextFormatFlags.HorizontalCenter;
if (RightToLeft == RightToLeft.Yes)
return textFormat | TextFormatFlags.RightToLeft;
else
return textFormat;
}
}
private static int DocumentTabMaxWidth
{
get { return _DocumentTabMaxWidth; }
}
private static int DocumentButtonGapTop
{
get { return _DocumentButtonGapTop; }
}
private static int DocumentButtonGapBottom
{
get { return _DocumentButtonGapBottom; }
}
private static int DocumentButtonGapBetween
{
get { return _DocumentButtonGapBetween; }
}
private static int DocumentButtonGapRight
{
get { return _DocumentButtonGapRight; }
}
private static int DocumentTabGapTop
{
get { return _DocumentTabGapTop; }
}
private static int DocumentTabGapLeft
{
get { return _DocumentTabGapLeft; }
}
private static int DocumentTabGapRight
{
get { return _DocumentTabGapRight; }
}
private static int DocumentIconGapBottom
{
get { return _DocumentIconGapBottom; }
}
private static int DocumentIconGapLeft
{
get { return _DocumentIconGapLeft; }
}
private static int DocumentIconGapRight
{
get { return _DocumentIconGapRight; }
}
private static int DocumentIconWidth
{
get { return _DocumentIconWidth; }
}
private static int DocumentIconHeight
{
get { return _DocumentIconHeight; }
}
private static int DocumentTextGapRight
{
get { return _DocumentTextGapRight; }
}
private static Pen PenToolWindowTabBorder
{
get { return SystemPens.GrayText; }
}
private static Pen PenDocumentTabActiveBorder
{
get { return SystemPens.ControlDarkDark; }
}
private static Pen PenDocumentTabInactiveBorder
{
get { return SystemPens.GrayText; }
}
#endregion
#endregion
public VS2005DockPaneStrip(DockPane pane)
: base(pane)
{
SetStyle(ControlStyles.ResizeRedraw |
ControlStyles.UserPaint |
ControlStyles.AllPaintingInWmPaint |
ControlStyles.OptimizedDoubleBuffer, true);
SuspendLayout();
m_components = new Container();
m_toolTip = new ToolTip(Components);
m_selectMenu = new ContextMenuStrip(Components);
ResumeLayout();
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
Components.Dispose();
if (m_boldFont != null)
{
m_boldFont.Dispose();
m_boldFont = null;
}
}
base.Dispose(disposing);
}
protected internal override int MeasureHeight()
{
if (Appearance == DockPane.AppearanceStyle.ToolWindow)
return MeasureHeight_ToolWindow();
else
return MeasureHeight_Document();
}
private int MeasureHeight_ToolWindow()
{
if (DockPane.IsAutoHide || Tabs.Count <= 1)
return 0;
int height = Math.Max(TextFont.Height, ToolWindowImageHeight + ToolWindowImageGapTop + ToolWindowImageGapBottom)
+ ToolWindowStripGapTop + ToolWindowStripGapBottom;
return height;
}
private int MeasureHeight_Document()
{
int height = Math.Max(TextFont.Height + DocumentTabGapTop,
ButtonClose.Height + DocumentButtonGapTop + DocumentButtonGapBottom)
+ DocumentStripGapBottom + DocumentStripGapTop;
return height;
}
protected override void OnPaint(PaintEventArgs e)
{
Rectangle rect = TabsRectangle;
DockPanelGradient gradient = DockPane.DockPanel.Skin.DockPaneStripSkin.DocumentGradient.DockStripGradient;
if (Appearance == DockPane.AppearanceStyle.Document)
{
rect.X -= DocumentTabGapLeft;
// Add these values back in so that the DockStrip color is drawn
// beneath the close button and window list button.
// It is possible depending on the DockPanel DocumentStyle to have
// a Document without a DockStrip.
rect.Width += DocumentTabGapLeft +
DocumentTabGapRight +
DocumentButtonGapRight +
ButtonClose.Width +
ButtonWindowList.Width;
}
else
{
gradient = DockPane.DockPanel.Skin.DockPaneStripSkin.ToolWindowGradient.DockStripGradient;
}
Color startColor = gradient.StartColor;
Color endColor = gradient.EndColor;
LinearGradientMode gradientMode = gradient.LinearGradientMode;
DrawingRoutines.SafelyDrawLinearGradient(rect, startColor, endColor, gradientMode, e.Graphics);
base.OnPaint(e);
CalculateTabs();
if (Appearance == DockPane.AppearanceStyle.Document && DockPane.ActiveContent != null)
{
if (EnsureDocumentTabVisible(DockPane.ActiveContent, false))
CalculateTabs();
}
DrawTabStrip(e.Graphics);
}
protected override void OnRefreshChanges()
{
SetInertButtons();
Invalidate();
}
public override GraphicsPath GetOutline(int index)
{
if (Appearance == DockPane.AppearanceStyle.Document)
return GetOutline_Document(index);
else
return GetOutline_ToolWindow(index);
}
private GraphicsPath GetOutline_Document(int index)
{
Rectangle rectTab = GetTabRectangle(index);
rectTab.X -= rectTab.Height / 2;
rectTab.Intersect(TabsRectangle);
rectTab = RectangleToScreen(DrawHelper.RtlTransform(this, rectTab));
Rectangle rectPaneClient = DockPane.RectangleToScreen(DockPane.ClientRectangle);
GraphicsPath path = new GraphicsPath();
GraphicsPath pathTab = GetTabOutline_Document(Tabs[index], true, true, true);
path.AddPath(pathTab, true);
if (DockPane.DockPanel.DocumentTabStripLocation == DocumentTabStripLocation.Bottom)
{
path.AddLine(rectTab.Right, rectTab.Top, rectPaneClient.Right, rectTab.Top);
path.AddLine(rectPaneClient.Right, rectTab.Top, rectPaneClient.Right, rectPaneClient.Top);
path.AddLine(rectPaneClient.Right, rectPaneClient.Top, rectPaneClient.Left, rectPaneClient.Top);
path.AddLine(rectPaneClient.Left, rectPaneClient.Top, rectPaneClient.Left, rectTab.Top);
path.AddLine(rectPaneClient.Left, rectTab.Top, rectTab.Right, rectTab.Top);
}
else
{
path.AddLine(rectTab.Right, rectTab.Bottom, rectPaneClient.Right, rectTab.Bottom);
path.AddLine(rectPaneClient.Right, rectTab.Bottom, rectPaneClient.Right, rectPaneClient.Bottom);
path.AddLine(rectPaneClient.Right, rectPaneClient.Bottom, rectPaneClient.Left, rectPaneClient.Bottom);
path.AddLine(rectPaneClient.Left, rectPaneClient.Bottom, rectPaneClient.Left, rectTab.Bottom);
path.AddLine(rectPaneClient.Left, rectTab.Bottom, rectTab.Right, rectTab.Bottom);
}
return path;
}
private GraphicsPath GetOutline_ToolWindow(int index)
{
Rectangle rectTab = GetTabRectangle(index);
rectTab.Intersect(TabsRectangle);
rectTab = RectangleToScreen(DrawHelper.RtlTransform(this, rectTab));
Rectangle rectPaneClient = DockPane.RectangleToScreen(DockPane.ClientRectangle);
GraphicsPath path = new GraphicsPath();
GraphicsPath pathTab = GetTabOutline(Tabs[index], true, true);
path.AddPath(pathTab, true);
path.AddLine(rectTab.Left, rectTab.Top, rectPaneClient.Left, rectTab.Top);
path.AddLine(rectPaneClient.Left, rectTab.Top, rectPaneClient.Left, rectPaneClient.Top);
path.AddLine(rectPaneClient.Left, rectPaneClient.Top, rectPaneClient.Right, rectPaneClient.Top);
path.AddLine(rectPaneClient.Right, rectPaneClient.Top, rectPaneClient.Right, rectTab.Top);
path.AddLine(rectPaneClient.Right, rectTab.Top, rectTab.Right, rectTab.Top);
return path;
}
private void CalculateTabs()
{
if (Appearance == DockPane.AppearanceStyle.ToolWindow)
CalculateTabs_ToolWindow();
else
CalculateTabs_Document();
}
private void CalculateTabs_ToolWindow()
{
if (Tabs.Count <= 1 || DockPane.IsAutoHide)
return;
Rectangle rectTabStrip = TabStripRectangle;
// Calculate tab widths
int countTabs = Tabs.Count;
foreach (TabVS2005 tab in Tabs)
{
tab.MaxWidth = GetMaxTabWidth(Tabs.IndexOf(tab));
tab.Flag = false;
}
// Set tab whose max width less than average width
bool anyWidthWithinAverage = true;
int totalWidth = rectTabStrip.Width - ToolWindowStripGapLeft - ToolWindowStripGapRight;
int totalAllocatedWidth = 0;
int averageWidth = totalWidth / countTabs;
int remainedTabs = countTabs;
for (anyWidthWithinAverage = true; anyWidthWithinAverage && remainedTabs > 0; )
{
anyWidthWithinAverage = false;
foreach (TabVS2005 tab in Tabs)
{
if (tab.Flag)
continue;
if (tab.MaxWidth <= averageWidth)
{
tab.Flag = true;
tab.TabWidth = tab.MaxWidth;
totalAllocatedWidth += tab.TabWidth;
anyWidthWithinAverage = true;
remainedTabs--;
}
}
if (remainedTabs != 0)
averageWidth = (totalWidth - totalAllocatedWidth) / remainedTabs;
}
// If any tab width not set yet, set it to the average width
if (remainedTabs > 0)
{
int roundUpWidth = (totalWidth - totalAllocatedWidth) - (averageWidth * remainedTabs);
foreach (TabVS2005 tab in Tabs)
{
if (tab.Flag)
continue;
tab.Flag = true;
if (roundUpWidth > 0)
{
tab.TabWidth = averageWidth + 1;
roundUpWidth--;
}
else
tab.TabWidth = averageWidth;
}
}
// Set the X position of the tabs
int x = rectTabStrip.X + ToolWindowStripGapLeft;
foreach (TabVS2005 tab in Tabs)
{
tab.TabX = x;
x += tab.TabWidth;
}
}
private bool CalculateDocumentTab(Rectangle rectTabStrip, ref int x, int index)
{
bool overflow = false;
TabVS2005 tab = Tabs[index] as TabVS2005;
tab.MaxWidth = GetMaxTabWidth(index);
int width = Math.Min(tab.MaxWidth, DocumentTabMaxWidth);
if (x + width < rectTabStrip.Right || index == StartDisplayingTab)
{
tab.TabX = x;
tab.TabWidth = width;
EndDisplayingTab = index;
}
else
{
tab.TabX = 0;
tab.TabWidth = 0;
overflow = true;
}
x += width;
return overflow;
}
/// <summary>
/// Calculate which tabs are displayed and in what order.
/// </summary>
private void CalculateTabs_Document()
{
if (m_startDisplayingTab >= Tabs.Count)
m_startDisplayingTab = 0;
Rectangle rectTabStrip = TabsRectangle;
int x = rectTabStrip.X + rectTabStrip.Height / 2;
bool overflow = false;
// Originally all new documents that were considered overflow
// (not enough pane strip space to show all tabs) were added to
// the far left (assuming not right to left) and the tabs on the
// right were dropped from view. If StartDisplayingTab is not 0
// then we are dealing with making sure a specific tab is kept in focus.
if (m_startDisplayingTab > 0)
{
int tempX = x;
TabVS2005 tab = Tabs[m_startDisplayingTab] as TabVS2005;
tab.MaxWidth = GetMaxTabWidth(m_startDisplayingTab);
// Add the active tab and tabs to the left
for (int i = StartDisplayingTab; i >= 0; i--)
CalculateDocumentTab(rectTabStrip, ref tempX, i);
// Store which tab is the first one displayed so that it
// will be drawn correctly (without part of the tab cut off)
FirstDisplayingTab = EndDisplayingTab;
tempX = x; // Reset X location because we are starting over
// Start with the first tab displayed - name is a little misleading.
// Loop through each tab and set its location. If there is not enough
// room for all of them overflow will be returned.
for (int i = EndDisplayingTab; i < Tabs.Count; i++)
overflow = CalculateDocumentTab(rectTabStrip, ref tempX, i);
// If not all tabs are shown then we have an overflow.
if (FirstDisplayingTab != 0)
overflow = true;
}
else
{
for (int i = StartDisplayingTab; i < Tabs.Count; i++)
overflow = CalculateDocumentTab(rectTabStrip, ref x, i);
for (int i = 0; i < StartDisplayingTab; i++)
overflow = CalculateDocumentTab(rectTabStrip, ref x, i);
FirstDisplayingTab = StartDisplayingTab;
}
if (!overflow)
{
m_startDisplayingTab = 0;
FirstDisplayingTab = 0;
x = rectTabStrip.X + rectTabStrip.Height / 2;
foreach (TabVS2005 tab in Tabs)
{
tab.TabX = x;
x += tab.TabWidth;
}
}
DocumentTabsOverflow = overflow;
}
protected internal override void EnsureTabVisible(IDockContent content)
{
if (Appearance != DockPane.AppearanceStyle.Document || !Tabs.Contains(content))
return;
CalculateTabs();
EnsureDocumentTabVisible(content, true);
}
private bool EnsureDocumentTabVisible(IDockContent content, bool repaint)
{
int index = Tabs.IndexOf(content);
TabVS2005 tab = Tabs[index] as TabVS2005;
if (tab.TabWidth != 0)
return false;
StartDisplayingTab = index;
if (repaint)
Invalidate();
return true;
}
private int GetMaxTabWidth(int index)
{
if (Appearance == DockPane.AppearanceStyle.ToolWindow)
return GetMaxTabWidth_ToolWindow(index);
else
return GetMaxTabWidth_Document(index);
}
private int GetMaxTabWidth_ToolWindow(int index)
{
IDockContent content = Tabs[index].Content;
Size sizeString = TextRenderer.MeasureText(content.DockHandler.TabText, TextFont);
return ToolWindowImageWidth + sizeString.Width + ToolWindowImageGapLeft
+ ToolWindowImageGapRight + ToolWindowTextGapRight;
}
private int GetMaxTabWidth_Document(int index)
{
IDockContent content = Tabs[index].Content;
int height = GetTabRectangle_Document(index).Height;
Size sizeText = TextRenderer.MeasureText(content.DockHandler.TabText, BoldFont, new Size(DocumentTabMaxWidth, height), DocumentTextFormat);
if (DockPane.DockPanel.ShowDocumentIcon)
return sizeText.Width + DocumentIconWidth + DocumentIconGapLeft + DocumentIconGapRight + DocumentTextGapRight;
else
return sizeText.Width + DocumentIconGapLeft + DocumentTextGapRight;
}
private void DrawTabStrip(Graphics g)
{
if (Appearance == DockPane.AppearanceStyle.Document)
DrawTabStrip_Document(g);
else
DrawTabStrip_ToolWindow(g);
}
private void DrawTabStrip_Document(Graphics g)
{
int count = Tabs.Count;
if (count == 0)
return;
Rectangle rectTabStrip = TabStripRectangle;
// Draw the tabs
Rectangle rectTabOnly = TabsRectangle;
Rectangle rectTab = Rectangle.Empty;
TabVS2005 tabActive = null;
g.SetClip(DrawHelper.RtlTransform(this, rectTabOnly));
for (int i = 0; i < count; i++)
{
rectTab = GetTabRectangle(i);
if (Tabs[i].Content == DockPane.ActiveContent)
{
tabActive = Tabs[i] as TabVS2005;
continue;
}
if (rectTab.IntersectsWith(rectTabOnly))
DrawTab(g, Tabs[i] as TabVS2005, rectTab);
}
g.SetClip(rectTabStrip);
if (DockPane.DockPanel.DocumentTabStripLocation == DocumentTabStripLocation.Bottom)
g.DrawLine(PenDocumentTabActiveBorder, rectTabStrip.Left, rectTabStrip.Top + 1,
rectTabStrip.Right, rectTabStrip.Top + 1);
else
g.DrawLine(PenDocumentTabActiveBorder, rectTabStrip.Left, rectTabStrip.Bottom - 1,
rectTabStrip.Right, rectTabStrip.Bottom - 1);
g.SetClip(DrawHelper.RtlTransform(this, rectTabOnly));
if (tabActive != null)
{
rectTab = GetTabRectangle(Tabs.IndexOf(tabActive));
if (rectTab.IntersectsWith(rectTabOnly))
{
rectTab.Intersect(rectTabOnly);
DrawTab(g, tabActive, rectTab);
}
}
}
private void DrawTabStrip_ToolWindow(Graphics g)
{
Rectangle rectTabStrip = TabStripRectangle;
g.DrawLine(PenToolWindowTabBorder, rectTabStrip.Left, rectTabStrip.Top,
rectTabStrip.Right, rectTabStrip.Top);
for (int i = 0; i < Tabs.Count; i++)
DrawTab(g, Tabs[i] as TabVS2005, GetTabRectangle(i));
}
private Rectangle GetTabRectangle(int index)
{
if (Appearance == DockPane.AppearanceStyle.ToolWindow)
return GetTabRectangle_ToolWindow(index);
else
return GetTabRectangle_Document(index);
}
private Rectangle GetTabRectangle_ToolWindow(int index)
{
Rectangle rectTabStrip = TabStripRectangle;
TabVS2005 tab = (TabVS2005)(Tabs[index]);
return new Rectangle(tab.TabX, rectTabStrip.Y, tab.TabWidth, rectTabStrip.Height);
}
private Rectangle GetTabRectangle_Document(int index)
{
Rectangle rectTabStrip = TabStripRectangle;
TabVS2005 tab = (TabVS2005)Tabs[index];
Rectangle rect = new Rectangle();
rect.X = tab.TabX;
rect.Width = tab.TabWidth;
rect.Height = rectTabStrip.Height - DocumentTabGapTop;
if (DockPane.DockPanel.DocumentTabStripLocation == DocumentTabStripLocation.Bottom)
rect.Y = rectTabStrip.Y + DocumentStripGapBottom;
else
rect.Y = rectTabStrip.Y + DocumentTabGapTop;
return rect;
}
private void DrawTab(Graphics g, TabVS2005 tab, Rectangle rect)
{
if (Appearance == DockPane.AppearanceStyle.ToolWindow)
DrawTab_ToolWindow(g, tab, rect);
else
DrawTab_Document(g, tab, rect);
}
private GraphicsPath GetTabOutline(Tab tab, bool rtlTransform, bool toScreen)
{
if (Appearance == DockPane.AppearanceStyle.ToolWindow)
return GetTabOutline_ToolWindow(tab, rtlTransform, toScreen);
else
return GetTabOutline_Document(tab, rtlTransform, toScreen, false);
}
private GraphicsPath GetTabOutline_ToolWindow(Tab tab, bool rtlTransform, bool toScreen)
{
Rectangle rect = GetTabRectangle(Tabs.IndexOf(tab));
if (rtlTransform)
rect = DrawHelper.RtlTransform(this, rect);
if (toScreen)
rect = RectangleToScreen(rect);
DrawHelper.GetRoundedCornerTab(GraphicsPath, rect, false);
return GraphicsPath;
}
private GraphicsPath GetTabOutline_Document(Tab tab, bool rtlTransform, bool toScreen, bool full)
{
int curveSize = 6;
GraphicsPath.Reset();
Rectangle rect = GetTabRectangle(Tabs.IndexOf(tab));
// Shorten TabOutline so it doesn't get overdrawn by icons next to it
rect.Intersect(TabsRectangle);
rect.Width--;
if (rtlTransform)
rect = DrawHelper.RtlTransform(this, rect);
if (toScreen)
rect = RectangleToScreen(rect);
// Draws the full angle piece for active content (or first tab)
if (tab.Content == DockPane.ActiveContent || full || Tabs.IndexOf(tab) == FirstDisplayingTab)
{
if (RightToLeft == RightToLeft.Yes)
{
if (DockPane.DockPanel.DocumentTabStripLocation == DocumentTabStripLocation.Bottom)
{
// For some reason the next line draws a line that is not hidden like it is when drawing the tab strip on top.
// It is not needed so it has been commented out.
//GraphicsPath.AddLine(rect.Right, rect.Bottom, rect.Right + rect.Height / 2, rect.Bottom);
GraphicsPath.AddLine(rect.Right + rect.Height / 2, rect.Top, rect.Right - rect.Height / 2 + curveSize / 2, rect.Bottom - curveSize / 2);
}
else
{
GraphicsPath.AddLine(rect.Right, rect.Bottom, rect.Right + rect.Height / 2, rect.Bottom);
GraphicsPath.AddLine(rect.Right + rect.Height / 2, rect.Bottom, rect.Right - rect.Height / 2 + curveSize / 2, rect.Top + curveSize / 2);
}
}
else
{
if (DockPane.DockPanel.DocumentTabStripLocation == DocumentTabStripLocation.Bottom)
{
// For some reason the next line draws a line that is not hidden like it is when drawing the tab strip on top.
// It is not needed so it has been commented out.
//GraphicsPath.AddLine(rect.Left, rect.Top, rect.Left - rect.Height / 2, rect.Top);
GraphicsPath.AddLine(rect.Left - rect.Height / 2, rect.Top, rect.Left + rect.Height / 2 - curveSize / 2, rect.Bottom - curveSize / 2);
}
else
{
GraphicsPath.AddLine(rect.Left, rect.Bottom, rect.Left - rect.Height / 2, rect.Bottom);
GraphicsPath.AddLine(rect.Left - rect.Height / 2, rect.Bottom, rect.Left + rect.Height / 2 - curveSize / 2, rect.Top + curveSize / 2);
}
}
}
// Draws the partial angle for non-active content
else
{
if (RightToLeft == RightToLeft.Yes)
{
if (DockPane.DockPanel.DocumentTabStripLocation == DocumentTabStripLocation.Bottom)
{
GraphicsPath.AddLine(rect.Right, rect.Top, rect.Right, rect.Top + rect.Height / 2);
GraphicsPath.AddLine(rect.Right, rect.Top + rect.Height / 2, rect.Right - rect.Height / 2 + curveSize / 2, rect.Bottom - curveSize / 2);
}
else
{
GraphicsPath.AddLine(rect.Right, rect.Bottom, rect.Right, rect.Bottom - rect.Height / 2);
GraphicsPath.AddLine(rect.Right, rect.Bottom - rect.Height / 2, rect.Right - rect.Height / 2 + curveSize / 2, rect.Top + curveSize / 2);
}
}
else
{
if (DockPane.DockPanel.DocumentTabStripLocation == DocumentTabStripLocation.Bottom)
{
GraphicsPath.AddLine(rect.Left, rect.Top, rect.Left, rect.Top + rect.Height / 2);
GraphicsPath.AddLine(rect.Left, rect.Top + rect.Height / 2, rect.Left + rect.Height / 2 - curveSize / 2, rect.Bottom - curveSize / 2);
}
else
{
GraphicsPath.AddLine(rect.Left, rect.Bottom, rect.Left, rect.Bottom - rect.Height / 2);
GraphicsPath.AddLine(rect.Left, rect.Bottom - rect.Height / 2, rect.Left + rect.Height / 2 - curveSize / 2, rect.Top + curveSize / 2);
}
}
}
if (RightToLeft == RightToLeft.Yes)
{
if (DockPane.DockPanel.DocumentTabStripLocation == DocumentTabStripLocation.Bottom)
{
// Draws the bottom horizontal line (short side)
GraphicsPath.AddLine(rect.Right - rect.Height / 2 - curveSize / 2, rect.Bottom, rect.Left + curveSize / 2, rect.Bottom);
// Drawing the rounded corner is not necessary. The path is automatically connected
//GraphicsPath.AddArc(new Rectangle(rect.Left, rect.Top, curveSize, curveSize), 180, 90);
}
else
{
// Draws the bottom horizontal line (short side)
GraphicsPath.AddLine(rect.Right - rect.Height / 2 - curveSize / 2, rect.Top, rect.Left + curveSize / 2, rect.Top);
GraphicsPath.AddArc(new Rectangle(rect.Left, rect.Top, curveSize, curveSize), 180, 90);
}
}
else
{
if (DockPane.DockPanel.DocumentTabStripLocation == DocumentTabStripLocation.Bottom)
{
// Draws the bottom horizontal line (short side)
GraphicsPath.AddLine(rect.Left + rect.Height / 2 + curveSize / 2, rect.Bottom, rect.Right - curveSize / 2, rect.Bottom);
// Drawing the rounded corner is not necessary. The path is automatically connected
//GraphicsPath.AddArc(new Rectangle(rect.Right - curveSize, rect.Bottom, curveSize, curveSize), 90, -90);
}
else
{
// Draws the top horizontal line (short side)
GraphicsPath.AddLine(rect.Left + rect.Height / 2 + curveSize / 2, rect.Top, rect.Right - curveSize / 2, rect.Top);
// Draws the rounded corner oppposite the angled side
GraphicsPath.AddArc(new Rectangle(rect.Right - curveSize, rect.Top, curveSize, curveSize), -90, 90);
}
}
if (Tabs.IndexOf(tab) != EndDisplayingTab &&
(Tabs.IndexOf(tab) != Tabs.Count - 1 && Tabs[Tabs.IndexOf(tab) + 1].Content == DockPane.ActiveContent)
&& !full)
{
if (RightToLeft == RightToLeft.Yes)
{
if (DockPane.DockPanel.DocumentTabStripLocation == DocumentTabStripLocation.Bottom)
{
GraphicsPath.AddLine(rect.Left, rect.Bottom - curveSize / 2, rect.Left, rect.Bottom - rect.Height / 2);
GraphicsPath.AddLine(rect.Left, rect.Bottom - rect.Height / 2, rect.Left + rect.Height / 2, rect.Top);
}
else
{
GraphicsPath.AddLine(rect.Left, rect.Top + curveSize / 2, rect.Left, rect.Top + rect.Height / 2);
GraphicsPath.AddLine(rect.Left, rect.Top + rect.Height / 2, rect.Left + rect.Height / 2, rect.Bottom);
}
}
else
{
if (DockPane.DockPanel.DocumentTabStripLocation == DocumentTabStripLocation.Bottom)
{
GraphicsPath.AddLine(rect.Right, rect.Bottom - curveSize / 2, rect.Right, rect.Bottom - rect.Height / 2);
GraphicsPath.AddLine(rect.Right, rect.Bottom - rect.Height / 2, rect.Right - rect.Height / 2, rect.Top);
}
else
{
GraphicsPath.AddLine(rect.Right, rect.Top + curveSize / 2, rect.Right, rect.Top + rect.Height / 2);
GraphicsPath.AddLine(rect.Right, rect.Top + rect.Height / 2, rect.Right - rect.Height / 2, rect.Bottom);
}
}
}
else
{
// Draw the vertical line opposite the angled side
if (RightToLeft == RightToLeft.Yes)
{
if (DockPane.DockPanel.DocumentTabStripLocation == DocumentTabStripLocation.Bottom)
GraphicsPath.AddLine(rect.Left, rect.Bottom - curveSize / 2, rect.Left, rect.Top);
else
GraphicsPath.AddLine(rect.Left, rect.Top + curveSize / 2, rect.Left, rect.Bottom);
}
else
{
if (DockPane.DockPanel.DocumentTabStripLocation == DocumentTabStripLocation.Bottom)
GraphicsPath.AddLine(rect.Right, rect.Bottom - curveSize / 2, rect.Right, rect.Top);
else
GraphicsPath.AddLine(rect.Right, rect.Top + curveSize / 2, rect.Right, rect.Bottom);
}
}
return GraphicsPath;
}
private void DrawTab_ToolWindow(Graphics g, TabVS2005 tab, Rectangle rect)
{
Rectangle rectIcon = new Rectangle(
rect.X + ToolWindowImageGapLeft,
rect.Y + rect.Height - 1 - ToolWindowImageGapBottom - ToolWindowImageHeight,
ToolWindowImageWidth, ToolWindowImageHeight);
Rectangle rectText = rectIcon;
rectText.X += rectIcon.Width + ToolWindowImageGapRight;
rectText.Width = rect.Width - rectIcon.Width - ToolWindowImageGapLeft -
ToolWindowImageGapRight - ToolWindowTextGapRight;
Rectangle rectTab = DrawHelper.RtlTransform(this, rect);
rectText = DrawHelper.RtlTransform(this, rectText);
rectIcon = DrawHelper.RtlTransform(this, rectIcon);
GraphicsPath path = GetTabOutline(tab, true, false);
if (DockPane.ActiveContent == tab.Content)
{
Color startColor = DockPane.DockPanel.Skin.DockPaneStripSkin.ToolWindowGradient.ActiveTabGradient.StartColor;
Color endColor = DockPane.DockPanel.Skin.DockPaneStripSkin.ToolWindowGradient.ActiveTabGradient.EndColor;
LinearGradientMode gradientMode = DockPane.DockPanel.Skin.DockPaneStripSkin.ToolWindowGradient.ActiveTabGradient.LinearGradientMode;
g.FillPath(new LinearGradientBrush(rectTab, startColor, endColor, gradientMode), path);
g.DrawPath(PenToolWindowTabBorder, path);
Color textColor = DockPane.DockPanel.Skin.DockPaneStripSkin.ToolWindowGradient.ActiveTabGradient.TextColor;
TextRenderer.DrawText(g, tab.Content.DockHandler.TabText, TextFont, rectText, textColor, ToolWindowTextFormat);
}
else
{
Color startColor = DockPane.DockPanel.Skin.DockPaneStripSkin.ToolWindowGradient.InactiveTabGradient.StartColor;
Color endColor = DockPane.DockPanel.Skin.DockPaneStripSkin.ToolWindowGradient.InactiveTabGradient.EndColor;
LinearGradientMode gradientMode = DockPane.DockPanel.Skin.DockPaneStripSkin.ToolWindowGradient.InactiveTabGradient.LinearGradientMode;
g.FillPath(new LinearGradientBrush(rectTab, startColor, endColor, gradientMode), path);
if (Tabs.IndexOf(DockPane.ActiveContent) != Tabs.IndexOf(tab) + 1)
{
Point pt1 = new Point(rect.Right, rect.Top + ToolWindowTabSeperatorGapTop);
Point pt2 = new Point(rect.Right, rect.Bottom - ToolWindowTabSeperatorGapBottom);
g.DrawLine(PenToolWindowTabBorder, DrawHelper.RtlTransform(this, pt1), DrawHelper.RtlTransform(this, pt2));
}
Color textColor = DockPane.DockPanel.Skin.DockPaneStripSkin.ToolWindowGradient.InactiveTabGradient.TextColor;
TextRenderer.DrawText(g, tab.Content.DockHandler.TabText, TextFont, rectText, textColor, ToolWindowTextFormat);
}
if (rectTab.Contains(rectIcon))
g.DrawIcon(tab.Content.DockHandler.Icon, rectIcon);
}
private void DrawTab_Document(Graphics g, TabVS2005 tab, Rectangle rect)
{
if (tab.TabWidth == 0)
return;
Rectangle rectIcon = new Rectangle(
rect.X + DocumentIconGapLeft,
rect.Y + rect.Height - 1 - DocumentIconGapBottom - DocumentIconHeight,
DocumentIconWidth, DocumentIconHeight);
Rectangle rectText = rectIcon;
if (DockPane.DockPanel.ShowDocumentIcon)
{
rectText.X += rectIcon.Width + DocumentIconGapRight;
rectText.Y = rect.Y;
rectText.Width = rect.Width - rectIcon.Width - DocumentIconGapLeft -
DocumentIconGapRight - DocumentTextGapRight;
rectText.Height = rect.Height;
}
else
rectText.Width = rect.Width - DocumentIconGapLeft - DocumentTextGapRight;
Rectangle rectTab = DrawHelper.RtlTransform(this, rect);
Rectangle rectBack = DrawHelper.RtlTransform(this, rect);
rectBack.Width += rect.X;
rectBack.X = 0;
rectText = DrawHelper.RtlTransform(this, rectText);
rectIcon = DrawHelper.RtlTransform(this, rectIcon);
GraphicsPath path = GetTabOutline(tab, true, false);
if (DockPane.ActiveContent == tab.Content)
{
Color startColor = DockPane.DockPanel.Skin.DockPaneStripSkin.DocumentGradient.ActiveTabGradient.StartColor;
Color endColor = DockPane.DockPanel.Skin.DockPaneStripSkin.DocumentGradient.ActiveTabGradient.EndColor;
LinearGradientMode gradientMode = DockPane.DockPanel.Skin.DockPaneStripSkin.DocumentGradient.ActiveTabGradient.LinearGradientMode;
g.FillPath(new LinearGradientBrush(rectBack, startColor, endColor, gradientMode), path);
g.DrawPath(PenDocumentTabActiveBorder, path);
Color textColor = DockPane.DockPanel.Skin.DockPaneStripSkin.DocumentGradient.ActiveTabGradient.TextColor;
if (DockPane.IsActiveDocumentPane)
TextRenderer.DrawText(g, tab.Content.DockHandler.TabText, BoldFont, rectText, textColor, DocumentTextFormat);
else
TextRenderer.DrawText(g, tab.Content.DockHandler.TabText, TextFont, rectText, textColor, DocumentTextFormat);
}
else
{
Color startColor = DockPane.DockPanel.Skin.DockPaneStripSkin.DocumentGradient.InactiveTabGradient.StartColor;
Color endColor = DockPane.DockPanel.Skin.DockPaneStripSkin.DocumentGradient.InactiveTabGradient.EndColor;
LinearGradientMode gradientMode = DockPane.DockPanel.Skin.DockPaneStripSkin.DocumentGradient.InactiveTabGradient.LinearGradientMode;
g.FillPath(new LinearGradientBrush(rectBack, startColor, endColor, gradientMode), path);
g.DrawPath(PenDocumentTabInactiveBorder, path);
Color textColor = DockPane.DockPanel.Skin.DockPaneStripSkin.DocumentGradient.InactiveTabGradient.TextColor;
TextRenderer.DrawText(g, tab.Content.DockHandler.TabText, TextFont, rectText, textColor, DocumentTextFormat);
}
if (rectTab.Contains(rectIcon) && DockPane.DockPanel.ShowDocumentIcon)
g.DrawIcon(tab.Content.DockHandler.Icon, rectIcon);
}
private void WindowList_Click(object sender, EventArgs e)
{
SelectMenu.Items.Clear();
foreach (TabVS2005 tab in Tabs)
{
IDockContent content = tab.Content;
ToolStripItem item = SelectMenu.Items.Add(content.DockHandler.TabText, content.DockHandler.Icon.ToBitmap());
item.Tag = tab.Content;
item.Click += new EventHandler(ContextMenuItem_Click);
}
var workingArea = Screen.GetWorkingArea(ButtonWindowList.PointToScreen(new Point(ButtonWindowList.Width / 2, ButtonWindowList.Height / 2)));
var menu = new Rectangle(ButtonWindowList.PointToScreen(new Point(0, ButtonWindowList.Location.Y + ButtonWindowList.Height)), SelectMenu.Size);
var menuMargined = new Rectangle(menu.X - SelectMenuMargin, menu.Y - SelectMenuMargin, menu.Width + SelectMenuMargin, menu.Height + SelectMenuMargin);
if (workingArea.Contains(menuMargined))
{
SelectMenu.Show(menu.Location);
}
else
{
var newPoint = menu.Location;
newPoint.X = DrawHelper.Balance(SelectMenu.Width, SelectMenuMargin, newPoint.X, workingArea.Left, workingArea.Right);
newPoint.Y = DrawHelper.Balance(SelectMenu.Size.Height, SelectMenuMargin, newPoint.Y, workingArea.Top, workingArea.Bottom);
var button = ButtonWindowList.PointToScreen(new Point(0, ButtonWindowList.Height));
if (newPoint.Y < button.Y)
{
// flip the menu up to be above the button.
newPoint.Y = button.Y - ButtonWindowList.Height;
SelectMenu.Show(newPoint, ToolStripDropDownDirection.AboveRight);
}
else
{
SelectMenu.Show(newPoint);
}
}
}
private void ContextMenuItem_Click(object sender, EventArgs e)
{
ToolStripMenuItem item = sender as ToolStripMenuItem;
if (item != null)
{
IDockContent content = (IDockContent)item.Tag;
DockPane.ActiveContent = content;
}
}
private void SetInertButtons()
{
if (Appearance == DockPane.AppearanceStyle.ToolWindow)
{
if (m_buttonClose != null)
m_buttonClose.Left = -m_buttonClose.Width;
if (m_buttonWindowList != null)
m_buttonWindowList.Left = -m_buttonWindowList.Width;
}
else
{
ButtonClose.Enabled = DockPane.ActiveContent == null ? true : DockPane.ActiveContent.DockHandler.CloseButton;
m_closeButtonVisible = DockPane.ActiveContent == null ? true : DockPane.ActiveContent.DockHandler.CloseButtonVisible;
ButtonClose.Visible = m_closeButtonVisible;
ButtonClose.RefreshChanges();
ButtonWindowList.RefreshChanges();
}
}
protected override void OnLayout(LayoutEventArgs levent)
{
if (Appearance == DockPane.AppearanceStyle.Document)
{
LayoutButtons();
OnRefreshChanges();
}
base.OnLayout(levent);
}
private void LayoutButtons()
{
Rectangle rectTabStrip = TabStripRectangle;
// Set position and size of the buttons
int buttonWidth = ButtonClose.Image.Width;
int buttonHeight = ButtonClose.Image.Height;
int height = rectTabStrip.Height - DocumentButtonGapTop - DocumentButtonGapBottom;
if (buttonHeight < height)
{
buttonWidth = buttonWidth * (height / buttonHeight);
buttonHeight = height;
}
Size buttonSize = new Size(buttonWidth, buttonHeight);
int x = rectTabStrip.X + rectTabStrip.Width - DocumentTabGapLeft
- DocumentButtonGapRight - buttonWidth;
int y = rectTabStrip.Y + DocumentButtonGapTop;
Point point = new Point(x, y);
ButtonClose.Bounds = DrawHelper.RtlTransform(this, new Rectangle(point, buttonSize));
// If the close button is not visible draw the window list button overtop.
// Otherwise it is drawn to the left of the close button.
if (m_closeButtonVisible)
point.Offset(-(DocumentButtonGapBetween + buttonWidth), 0);
ButtonWindowList.Bounds = DrawHelper.RtlTransform(this, new Rectangle(point, buttonSize));
}
private void Close_Click(object sender, EventArgs e)
{
DockPane.CloseActiveContent();
}
protected internal override int HitTest(Point ptMouse)
{
if (!TabsRectangle.Contains(ptMouse))
return -1;
foreach (Tab tab in Tabs)
{
GraphicsPath path = GetTabOutline(tab, true, false);
if (path.IsVisible(ptMouse))
return Tabs.IndexOf(tab);
}
return -1;
}
protected override Rectangle GetTabBounds(Tab tab)
{
GraphicsPath path = GetTabOutline(tab, true, false);
RectangleF rectangle = path.GetBounds();
return new Rectangle((int)rectangle.Left, (int)rectangle.Top, (int)rectangle.Width, (int)rectangle.Height);
}
protected override void OnMouseHover(EventArgs e)
{
int index = HitTest(PointToClient(Control.MousePosition));
string toolTip = string.Empty;
base.OnMouseHover(e);
if (index != -1)
{
TabVS2005 tab = Tabs[index] as TabVS2005;
if (!String.IsNullOrEmpty(tab.Content.DockHandler.ToolTipText))
toolTip = tab.Content.DockHandler.ToolTipText;
else if (tab.MaxWidth > tab.TabWidth)
toolTip = tab.Content.DockHandler.TabText;
}
if (m_toolTip.GetToolTip(this) != toolTip)
{
m_toolTip.Active = false;
m_toolTip.SetToolTip(this, toolTip);
m_toolTip.Active = true;
}
// requires further tracking of mouse hover behavior,
ResetMouseEventArgs();
}
protected override void OnRightToLeftChanged(EventArgs e)
{
base.OnRightToLeftChanged(e);
PerformLayout();
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Globalization;
namespace System.Management
{
/// <summary>
/// <para> Provides methods to convert DMTF datetime and time interval to CLR compliant
/// <see cref='System.DateTime'/> and <see cref='System.TimeSpan'/> format and vice versa.
/// </para>
/// </summary>
/// <example>
/// <code lang='C#'>
/// using System;
/// using System.Management;
///
/// // The sample below demonstrates the various conversions that can be done using ManagementDateTimeConverter class
/// class Sample_ManagementDateTimeConverterClass
/// {
/// public static int Main(string[] args)
/// {
/// string dmtfDate = "20020408141835.999999-420";
/// string dmtfTimeInterval = "00000010122532:123456:000";
///
/// // Converting DMTF datetime to System.DateTime
/// DateTime dt = ManagementDateTimeConverter.ToDateTime(dmtfDate);
///
/// // Converting System.DateTime to DMTF datetime
/// string dmtfDate = ManagementDateTimeConverter.ToDateTime(DateTime.Now);
///
/// // Converting DMTF timeinterval to System.TimeSpan
/// System.TimeSpan tsRet = ManagementDateTimeConverter. ToTimeSpan(dmtfTimeInterval);
///
/// //Converting System.TimeSpan to DMTF time interval format
/// System.TimeSpan ts = new System.TimeSpan(10,12,25,32,456);
/// string dmtfTimeInt = ManagementDateTimeConverter.ToDmtfTimeInterval(ts);
///
/// return 0;
///
/// }
/// }
/// </code>
/// <code lang='VB'>
/// Imports System
/// Imports System.Management
///
/// 'The sample below demonstrates the various conversions that can be done using ManagementDateTimeConverter class
/// Class Sample_ManagementClass
/// Overloads Public Shared Function Main(args() As String) As Integer
/// Dim dmtfDate As String = "20020408141835.999999-420"
/// Dim dmtfTimeInterval As String = "00000010122532:123456:000"
///
/// 'Converting DMTF datetime and intervals to System.DateTime
/// Dim dt As DateTime = ManagementDateTimeConverter.ToDateTime(dmtfDate)
///
/// 'Converting System.DateTime to DMTF datetime
/// dmtfDate = ManagementDateTimeConverter.ToDateTime(DateTime.Now)
///
/// ' Converting DMTF timeinterval to System.TimeSpan
/// Dim tsRet As System.TimeSpan = ManagementDateTimeConverter.ToTimeSpan(dmtfTimeInterval)
///
/// 'Converting System.TimeSpan to DMTF time interval format
/// Dim ts As System.TimeSpan = New System.TimeSpan(10, 12, 25, 32, 456)
/// String dmtfTimeInt = ManagementDateTimeConverter.ToDmtfTimeInterval(ts)
///
/// Return 0
/// End Function
/// End Class
///
/// </code>
/// </example>
public sealed class ManagementDateTimeConverter
{
// constants
private const int SIZEOFDMTFDATETIME = 25;
private const int MAXSIZE_UTC_DMTF = 999;
private const long MAXDATE_INTIMESPAN = 99999999;
private ManagementDateTimeConverter()
{
}
/// <summary>
/// <para>Converts a given DMTF datetime to <see cref='System.DateTime'/> object. The returned DateTime will be in the
/// current TimeZone of the system.</para>
/// </summary>
/// <param name='dmtfDate'>A string representing the datetime in DMTF format.</param>
/// <returns>
/// <para>A <see cref='System.DateTime'/> object that represents the given DMTF datetime.</para>
/// </returns>
/// <remarks>
/// <para> Date and time in WMI is represented in DMTF datetime format. This format is explained in WMI SDK documentation.
/// DMTF datetime string has an UTC offset which this datetime string represents.
/// During conversion to <see cref='System.DateTime'/>, UTC offset is used to convert the date to the
/// current timezone. According to DMTF format a particular field can be represented by the character
/// '*'. This will be converted to the MinValue of this field that can be represented in <see cref='System.DateTime'/>.
/// </para>
/// </remarks>
/// <example>
/// <code lang='C#'>
/// // Convert a DMTF datetime to System.DateTime
/// DateTime date = ManagementDateTimeConverter.ToDateTime("20020408141835.999999-420");
/// </code>
/// <code lang='VB'>
/// ' Convert a DMTF datetime to System.DateTime
/// Dim date as DateTime = ManagementDateTimeConverter.ToDateTime("20020408141835.999999-420")
/// </code>
/// </example>
public static DateTime ToDateTime(string dmtfDate)
{
int year = DateTime.MinValue.Year;
int month = DateTime.MinValue.Month;
int day = DateTime.MinValue.Day;
int hour = DateTime.MinValue.Hour;
int minute = DateTime.MinValue.Minute;
int second = DateTime.MinValue.Second;
string dmtf = dmtfDate;
// If the string passed is empty or null then throw
// an exception
if(dmtf == null)
{
throw new ArgumentOutOfRangeException(nameof(dmtfDate));
}
if (dmtf.Length == 0)
{
throw new ArgumentOutOfRangeException(nameof(dmtfDate));
}
// if the length of the string is not equal to the
// standard length of the DMTF datetime then throw an exception
if(dmtf.Length != SIZEOFDMTFDATETIME)
{
throw new ArgumentOutOfRangeException(nameof(dmtfDate));
}
IFormatProvider frmInt32 = (IFormatProvider)CultureInfo.InvariantCulture.GetFormat(typeof(int));
long ticks = 0;
int utcOffset = 0;
try
{
var tempString = dmtf.Substring(0, 4);
if (("****" != tempString))
{
year = int.Parse(tempString,frmInt32);
}
tempString = dmtf.Substring(4, 2);
if (("**" != tempString))
{
month = int.Parse(tempString,frmInt32);
}
tempString = dmtf.Substring(6, 2);
if (("**" != tempString))
{
day = int.Parse(tempString,frmInt32);
}
tempString = dmtf.Substring(8, 2);
if (("**" != tempString))
{
hour = int.Parse(tempString,frmInt32);
}
tempString = dmtf.Substring(10, 2);
if (("**" != tempString))
{
minute = int.Parse(tempString,frmInt32);
}
tempString = dmtf.Substring(12, 2);
if (("**" != tempString))
{
second = int.Parse(tempString,frmInt32);
}
tempString = dmtf.Substring(15, 6);
if (("******" != tempString))
{
ticks = (long.Parse(tempString,(IFormatProvider)CultureInfo.InvariantCulture.GetFormat(typeof(long)))) * (TimeSpan.TicksPerMillisecond/1000);
}
tempString = dmtf.Substring(22, 3);
if (("***" != tempString))
{
tempString = dmtf.Substring(21, 4);
utcOffset = int.Parse(tempString,frmInt32);
}
if( year < 0 || month < 0 || day < 0 || hour < 0 || minute < 0 || second < 0 || ticks < 0)
{
throw new ArgumentOutOfRangeException(nameof(dmtfDate));
}
}
catch
{
throw new ArgumentOutOfRangeException(nameof(dmtfDate));
}
// Construct a new System.DateTime object, netfx uses date kind unspecified so use the same
var datetime = new DateTime(year, month, day, hour, minute, second, 0, DateTimeKind.Unspecified);
// Then add the ticks calculated from the microseconds
datetime = datetime.AddTicks(ticks);
// Then adjust the offset, using a manual calulation to keep the same possible range as netfx
datetime = datetime.AddMinutes(-(utcOffset - TimeZoneInfo.Local.GetUtcOffset(datetime).Ticks / TimeSpan.TicksPerMinute));
return datetime;
}
/// <summary>
/// <para>Converts a given <see cref='System.DateTime'/> object to DMTF format.</para>
///
/// </summary>
/// <param name='date'>A <see cref='System.DateTime'/> object representing the datetime to be converted to DMTF datetime.</param>
/// <returns>
/// <para>A string that represents the DMTF datetime for the given DateTime object.</para>
/// </returns>
/// <remarks>
/// <para> Date and time in WMI is represented in DMTF datetime format. This format is explained in WMI SDK documentation.
/// The DMTF datetime string represented will be with respect to the UTC offset of the
/// current timezone. The lowest precision in DMTF is microseconds and
/// in <see cref='System.DateTime'/> is Ticks , which is equivalent to 100 of nanoseconds.
/// During conversion these Ticks are converted to microseconds and rounded
/// off to the the nearest microsecond.
/// </para>
/// </remarks>
/// <example>
/// <code lang='C#'>
/// // Convert the current time in System.DateTime to DMTF format
/// string dmtfDateTime = ManagementDateTimeConverter.ToDmtfDateTime(DateTime.Now);
/// </code>
/// <code lang='VB'>
/// ' Convert the current time in System.DateTime to DMTF format
/// Dim dmtfDateTime as String = ManagementDateTimeConverter.ToDmtfDateTime(DateTime.Now)
/// </code>
/// </example>
public static string ToDmtfDateTime(DateTime date)
{
string UtcString = string.Empty;
// Fill up the UTC field in the DMTF date with the current
// zones UTC value. If date kind is UTC use offset of zero to match netfx (i.e.: TimeZone.GetUtcOffset)
TimeSpan tickOffset = date.Kind == DateTimeKind.Utc ? TimeSpan.Zero : TimeZoneInfo.Local.GetUtcOffset(date);
long OffsetMins = (tickOffset.Ticks / System.TimeSpan.TicksPerMinute);
IFormatProvider frmInt32 = (IFormatProvider)CultureInfo.InvariantCulture.GetFormat(typeof(int));
// If the offset is more than that what can be specified in DMTF format, then
// convert the date to UniversalTime
if(Math.Abs(OffsetMins) > MAXSIZE_UTC_DMTF)
{
date = date.ToUniversalTime();
UtcString = "+000";
}
else
if ((tickOffset.Ticks >= 0))
{
UtcString = "+" + ((tickOffset.Ticks / System.TimeSpan.TicksPerMinute)).ToString(frmInt32).PadLeft(3,'0');
}
else
{
string strTemp = OffsetMins.ToString(frmInt32);
UtcString = "-" + strTemp.Substring(1, strTemp.Length-1).PadLeft(3,'0');
}
string dmtfDateTime = date.Year.ToString(frmInt32).PadLeft(4,'0');
dmtfDateTime = (dmtfDateTime + date.Month.ToString(frmInt32).PadLeft(2, '0'));
dmtfDateTime = (dmtfDateTime + date.Day.ToString(frmInt32).PadLeft(2, '0'));
dmtfDateTime = (dmtfDateTime + date.Hour.ToString(frmInt32).PadLeft(2, '0'));
dmtfDateTime = (dmtfDateTime + date.Minute.ToString(frmInt32).PadLeft(2, '0'));
dmtfDateTime = (dmtfDateTime + date.Second.ToString(frmInt32).PadLeft(2, '0'));
dmtfDateTime = (dmtfDateTime + ".");
// Construct a DateTime with with the precision to Second as same as the passed DateTime and so get
// the ticks difference so that the microseconds can be calculated
DateTime dtTemp = new DateTime(date.Year ,date.Month,date.Day ,date.Hour ,date.Minute ,date.Second,0);
long microsec = ((date.Ticks-dtTemp.Ticks) * 1000) / System.TimeSpan.TicksPerMillisecond;
// fill the microseconds field
string strMicrosec = microsec.ToString((IFormatProvider)CultureInfo.InvariantCulture.GetFormat(typeof(long)));
if(strMicrosec.Length > 6)
{
strMicrosec = strMicrosec.Substring(0,6);
}
dmtfDateTime = dmtfDateTime + strMicrosec.PadLeft(6,'0');
// adding the UTC offset
dmtfDateTime = dmtfDateTime + UtcString;
return dmtfDateTime;
}
/// <summary>
/// <para>Converts a given DMTF time interval to <see cref='System.TimeSpan'/> object.</para>
/// </summary>
/// <param name='dmtfTimespan'>A string represesentation of the DMTF time interval.</param>
/// <returns>
/// <para>A <see cref='System.TimeSpan'/> object that represents the given DMTF time interval.</para>
/// </returns>
/// <remarks>
/// <para> Time interval in WMI is represented in DMTF format. This format is explained in WMI SDK documentation.
/// If the DMTF time interval value is more than that of
/// <see cref='System.TimeSpan.MaxValue'/> then <see cref='System.ArgumentOutOfRangeException'/> is thrown.
/// </para>
/// </remarks>
/// <example>
/// <code lang='C#'>
/// // Convert a DMTF time interval to System.TimeSpan
/// TimeSpan dmtfTimeInterval = ManagementDateTimeConverter.ToTimeSpan("00000010122532:123456:000");
/// </code>
/// <code lang='VB'>
/// ' Convert a DMTF time interval to System.TimeSpan
/// Dim ts as TimeSpan = ManagementDateTimeConverter.ToTimeSpan("00000010122532:123456:000")
/// </code>
/// </example>
public static TimeSpan ToTimeSpan(string dmtfTimespan)
{
int days = 0;
int hours = 0;
int minutes = 0;
int seconds = 0;
IFormatProvider frmInt32 = (IFormatProvider)CultureInfo.InvariantCulture.GetFormat(typeof(int));
string dmtfts = dmtfTimespan;
TimeSpan timespan = TimeSpan.MinValue;
if (dmtfts == null)
{
throw new System.ArgumentOutOfRangeException(nameof(dmtfTimespan));
}
if (dmtfts.Length == 0)
{
throw new System.ArgumentOutOfRangeException(nameof(dmtfTimespan));
}
if(dmtfts.Length != SIZEOFDMTFDATETIME)
{
throw new System.ArgumentOutOfRangeException(nameof(dmtfTimespan));
}
if(dmtfts.Substring(21,4) != ":000")
{
throw new System.ArgumentOutOfRangeException(nameof(dmtfTimespan));
}
long ticks = 0;
try
{
string tempString = string.Empty;
tempString = dmtfts.Substring(0, 8);
days = int.Parse(tempString,frmInt32);
tempString = dmtfts.Substring(8, 2);
hours = int.Parse(tempString,frmInt32);
tempString = dmtfts.Substring(10, 2);
minutes = int.Parse(tempString,frmInt32);
tempString = dmtfts.Substring(12, 2);
seconds = int.Parse(tempString,frmInt32);
tempString = dmtfts.Substring(15, 6);
ticks = (long.Parse(tempString,(IFormatProvider)CultureInfo.InvariantCulture.GetFormat(typeof(long)))) * (System.TimeSpan.TicksPerMillisecond/1000);
}
catch
{
throw new System.ArgumentOutOfRangeException(nameof(dmtfTimespan));
}
if( days < 0 || hours < 0 || minutes < 0 || seconds < 0 || ticks < 0 )
{
throw new System.ArgumentOutOfRangeException(nameof(dmtfTimespan));
}
timespan = new System.TimeSpan(days, hours, minutes, seconds, 0);
// Get a timepan for the additional ticks obtained for the microsecond part of DMTF time interval
// and then add it to the the original timespan
TimeSpan tsTemp = System.TimeSpan.FromTicks(ticks);
timespan = timespan + tsTemp;
return timespan;
}
/// <summary>
/// <para>Converts a given <see cref='System.TimeSpan'/> object to DMTF time interval.</para>
/// </summary>
/// <param name='timespan'> A <see cref='System.TimeSpan'/> object representing the datetime to be converted to DMTF time interval.
/// </param>
/// <returns>
/// <para>A string that represents the DMTF time interval for the given TimeSpan object.</para>
/// </returns>
/// <remarks>
/// <para> Time interval in WMI is represented in DMTF datetime format. This format
/// is explained in WMI SDK documentation. The lowest precision in
/// DMTF is microseconds and in <see cref='System.TimeSpan'/> is Ticks , which is equivalent
/// to 100 of nanoseconds.During conversion these Ticks are converted to
/// microseconds and rounded off to the the nearest microsecond.
/// </para>
/// </remarks>
/// <example>
/// <code lang='C#'>
/// // Construct a Timespan object and convert it to DMTF format
/// System.TimeSpan ts = new System.TimeSpan(10,12,25,32,456);
/// String dmtfTimeInterval = ManagementDateTimeConverter.ToDmtfTimeInterval(ts);
/// </code>
/// <code lang='VB'>
/// // Construct a Timespan object and convert it to DMTF format
/// Dim ts as System.TimeSpan = new System.TimeSpan(10,12,25,32,456)
/// Dim dmtfTimeInterval as String = ManagementDateTimeConverter.ToDmtfTimeInterval(ts)
/// </code>
/// </example>
public static string ToDmtfTimeInterval(TimeSpan timespan)
{
string dmtftimespan = timespan.Days.ToString((IFormatProvider)CultureInfo.InvariantCulture.GetFormat(typeof(System.Int32))).PadLeft(8,'0');
IFormatProvider frmInt32 = (IFormatProvider)CultureInfo.InvariantCulture.GetFormat(typeof(int));
// Days that can be represented is more than what can be represented
// then throw an exception
// and also negative timespan cannot be represented in DMTF
if(timespan.Days > MAXDATE_INTIMESPAN || timespan < TimeSpan.Zero)
{
throw new System.ArgumentOutOfRangeException();
}
dmtftimespan = (dmtftimespan + timespan.Hours.ToString(frmInt32).PadLeft(2, '0'));
dmtftimespan = (dmtftimespan + timespan.Minutes.ToString(frmInt32).PadLeft(2, '0'));
dmtftimespan = (dmtftimespan + timespan.Seconds.ToString(frmInt32).PadLeft(2, '0'));
dmtftimespan = (dmtftimespan + ".");
// Construct a DateTime with with the precision to Second as same as the passed DateTime and so get
// the ticks difference so that the microseconds can be calculated
TimeSpan tsTemp = new TimeSpan(timespan.Days ,timespan.Hours,timespan.Minutes ,timespan.Seconds ,0);
long microsec = ((timespan.Ticks-tsTemp.Ticks) * 1000) / System.TimeSpan.TicksPerMillisecond;
// fill the microseconds field
string strMicrosec = microsec.ToString((IFormatProvider)CultureInfo.InvariantCulture.GetFormat(typeof(long)));
if(strMicrosec.Length > 6)
{
strMicrosec = strMicrosec.Substring(0,6);
}
dmtftimespan = dmtftimespan + strMicrosec.PadLeft(6,'0');
dmtftimespan = dmtftimespan + ":000";
return dmtftimespan;
}
} // ManagementDateTimeConverter
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the MIT license. See License.txt in the project root for license information.
using System.Threading.Tasks;
using Test.Utilities;
using Xunit;
using VerifyCS = Test.Utilities.CSharpCodeFixVerifier<
Microsoft.NetCore.Analyzers.Runtime.TestForEmptyStringsUsingStringLengthAnalyzer,
Microsoft.NetCore.CSharp.Analyzers.Runtime.CSharpTestForEmptyStringsUsingStringLengthFixer>;
using VerifyVB = Test.Utilities.VisualBasicCodeFixVerifier<
Microsoft.NetCore.Analyzers.Runtime.TestForEmptyStringsUsingStringLengthAnalyzer,
Microsoft.NetCore.VisualBasic.Analyzers.Runtime.BasicTestForEmptyStringsUsingStringLengthFixer>;
namespace Microsoft.NetCore.Analyzers.Runtime.UnitTests
{
public class TestForEmptyStringsUsingStringLengthFixerTests
{
private const int c_StringLengthCodeActionIndex = 1;
[Fact, WorkItem(3686, "https://github.com/dotnet/roslyn-analyzers/pull/3686")]
public async Task CA1820_FixTestEmptyStringsUsingIsNullOrEmpty_WhenStringIsLiteralAsync()
{
await VerifyCS.VerifyCodeFixAsync(@"
public class A
{
public bool Compare(string s)
{
return [|s == """"|];
}
public bool CompareEmptyIsLeft(string s)
{
return [|"""" == s|];
}
}
", @"
public class A
{
public bool Compare(string s)
{
return string.IsNullOrEmpty(s);
}
public bool CompareEmptyIsLeft(string s)
{
return string.IsNullOrEmpty(s);
}
}
");
await VerifyVB.VerifyCodeFixAsync(@"
Public Class A
Public Function Compare(s As String) As Boolean
Return [|s = """"|]
End Function
Public Function CompareEmptyIsLeft(s As String) As Boolean
Return [|"""" = s|]
End Function
End Class
", @"
Public Class A
Public Function Compare(s As String) As Boolean
Return String.IsNullOrEmpty(s)
End Function
Public Function CompareEmptyIsLeft(s As String) As Boolean
Return String.IsNullOrEmpty(s)
End Function
End Class
");
}
[Fact]
public async Task CA1820_FixTestEmptyStringsUsingStringLength_WhenStringIsLiteralAsync()
{
await new VerifyCS.Test
{
TestState =
{
Sources =
{
@"
public class A
{
public bool Compare(string s)
{
return [|s == """"|];
}
}
",
},
},
FixedState =
{
Sources =
{
@"
public class A
{
public bool Compare(string s)
{
return s.Length == 0;
}
}
",
},
},
CodeActionIndex = c_StringLengthCodeActionIndex,
CodeActionEquivalenceKey = "TestForEmptyStringCorrectlyUsingStringLength",
}.RunAsync();
await new VerifyVB.Test
{
TestState =
{
Sources =
{
@"
Public Class A
Public Function Compare(s As String) As Boolean
Return [|s = """"|]
End Function
End Class
",
},
},
FixedState =
{
Sources =
{
@"
Public Class A
Public Function Compare(s As String) As Boolean
Return s.Length = 0
End Function
End Class
",
},
},
CodeActionIndex = c_StringLengthCodeActionIndex,
CodeActionEquivalenceKey = "TestForEmptyStringCorrectlyUsingStringLength",
}.RunAsync();
}
[Fact]
public async Task CA1820_FixTestEmptyStringsUsingIsNullOrEmptyAsync()
{
await VerifyCS.VerifyCodeFixAsync(@"
public class A
{
public bool Compare(string s)
{
return [|s == string.Empty|];
}
}
", @"
public class A
{
public bool Compare(string s)
{
return string.IsNullOrEmpty(s);
}
}
");
await VerifyVB.VerifyCodeFixAsync(@"
Public Class A
Public Function Compare(s As String) As Boolean
Return [|s = String.Empty|]
End Function
End Class
", @"
Public Class A
Public Function Compare(s As String) As Boolean
Return String.IsNullOrEmpty(s)
End Function
End Class
");
}
[Fact]
public async Task CA1820_FixTestEmptyStringsUsingStringLengthAsync()
{
await new VerifyCS.Test
{
TestState =
{
Sources =
{
@"
public class A
{
public bool Compare(string s)
{
return [|s == string.Empty|];
}
}
",
},
},
FixedState =
{
Sources =
{
@"
public class A
{
public bool Compare(string s)
{
return s.Length == 0;
}
}
",
},
},
CodeActionIndex = c_StringLengthCodeActionIndex,
CodeActionEquivalenceKey = "TestForEmptyStringCorrectlyUsingStringLength",
}.RunAsync();
await new VerifyVB.Test
{
TestState =
{
Sources =
{
@"
Public Class A
Public Function Compare(s As String) As Boolean
Return [|s = String.Empty|]
End Function
End Class
",
},
},
FixedState =
{
Sources =
{
@"
Public Class A
Public Function Compare(s As String) As Boolean
Return s.Length = 0
End Function
End Class
",
},
},
CodeActionIndex = c_StringLengthCodeActionIndex,
CodeActionEquivalenceKey = "TestForEmptyStringCorrectlyUsingStringLength",
}.RunAsync();
}
[Fact]
public async Task CA1820_FixTestEmptyStringsUsingIsNullOrEmptyComparisonOnRightAsync()
{
await VerifyCS.VerifyCodeFixAsync(@"
public class A
{
public bool Compare(string s)
{
return [|string.Empty == s|];
}
}
", @"
public class A
{
public bool Compare(string s)
{
return string.IsNullOrEmpty(s);
}
}
");
await VerifyVB.VerifyCodeFixAsync(@"
Public Class A
Public Function Compare(s As String) As Boolean
Return [|String.Empty = s|]
End Function
End Class
", @"
Public Class A
Public Function Compare(s As String) As Boolean
Return String.IsNullOrEmpty(s)
End Function
End Class
");
}
[Fact]
public async Task CA1820_FixTestEmptyStringsUsingStringLengthComparisonOnRightAsync()
{
await new VerifyCS.Test
{
TestState =
{
Sources =
{
@"
public class A
{
public bool Compare(string s)
{
return [|string.Empty == s|];
}
}
",
},
},
FixedState =
{
Sources =
{
@"
public class A
{
public bool Compare(string s)
{
return 0 == s.Length;
}
}
",
},
},
CodeActionIndex = c_StringLengthCodeActionIndex,
CodeActionEquivalenceKey = "TestForEmptyStringCorrectlyUsingStringLength",
}.RunAsync();
await new VerifyVB.Test
{
TestState =
{
Sources =
{
@"
Public Class A
Public Function Compare(s As String) As Boolean
Return [|String.Empty = s|]
End Function
End Class
",
},
},
FixedState =
{
Sources =
{
@"
Public Class A
Public Function Compare(s As String) As Boolean
Return 0 = s.Length
End Function
End Class
",
},
},
CodeActionIndex = c_StringLengthCodeActionIndex,
CodeActionEquivalenceKey = "TestForEmptyStringCorrectlyUsingStringLength",
}.RunAsync();
}
[Fact]
public async Task CA1820_FixInequalityTestEmptyStringsUsingIsNullOrEmptyAsync()
{
await VerifyCS.VerifyCodeFixAsync(@"
public class A
{
public bool Compare(string s)
{
return [|s != string.Empty|];
}
}
", @"
public class A
{
public bool Compare(string s)
{
return !string.IsNullOrEmpty(s);
}
}
");
await VerifyVB.VerifyCodeFixAsync(@"
Public Class A
Public Function Compare(s As String) As Boolean
Return [|s <> String.Empty|]
End Function
End Class
", @"
Public Class A
Public Function Compare(s As String) As Boolean
Return Not String.IsNullOrEmpty(s)
End Function
End Class
");
}
[Fact]
public async Task CA1820_FixInequalityTestEmptyStringsUsingStringLengthAsync()
{
await new VerifyCS.Test
{
TestState =
{
Sources =
{
@"
public class A
{
public bool Compare(string s)
{
return [|s != string.Empty|];
}
}
",
},
},
FixedState =
{
Sources =
{
@"
public class A
{
public bool Compare(string s)
{
return s.Length != 0;
}
}
",
},
},
CodeActionIndex = c_StringLengthCodeActionIndex,
CodeActionEquivalenceKey = "TestForEmptyStringCorrectlyUsingStringLength",
}.RunAsync();
await new VerifyVB.Test
{
TestState =
{
Sources =
{
@"
Public Class A
Public Function Compare(s As String) As Boolean
Return [|s <> String.Empty|]
End Function
End Class
",
},
},
FixedState =
{
Sources =
{
@"
Public Class A
Public Function Compare(s As String) As Boolean
Return s.Length <> 0
End Function
End Class
",
},
},
CodeActionIndex = c_StringLengthCodeActionIndex,
CodeActionEquivalenceKey = "TestForEmptyStringCorrectlyUsingStringLength",
}.RunAsync();
}
[Fact]
public async Task CA1820_FixInequalityTestEmptyStringsUsingIsNullOrEmptyComparisonOnRightAsync()
{
await VerifyCS.VerifyCodeFixAsync(@"
public class A
{
public bool Compare(string s)
{
return [|string.Empty != s|];
}
}
", @"
public class A
{
public bool Compare(string s)
{
return !string.IsNullOrEmpty(s);
}
}
");
await VerifyVB.VerifyCodeFixAsync(@"
Public Class A
Public Function Compare(s As String) As Boolean
Return [|String.Empty <> s|]
End Function
End Class
", @"
Public Class A
Public Function Compare(s As String) As Boolean
Return Not String.IsNullOrEmpty(s)
End Function
End Class
");
}
[Fact]
public async Task CA1820_FixInequalityTestEmptyStringsUsingStringLengthComparisonOnRightAsync()
{
await new VerifyCS.Test
{
TestState =
{
Sources =
{
@"
public class A
{
public bool Compare(string s)
{
return [|string.Empty != s|];
}
}
",
},
},
FixedState =
{
Sources =
{
@"
public class A
{
public bool Compare(string s)
{
return 0 != s.Length;
}
}
",
},
},
CodeActionIndex = c_StringLengthCodeActionIndex,
CodeActionEquivalenceKey = "TestForEmptyStringCorrectlyUsingStringLength",
}.RunAsync();
await new VerifyVB.Test
{
TestState =
{
Sources =
{
@"
Public Class A
Public Function Compare(s As String) As Boolean
Return [|String.Empty <> s|]
End Function
End Class
",
},
},
FixedState =
{
Sources =
{
@"
Public Class A
Public Function Compare(s As String) As Boolean
Return 0 <> s.Length
End Function
End Class
",
},
},
CodeActionIndex = c_StringLengthCodeActionIndex,
CodeActionEquivalenceKey = "TestForEmptyStringCorrectlyUsingStringLength",
}.RunAsync();
}
[Fact]
public async Task CA1820_FixForComparisonWithEmptyStringInFunctionArgumentAsync()
{
await VerifyCS.VerifyCodeFixAsync(@"
public class A
{
string _s = string.Empty;
public void F()
{
G([|_s == string.Empty|]);
}
public void G(bool comparison) {}
}
", @"
public class A
{
string _s = string.Empty;
public void F()
{
G(string.IsNullOrEmpty(_s));
}
public void G(bool comparison) {}
}
");
await VerifyVB.VerifyCodeFixAsync(@"
Public Class A
Private _s As String = String.Empty
Public Sub F()
G([|_s = String.Empty|])
End Sub
Public Sub G(comparison As Boolean)
End Sub
End Class
", @"
Public Class A
Private _s As String = String.Empty
Public Sub F()
G(String.IsNullOrEmpty(_s))
End Sub
Public Sub G(comparison As Boolean)
End Sub
End Class
");
}
[Fact]
public async Task CA1820_FixForComparisonWithEmptyStringInTernaryOperatorAsync()
{
await VerifyCS.VerifyCodeFixAsync(@"
public class A
{
string _s = string.Empty;
public int F()
{
return [|_s == string.Empty|] ? 1 : 0;
}
}
", @"
public class A
{
string _s = string.Empty;
public int F()
{
return string.IsNullOrEmpty(_s) ? 1 : 0;
}
}
");
// VB doesn't have the ternary operator, but we add this test for symmetry.
await VerifyVB.VerifyCodeFixAsync(@"
Public Class A
Private _s As String = String.Empty
Public Function F() As Integer
Return If([|_s = String.Empty|], 1, 0)
End Function
End Class
", @"
Public Class A
Private _s As String = String.Empty
Public Function F() As Integer
Return If(String.IsNullOrEmpty(_s), 1, 0)
End Function
End Class
");
}
[Fact]
public async Task CA1820_FixForComparisonWithEmptyStringInThrowStatementAsync()
{
await VerifyCS.VerifyCodeFixAsync(@"
public class A
{
string _s = string.Empty;
public void F()
{
throw [|_s != string.Empty|] ? new System.Exception() : new System.ArgumentException();
}
}
", @"
public class A
{
string _s = string.Empty;
public void F()
{
throw !string.IsNullOrEmpty(_s) ? new System.Exception() : new System.ArgumentException();
}
}
");
}
[Fact]
public async Task CA1820_FixForComparisonWithEmptyStringInCatchFilterClauseAsync()
{
await VerifyCS.VerifyCodeFixAsync(@"
public class A
{
string _s = string.Empty;
public void F()
{
try { }
catch (System.Exception ex) when ([|_s != string.Empty|]) { }
}
}
", @"
public class A
{
string _s = string.Empty;
public void F()
{
try { }
catch (System.Exception ex) when (!string.IsNullOrEmpty(_s)) { }
}
}
");
}
[Fact]
public async Task CA1820_FixForComparisonWithEmptyStringInYieldReturnStatementAsync()
{
await VerifyCS.VerifyCodeFixAsync(@"
using System.Collections.Generic;
public class A
{
string _s = string.Empty;
public IEnumerable<bool> F()
{
yield return [|_s != string.Empty|];
}
}
", @"
using System.Collections.Generic;
public class A
{
string _s = string.Empty;
public IEnumerable<bool> F()
{
yield return !string.IsNullOrEmpty(_s);
}
}
");
}
[Fact]
public async Task CA1820_FixForComparisonWithEmptyStringInSwitchStatementAsync()
{
await VerifyCS.VerifyCodeFixAsync(@"
public class A
{
string _s = string.Empty;
public void F()
{
switch ([|_s != string.Empty|])
{
default:
throw new System.NotImplementedException();
}
}
}
", @"
public class A
{
string _s = string.Empty;
public void F()
{
switch (!string.IsNullOrEmpty(_s))
{
default:
throw new System.NotImplementedException();
}
}
}
");
}
[Fact]
public async Task CA1820_FixForComparisonWithEmptyStringInForLoopAsync()
{
await VerifyCS.VerifyCodeFixAsync(@"
public class A
{
string _s = string.Empty;
public void F()
{
for (; [|_s != string.Empty|]; )
{
throw new System.Exception();
}
}
}
", @"
public class A
{
string _s = string.Empty;
public void F()
{
for (; !string.IsNullOrEmpty(_s); )
{
throw new System.Exception();
}
}
}
");
}
[Fact]
public async Task CA1820_FixForComparisonWithEmptyStringInWhileLoopAsync()
{
await VerifyCS.VerifyCodeFixAsync(@"
public class A
{
string _s = string.Empty;
public void F()
{
while ([|_s != string.Empty|])
{
}
}
}
", @"
public class A
{
string _s = string.Empty;
public void F()
{
while (!string.IsNullOrEmpty(_s))
{
}
}
}
");
}
[Fact]
public async Task CA1820_FixForComparisonWithEmptyStringInDoWhileLoopAsync()
{
await VerifyCS.VerifyCodeFixAsync(@"
public class A
{
string _s = string.Empty;
public void F()
{
do
{
}
while ([|_s != string.Empty|]);
}
}
", @"
public class A
{
string _s = string.Empty;
public void F()
{
do
{
}
while (!string.IsNullOrEmpty(_s));
}
}
");
}
[Fact]
public async Task CA1820_MultilineFixTestEmptyStringsUsingIsNullOrEmptyAsync()
{
await VerifyCS.VerifyCodeFixAsync(@"
public class A
{
string _s = string.Empty;
public bool Compare(string s)
{
return [|s == string.Empty|] ||
s == _s;
}
}
", @"
public class A
{
string _s = string.Empty;
public bool Compare(string s)
{
return string.IsNullOrEmpty(s) ||
s == _s;
}
}
");
await VerifyVB.VerifyCodeFixAsync(@"
Public Class A
Private _s As String = String.Empty
Public Function Compare(s As String) As Boolean
Return [|s = String.Empty|] Or
s = _s
End Function
End Class
", @"
Public Class A
Private _s As String = String.Empty
Public Function Compare(s As String) As Boolean
Return String.IsNullOrEmpty(s) Or
s = _s
End Function
End Class
");
}
[Fact]
public async Task CA1820_MultilineFixTestEmptyStringsUsingStringLengthAsync()
{
await new VerifyCS.Test
{
TestState =
{
Sources =
{
@"
public class A
{
string _s = string.Empty;
public bool Compare(string s)
{
return [|s == string.Empty|] ||
s == _s;
}
}
",
},
},
FixedState =
{
Sources =
{
@"
public class A
{
string _s = string.Empty;
public bool Compare(string s)
{
return s.Length == 0 ||
s == _s;
}
}
",
},
},
CodeActionIndex = c_StringLengthCodeActionIndex,
CodeActionEquivalenceKey = "TestForEmptyStringCorrectlyUsingStringLength",
}.RunAsync();
await new VerifyVB.Test
{
TestState =
{
Sources =
{
@"
Public Class A
Private _s As String = String.Empty
Public Function Compare(s As String) As Boolean
Return [|s = String.Empty|] Or
s = _s
End Function
End Class
",
},
},
FixedState =
{
Sources =
{
@"
Public Class A
Private _s As String = String.Empty
Public Function Compare(s As String) As Boolean
Return s.Length = 0 Or
s = _s
End Function
End Class
",
},
},
CodeActionIndex = c_StringLengthCodeActionIndex,
CodeActionEquivalenceKey = "TestForEmptyStringCorrectlyUsingStringLength",
}.RunAsync();
}
[Fact]
public async Task CA1820_FixTestEmptyStringsUsingStringLength_WhenStringEqualsMethodIsUsedWithStringEmptyAsync()
{
await VerifyCS.VerifyCodeFixAsync(@"
public class A
{
public bool Compare(string s)
{
return [|s.Equals(string.Empty)|];
}
}
", @"
public class A
{
public bool Compare(string s)
{
return string.IsNullOrEmpty(s);
}
}
");
await VerifyVB.VerifyCodeFixAsync(@"
Public Class A
Public Function Compare(s As String) As Boolean
Return [|s.Equals(String.Empty)|]
End Function
End Class
", @"
Public Class A
Public Function Compare(s As String) As Boolean
Return String.IsNullOrEmpty(s)
End Function
End Class
");
}
[Fact]
public async Task CA1820_FixTestEmptyStringsUsingStringLength_WhenStringEqualsMethodIsUsedWithEmptyLiteralAsync()
{
await VerifyCS.VerifyCodeFixAsync(@"
public class A
{
public bool Compare(string s)
{
return [|s.Equals("""")|];
}
}
", @"
public class A
{
public bool Compare(string s)
{
return string.IsNullOrEmpty(s);
}
}
");
await VerifyVB.VerifyCodeFixAsync(@"
Public Class A
Public Function Compare(s As String) As Boolean
Return [|s.Equals("""")|]
End Function
End Class
", @"
Public Class A
Public Function Compare(s As String) As Boolean
Return String.IsNullOrEmpty(s)
End Function
End Class
");
}
[Fact]
public async Task CA1820_FixTestEmptyStringsUsingStringLength_WhenNotStringEqualsMethodIsUsedAsync()
{
await VerifyCS.VerifyCodeFixAsync(@"
public class A
{
public bool Compare(string s)
{
return ![|s.Equals(string.Empty)|];
}
}
", @"
public class A
{
public bool Compare(string s)
{
return !string.IsNullOrEmpty(s);
}
}
");
await VerifyVB.VerifyCodeFixAsync(@"
Public Class A
Public Function Compare(s As String) As Boolean
Return Not [|s.Equals(String.Empty)|]
End Function
End Class
", @"
Public Class A
Public Function Compare(s As String) As Boolean
Return Not String.IsNullOrEmpty(s)
End Function
End Class
");
}
}
}
| |
/* ****************************************************************************
*
* Copyright (c) Microsoft Corporation.
*
* This source code is subject to terms and conditions of the Apache License, Version 2.0. A
* copy of the license can be found in the License.html file at the root of this distribution. If
* you cannot locate the Apache License, Version 2.0, please send an email to
* [email protected]. By using this source code in any fashion, you are agreeing to be bound
* by the terms of the Apache License, Version 2.0.
*
* You must not remove this notice, or any other, from this software.
*
* ***************************************************************************/
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.Numerics;
using System.Text;
namespace Microsoft.PythonTools.Parsing {
/// <summary>
/// Summary description for ConstantValue.
/// </summary>
internal static class LiteralParser {
public static string ParseString(string text, bool isRaw, bool isUni) {
return ParseString(text.ToCharArray(), 0, text.Length, isRaw, isUni, false);
}
public static string ParseString(char[] text, int start, int length, bool isRaw, bool isUni, bool normalizeLineEndings) {
if (text == null) {
throw new ArgumentNullException("text");
}
if (isRaw && !isUni && !normalizeLineEndings) return new String(text, start, length);
StringBuilder buf = null;
int i = start;
int l = start + length;
int val;
while (i < l) {
char ch = text[i++];
if ((!isRaw || isUni) && ch == '\\') {
if (buf == null) {
buf = new StringBuilder(length);
buf.Append(text, start, i - start - 1);
}
if (i >= l) {
if (isRaw) {
buf.Append('\\');
break;
} else {
throw new ArgumentException("Trailing \\ in string");
}
}
ch = text[i++];
if (ch == 'u' || ch == 'U') {
int len = (ch == 'u') ? 4 : 8;
int max = 16;
if (isUni && !isRaw) {
if (TryParseInt(text, i, len, max, out val)) {
buf.Append((char)val);
i += len;
} else {
throw new System.Text.DecoderFallbackException(String.Format(@"'unicodeescape' codec can't decode bytes in position {0}: truncated \uXXXX escape", i));
}
} else {
buf.Append('\\');
buf.Append(ch);
}
} else {
if (isRaw) {
buf.Append('\\');
buf.Append(ch);
continue;
}
switch (ch) {
case 'a': buf.Append('\a'); continue;
case 'b': buf.Append('\b'); continue;
case 'f': buf.Append('\f'); continue;
case 'n': buf.Append('\n'); continue;
case 'r': buf.Append('\r'); continue;
case 't': buf.Append('\t'); continue;
case 'v': buf.Append('\v'); continue;
case '\\': buf.Append('\\'); continue;
case '\'': buf.Append('\''); continue;
case '\"': buf.Append('\"'); continue;
case '\r': if (i < l && text[i] == '\n') i++; continue;
case '\n': continue;
case 'x': //hex
if (!TryParseInt(text, i, 2, 16, out val)) {
goto default;
}
buf.Append((char)val);
i += 2;
continue;
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7': {
int onechar;
val = ch - '0';
if (i < l && HexValue(text[i], out onechar) && onechar < 8) {
val = val * 8 + onechar;
i++;
if (i < l && HexValue(text[i], out onechar) && onechar < 8) {
val = val * 8 + onechar;
i++;
}
}
}
buf.Append((char)val);
continue;
default:
buf.Append("\\");
buf.Append(ch);
continue;
}
}
} else if (ch == '\r' && normalizeLineEndings) {
if (buf == null) {
buf = new StringBuilder(length);
buf.Append(text, start, i - start - 1);
}
// normalize line endings
if (i < text.Length && text[i] == '\n') {
i++;
}
buf.Append('\n');
} else if (buf != null) {
buf.Append(ch);
}
}
if (buf != null) {
return buf.ToString();
}
return new String(text, start, length);
}
internal static List<char> ParseBytes(char[] text, int start, int length, bool isRaw, bool normalizeLineEndings) {
Debug.Assert(text != null);
List<char> buf = new List<char>(length);
int i = start;
int l = start + length;
int val;
while (i < l) {
char ch = text[i++];
if (!isRaw && ch == '\\') {
if (i >= l) {
throw new ArgumentException("Trailing \\ in string");
}
ch = text[i++];
switch (ch) {
case 'a': buf.Add('\a'); continue;
case 'b': buf.Add('\b'); continue;
case 'f': buf.Add('\f'); continue;
case 'n': buf.Add('\n'); continue;
case 'r': buf.Add('\r'); continue;
case 't': buf.Add('\t'); continue;
case 'v': buf.Add('\v'); continue;
case '\\': buf.Add('\\'); continue;
case '\'': buf.Add('\''); continue;
case '\"': buf.Add('\"'); continue;
case '\r': if (i < l && text[i] == '\n') i++; continue;
case '\n': continue;
case 'x': //hex
if (!TryParseInt(text, i, 2, 16, out val)) {
goto default;
}
buf.Add((char)val);
i += 2;
continue;
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7': {
int onechar;
val = ch - '0';
if (i < l && HexValue(text[i], out onechar) && onechar < 8) {
val = val * 8 + onechar;
i++;
if (i < l && HexValue(text[i], out onechar) && onechar < 8) {
val = val * 8 + onechar;
i++;
}
}
}
buf.Add((char)val);
continue;
default:
buf.Add('\\');
buf.Add(ch);
continue;
}
} else if (ch == '\r' && normalizeLineEndings) {
// normalize line endings
if (i < text.Length && text[i] == '\n') {
i++;
}
buf.Add('\n');
} else {
buf.Add(ch);
}
}
return buf;
}
private static bool HexValue(char ch, out int value) {
switch (ch) {
case '0':
case '\x660': value = 0; break;
case '1':
case '\x661': value = 1; break;
case '2':
case '\x662': value = 2; break;
case '3':
case '\x663': value = 3; break;
case '4':
case '\x664': value = 4; break;
case '5':
case '\x665': value = 5; break;
case '6':
case '\x666': value = 6; break;
case '7':
case '\x667': value = 7; break;
case '8':
case '\x668': value = 8; break;
case '9':
case '\x669': value = 9; break;
default:
if (ch >= 'a' && ch <= 'z') {
value = ch - 'a' + 10;
} else if (ch >= 'A' && ch <= 'Z') {
value = ch - 'A' + 10;
} else {
value = -1;
return false;
}
break;
}
return true;
}
private static int HexValue(char ch) {
int value;
if (!HexValue(ch, out value)) {
throw new ArgumentException("bad char for integer value: " + ch);
}
return value;
}
private static int CharValue(char ch, int b) {
int val = HexValue(ch);
if (val >= b) {
throw new ArgumentException(String.Format("bad char for the integer value: '{0}' (base {1})", ch, b));
}
return val;
}
private static bool ParseInt(string text, int b, out int ret) {
ret = 0;
long m = 1;
for (int i = text.Length - 1; i >= 0; i--) {
// avoid the exception here. Not only is throwing it expensive,
// but loading the resources for it is also expensive
long lret = (long)ret + m * CharValue(text[i], b);
if (Int32.MinValue <= lret && lret <= Int32.MaxValue) {
ret = (int)lret;
} else {
return false;
}
m *= b;
if (Int32.MinValue > m || m > Int32.MaxValue) {
return false;
}
}
return true;
}
private static bool TryParseInt(char[] text, int start, int length, int b, out int value) {
value = 0;
if (start + length > text.Length) {
return false;
}
for (int i = start, end = start + length; i < end; i++) {
int onechar;
if (HexValue(text[i], out onechar) && onechar < b) {
value = value * b + onechar;
} else {
return false;
}
}
return true;
}
public static object ParseInteger(string text, int b) {
Debug.Assert(b != 0);
int iret;
if (!ParseInt(text, b, out iret)) {
BigInteger ret = ParseBigInteger(text, b);
if (ret >= Int32.MinValue && ret <= Int32.MaxValue) {
return (int)ret;
}
return ret;
}
return iret;
}
public static object ParseIntegerSign(string text, int b) {
int start = 0, end = text.Length, saveb = b;
short sign = 1;
if (b < 0 || b == 1 || b > 36) {
throw new ArgumentException("base must be >= 2 and <= 36");
}
ParseIntegerStart(text, ref b, ref start, end, ref sign);
int ret = 0;
try {
int saveStart = start;
for (; ; ) {
int digit;
if (start >= end) {
if (saveStart == start) {
throw new ArgumentException("Invalid integer literal");
}
break;
}
if (!HexValue(text[start], out digit)) break;
if (!(digit < b)) {
if (text[start] == 'l' || text[start] == 'L') {
break;
}
throw new ArgumentException("Invalid integer literal");
}
checked {
// include sign here so that System.Int32.MinValue won't overflow
ret = ret * b + sign * digit;
}
start++;
}
} catch (OverflowException) {
return ParseBigIntegerSign(text, saveb);
}
ParseIntegerEnd(text, start, end);
return ret;
}
private static void ParseIntegerStart(string text, ref int b, ref int start, int end, ref short sign) {
// Skip whitespace
while (start < end && Char.IsWhiteSpace(text, start)) start++;
// Sign?
if (start < end) {
switch (text[start]) {
case '-':
sign = -1;
goto case '+';
case '+':
start++;
break;
}
}
// Skip whitespace
while (start < end && Char.IsWhiteSpace(text, start)) start++;
// Determine base
if (b == 0) {
if (start < end && text[start] == '0') {
// Hex, oct, or bin
if (++start < end) {
switch (text[start]) {
case 'x':
case 'X':
start++;
b = 16;
break;
case 'o':
case 'O':
b = 8;
start++;
break;
case 'b':
case 'B':
start++;
b = 2;
break;
}
}
if (b == 0) {
// Keep the leading zero
start--;
b = 8;
}
} else {
b = 10;
}
}
}
private static void ParseIntegerEnd(string text, int start, int end) {
// Skip whitespace
while (start < end && Char.IsWhiteSpace(text, start)) start++;
if (start < end) {
throw new ArgumentException("invalid integer number literal");
}
}
public static BigInteger ParseBigInteger(string text, int b) {
Debug.Assert(b != 0);
BigInteger ret = BigInteger.Zero;
BigInteger m = BigInteger.One;
if (text.Length != 0) {
int i = text.Length - 1;
if (text[i] == 'l' || text[i] == 'L') i -= 1;
int groupMax = 7;
if (b <= 10) groupMax = 9;// 2 147 483 647
while (i >= 0) {
// extract digits in a batch
int smallMultiplier = 1;
uint uval = 0;
for (int j = 0; j < groupMax && i >= 0; j++) {
uval = (uint)(CharValue(text[i--], b) * smallMultiplier + uval);
smallMultiplier *= b;
}
// this is more generous than needed
ret += m * (BigInteger)uval;
if (i >= 0) m = m * (smallMultiplier);
}
}
return ret;
}
public static BigInteger ParseBigIntegerSign(string text, int b) {
int start = 0, end = text.Length;
short sign = 1;
if (b < 0 || b == 1 || b > 36) {
throw new ArgumentException("base must be >= 2 and <= 36");
}
ParseIntegerStart(text, ref b, ref start, end, ref sign);
BigInteger ret = BigInteger.Zero;
int saveStart = start;
for (; ; ) {
int digit;
if (start >= end) {
if (start == saveStart) {
throw new ArgumentException("Invalid integer literal");
}
break;
}
if (!HexValue(text[start], out digit)) break;
if (!(digit < b)) {
if (text[start] == 'l' || text[start] == 'L') {
break;
}
throw new ArgumentException("Invalid integer literal");
}
ret = ret * b + digit;
start++;
}
if (start < end && (text[start] == 'l' || text[start] == 'L')) {
start++;
}
ParseIntegerEnd(text, start, end);
return sign < 0 ? -ret : ret;
}
public static double ParseFloat(string text) {
try {
//
// Strings that end with '\0' is the specific case that CLR libraries allow,
// however Python doesn't. Since we use CLR floating point number parser,
// we must check explicitly for the strings that end with '\0'
//
if (text != null && text.Length > 0 && text[text.Length - 1] == '\0') {
throw new ArgumentException("null byte in float literal");
}
return ParseFloatNoCatch(text);
} catch (OverflowException) {
return text.TrimStart().StartsWith("-") ? Double.NegativeInfinity : Double.PositiveInfinity;
}
}
private static double ParseFloatNoCatch(string text) {
string s = ReplaceUnicodeDigits(text);
switch (s.ToLower().TrimStart()) {
case "nan":
case "+nan":
case "-nan":
return double.NaN;
case "inf":
case "+inf":
return double.PositiveInfinity;
case "-inf":
return double.NegativeInfinity;
default:
// pass NumberStyles to disallow ,'s in float strings.
double res = double.Parse(s, NumberStyles.Float, System.Globalization.CultureInfo.InvariantCulture);
return (res == 0.0 && text.TrimStart().StartsWith("-")) ? NegativeZero : res;
}
}
internal const double NegativeZero = -0.0;
private static string ReplaceUnicodeDigits(string text) {
StringBuilder replacement = null;
for (int i = 0; i < text.Length; i++) {
if (text[i] >= '\x660' && text[i] <= '\x669') {
if (replacement == null) replacement = new StringBuilder(text);
replacement[i] = (char)(text[i] - '\x660' + '0');
}
}
if (replacement != null) {
text = replacement.ToString();
}
return text;
}
// ParseComplex helpers
private static char[] signs = new char[] { '+', '-' };
private static Exception ExnMalformed() {
return new ArgumentException("complex() arg is a malformed string");
}
public static Complex ParseImaginary(string text) {
try {
return new Complex(0.0, double.Parse(
text.Substring(0, text.Length - 1),
System.Globalization.CultureInfo.InvariantCulture.NumberFormat
));
} catch (OverflowException) {
return new Complex(0, Double.PositiveInfinity);
}
}
}
}
| |
//
// Copyright (c) 2004-2017 Jaroslaw Kowalski <[email protected]>, Kim Christensen, Julian Verdurmen
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of Jaroslaw Kowalski nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
// THE POSSIBILITY OF SUCH DAMAGE.
//
namespace NLog.UnitTests.Config
{
using System.IO;
using System.Text;
using NLog.Config;
using NLog.Filters;
using Xunit;
public class RuleConfigurationTests : NLogTestBase
{
[Fact]
public void NoRulesTest()
{
LoggingConfiguration c = CreateConfigurationFromString(@"
<nlog>
<targets>
<target name='d1' type='Debug' />
</targets>
<rules>
</rules>
</nlog>");
Assert.Equal(0, c.LoggingRules.Count);
}
[Fact]
public void SimpleRuleTest()
{
LoggingConfiguration c = CreateConfigurationFromString(@"
<nlog>
<targets>
<target name='d1' type='Debug' />
</targets>
<rules>
<logger name='*' minLevel='Info' writeTo='d1' />
</rules>
</nlog>");
Assert.Equal(1, c.LoggingRules.Count);
var rule = c.LoggingRules[0];
Assert.Equal("*", rule.LoggerNamePattern);
Assert.Equal(4, rule.Levels.Count);
Assert.Contains(LogLevel.Info, rule.Levels);
Assert.Contains(LogLevel.Warn, rule.Levels);
Assert.Contains(LogLevel.Error, rule.Levels);
Assert.Contains(LogLevel.Fatal, rule.Levels);
Assert.Equal(1, rule.Targets.Count);
Assert.Same(c.FindTargetByName("d1"), rule.Targets[0]);
Assert.False(rule.Final);
Assert.Equal(0, rule.Filters.Count);
}
[Fact]
public void SingleLevelTest()
{
LoggingConfiguration c = CreateConfigurationFromString(@"
<nlog>
<targets>
<target name='d1' type='Debug' />
</targets>
<rules>
<logger name='*' level='Warn' writeTo='d1' />
</rules>
</nlog>");
Assert.Equal(1, c.LoggingRules.Count);
var rule = c.LoggingRules[0];
Assert.Single(rule.Levels);
Assert.Contains(LogLevel.Warn, rule.Levels);
}
[Fact]
public void MinMaxLevelTest()
{
LoggingConfiguration c = CreateConfigurationFromString(@"
<nlog>
<targets>
<target name='d1' type='Debug' />
</targets>
<rules>
<logger name='*' minLevel='Info' maxLevel='Warn' writeTo='d1' />
</rules>
</nlog>");
Assert.Equal(1, c.LoggingRules.Count);
var rule = c.LoggingRules[0];
Assert.Equal(2, rule.Levels.Count);
Assert.Contains(LogLevel.Info, rule.Levels);
Assert.Contains(LogLevel.Warn, rule.Levels);
}
[Fact]
public void NoLevelsTest()
{
LoggingConfiguration c = CreateConfigurationFromString(@"
<nlog>
<targets>
<target name='d1' type='Debug' />
</targets>
<rules>
<logger name='*' writeTo='d1' />
</rules>
</nlog>");
Assert.Equal(1, c.LoggingRules.Count);
var rule = c.LoggingRules[0];
Assert.Equal(6, rule.Levels.Count);
Assert.Contains(LogLevel.Trace, rule.Levels);
Assert.Contains(LogLevel.Debug, rule.Levels);
Assert.Contains(LogLevel.Info, rule.Levels);
Assert.Contains(LogLevel.Warn, rule.Levels);
Assert.Contains(LogLevel.Error, rule.Levels);
Assert.Contains(LogLevel.Fatal, rule.Levels);
}
[Fact]
public void ExplicitLevelsTest()
{
LoggingConfiguration c = CreateConfigurationFromString(@"
<nlog>
<targets>
<target name='d1' type='Debug' />
</targets>
<rules>
<logger name='*' levels='Trace,Info,Warn' writeTo='d1' />
</rules>
</nlog>");
Assert.Equal(1, c.LoggingRules.Count);
var rule = c.LoggingRules[0];
Assert.Equal(3, rule.Levels.Count);
Assert.Contains(LogLevel.Trace, rule.Levels);
Assert.Contains(LogLevel.Info, rule.Levels);
Assert.Contains(LogLevel.Warn, rule.Levels);
}
[Fact]
public void MultipleTargetsTest()
{
LoggingConfiguration c = CreateConfigurationFromString(@"
<nlog>
<targets>
<target name='d1' type='Debug' />
<target name='d2' type='Debug' />
<target name='d3' type='Debug' />
<target name='d4' type='Debug' />
</targets>
<rules>
<logger name='*' level='Warn' writeTo='d1,d2,d3' />
</rules>
</nlog>");
Assert.Equal(1, c.LoggingRules.Count);
var rule = c.LoggingRules[0];
Assert.Equal(3, rule.Targets.Count);
Assert.Same(c.FindTargetByName("d1"), rule.Targets[0]);
Assert.Same(c.FindTargetByName("d2"), rule.Targets[1]);
Assert.Same(c.FindTargetByName("d3"), rule.Targets[2]);
}
[Fact]
public void MultipleRulesSameTargetTest()
{
LoggingConfiguration c = CreateConfigurationFromString(@"
<nlog>
<targets>
<target name='d1' type='Debug' layout='${message}' />
<target name='d2' type='Debug' layout='${message}' />
<target name='d3' type='Debug' layout='${message}' />
<target name='d4' type='Debug' layout='${message}' />
</targets>
<rules>
<logger name='*' level='Warn' writeTo='d1' />
<logger name='*' level='Warn' writeTo='d2' />
<logger name='*' level='Warn' writeTo='d3' />
</rules>
</nlog>");
LogFactory factory = new LogFactory(c);
var loggerConfig = factory.GetConfigurationForLogger("AAA", c);
var targets = loggerConfig.GetTargetsForLevel(LogLevel.Warn);
Assert.Equal("d1", targets.Target.Name);
Assert.Equal("d2", targets.NextInChain.Target.Name);
Assert.Equal("d3", targets.NextInChain.NextInChain.Target.Name);
Assert.Null(targets.NextInChain.NextInChain.NextInChain);
LogManager.Configuration = c;
var logger = LogManager.GetLogger("BBB");
logger.Warn("test1234");
this.AssertDebugLastMessage("d1", "test1234");
this.AssertDebugLastMessage("d2", "test1234");
this.AssertDebugLastMessage("d3", "test1234");
this.AssertDebugLastMessage("d4", string.Empty);
}
[Fact]
public void ChildRulesTest()
{
LoggingConfiguration c = CreateConfigurationFromString(@"
<nlog>
<targets>
<target name='d1' type='Debug' />
<target name='d2' type='Debug' />
<target name='d3' type='Debug' />
<target name='d4' type='Debug' />
</targets>
<rules>
<logger name='*' level='Warn' writeTo='d1,d2,d3'>
<logger name='Foo*' writeTo='d4' />
<logger name='Bar*' writeTo='d4' />
</logger>
</rules>
</nlog>");
Assert.Equal(1, c.LoggingRules.Count);
var rule = c.LoggingRules[0];
Assert.Equal(2, rule.ChildRules.Count);
Assert.Equal("Foo*", rule.ChildRules[0].LoggerNamePattern);
Assert.Equal("Bar*", rule.ChildRules[1].LoggerNamePattern);
}
[Fact]
public void FiltersTest()
{
LoggingConfiguration c = CreateConfigurationFromString(@"
<nlog>
<targets>
<target name='d1' type='Debug' />
<target name='d2' type='Debug' />
<target name='d3' type='Debug' />
<target name='d4' type='Debug' />
</targets>
<rules>
<logger name='*' level='Warn' writeTo='d1,d2,d3'>
<filters>
<when condition=""starts-with(message, 'x')"" action='Ignore' />
<when condition=""starts-with(message, 'z')"" action='Ignore' />
</filters>
</logger>
</rules>
</nlog>");
Assert.Equal(1, c.LoggingRules.Count);
var rule = c.LoggingRules[0];
Assert.Equal(2, rule.Filters.Count);
var conditionBasedFilter = rule.Filters[0] as ConditionBasedFilter;
Assert.NotNull(conditionBasedFilter);
Assert.Equal("starts-with(message, 'x')", conditionBasedFilter.Condition.ToString());
Assert.Equal(FilterResult.Ignore, conditionBasedFilter.Action);
conditionBasedFilter = rule.Filters[1] as ConditionBasedFilter;
Assert.NotNull(conditionBasedFilter);
Assert.Equal("starts-with(message, 'z')", conditionBasedFilter.Condition.ToString());
Assert.Equal(FilterResult.Ignore, conditionBasedFilter.Action);
}
[Fact]
public void FiltersTest_ignoreFinal()
{
LoggingConfiguration c = CreateConfigurationFromString(@"
<nlog>
<targets>
<target name='d1' type='Debug' layout='${message}' />
<target name='d2' type='Debug' layout='${message}' />
</targets>
<rules>
<logger name='*' level='Warn' writeTo='d1'>
<filters>
<when condition=""starts-with(message, 'x')"" action='IgnoreFinal' />
</filters>
</logger>
<logger name='*' level='Warn' writeTo='d2'>
</logger>
</rules>
</nlog>");
LogManager.Configuration = c;
var logger = LogManager.GetLogger("logger1");
logger.Warn("test 1");
AssertDebugLastMessage("d1", "test 1");
AssertDebugLastMessage("d2", "test 1");
logger.Warn("x-mass");
AssertDebugLastMessage("d1", "test 1");
AssertDebugLastMessage("d2", "test 1");
}
[Fact]
public void FiltersTest_logFinal()
{
LoggingConfiguration c = CreateConfigurationFromString(@"
<nlog>
<targets>
<target name='d1' type='Debug' layout='${message}' />
<target name='d2' type='Debug' layout='${message}' />
</targets>
<rules>
<logger name='*' level='Warn' writeTo='d1'>
<filters>
<when condition=""starts-with(message, 'x')"" action='LogFinal' />
</filters>
</logger>
<logger name='*' level='Warn' writeTo='d2'>
</logger>
</rules>
</nlog>");
LogManager.Configuration = c;
var logger = LogManager.GetLogger("logger1");
logger.Warn("test 1");
AssertDebugLastMessage("d1", "test 1");
AssertDebugLastMessage("d2", "test 1");
logger.Warn("x-mass");
AssertDebugLastMessage("d1", "x-mass");
AssertDebugLastMessage("d2", "test 1");
}
[Fact]
public void FiltersTest_ignore()
{
LoggingConfiguration c = CreateConfigurationFromString(@"
<nlog>
<targets>
<target name='d1' type='Debug' layout='${message}' />
<target name='d2' type='Debug' layout='${message}' />
</targets>
<rules>
<logger name='*' level='Warn' writeTo='d1'>
<filters>
<when condition=""starts-with(message, 'x')"" action='Ignore' />
</filters>
</logger>
<logger name='*' level='Warn' writeTo='d2'>
</logger>
</rules>
</nlog>");
LogManager.Configuration = c;
var logger = LogManager.GetLogger("logger1");
logger.Warn("test 1");
AssertDebugLastMessage("d1", "test 1");
AssertDebugLastMessage("d2", "test 1");
logger.Warn("x-mass");
AssertDebugLastMessage("d1", "test 1");
AssertDebugLastMessage("d2", "x-mass");
}
[Fact]
public void LoggingRule_Final_SuppressesOnlyMatchingLevels()
{
LoggingConfiguration c = CreateConfigurationFromString(@"
<nlog>
<targets>
<target name='d1' type='Debug' layout='${message}' />
</targets>
<rules>
<logger name='a' level='Debug' final='true' />
<logger name='*' minlevel='Debug' writeTo='d1' />
</rules>
</nlog>");
LogManager.Configuration = c;
Logger a = LogManager.GetLogger("a");
Assert.False(a.IsDebugEnabled);
Assert.True(a.IsInfoEnabled);
a.Info("testInfo");
a.Debug("suppressedDebug");
AssertDebugLastMessage("d1", "testInfo");
Logger b = LogManager.GetLogger("b");
b.Debug("testDebug");
AssertDebugLastMessage("d1", "testDebug");
}
[Fact]
public void UnusedTargetsShouldBeLoggedToInternalLogger()
{
string tempFileName = Path.GetTempFileName();
try
{
CreateConfigurationFromString(
"<nlog internalLogFile='" + tempFileName + @"' internalLogLevel='Warn'>
<targets>
<target name='d1' type='Debug' />
<target name='d2' type='Debug' />
<target name='d3' type='Debug' />
<target name='d4' type='Debug' />
<target name='d5' type='Debug' />
</targets>
<rules>
<logger name='*' level='Debug' writeTo='d1' />
<logger name='*' level='Debug' writeTo='d1,d2,d3' />
</rules>
</nlog>");
AssertFileContains(tempFileName, "Unused target detected. Add a rule for this target to the configuration. TargetName: d4", Encoding.UTF8);
AssertFileContains(tempFileName, "Unused target detected. Add a rule for this target to the configuration. TargetName: d5", Encoding.UTF8);
}
finally
{
NLog.Common.InternalLogger.Reset();
if (File.Exists(tempFileName))
{
File.Delete(tempFileName);
}
}
}
[Fact]
public void UnusedTargetsShouldBeLoggedToInternalLogger_PermitWrapped()
{
string tempFileName = Path.GetTempFileName();
try
{
CreateConfigurationFromString(
"<nlog internalLogFile='" + tempFileName + @"' internalLogLevel='Warn'>
<extensions>
<add assembly='NLog.UnitTests'/>
</extensions>
<targets>
<target name='d1' type='Debug' />
<target name='d2' type='MockWrapper'>
<target name='d3' type='Debug' />
</target>
<target name='d4' type='Debug' />
<target name='d5' type='Debug' />
</targets>
<rules>
<logger name='*' level='Debug' writeTo='d1' />
<logger name='*' level='Debug' writeTo='d1,d2,d4' />
</rules>
</nlog>");
AssertFileNotContains(tempFileName, "Unused target detected. Add a rule for this target to the configuration. TargetName: d2", Encoding.UTF8);
AssertFileNotContains(tempFileName, "Unused target detected. Add a rule for this target to the configuration. TargetName: d3", Encoding.UTF8);
AssertFileNotContains(tempFileName, "Unused target detected. Add a rule for this target to the configuration. TargetName: d4", Encoding.UTF8);
AssertFileContains(tempFileName, "Unused target detected. Add a rule for this target to the configuration. TargetName: d5", Encoding.UTF8);
}
finally
{
NLog.Common.InternalLogger.Reset();
if (File.Exists(tempFileName))
{
File.Delete(tempFileName);
}
}
}
[Fact]
public void LoggingRule_LevelOff_NotSetAsActualLogLevel()
{
LoggingConfiguration c = CreateConfigurationFromString(@"
<nlog>
<targets>
<target name='l1' type='Debug' layout='${message}' />
<target name='l2' type='Debug' layout='${message}' />
</targets>
<rules>
<logger name='a' level='Off' appendTo='l1' />
<logger name='a' minlevel='Debug' appendTo='l2' />
</rules>
</nlog>");
LogManager.Configuration = c;
Logger a = LogManager.GetLogger("a");
Assert.True(c.LoggingRules.Count == 2, "All rules should have been loaded.");
Assert.False(c.LoggingRules[0].IsLoggingEnabledForLevel(LogLevel.Off), "Log level Off should always return false.");
// The two functions below should not throw an exception.
c.LoggingRules[0].EnableLoggingForLevel(LogLevel.Debug);
c.LoggingRules[0].DisableLoggingForLevel(LogLevel.Debug);
}
}
}
| |
using Lucene.Net.Documents;
using System;
using System.Runtime.CompilerServices;
namespace Lucene.Net.Index
{
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using BinaryDocValuesField = BinaryDocValuesField;
using BinaryDocValuesUpdate = Lucene.Net.Index.DocValuesUpdate.BinaryDocValuesUpdate;
using BytesRef = Lucene.Net.Util.BytesRef;
using DocIdSetIterator = Lucene.Net.Search.DocIdSetIterator;
using FixedBitSet = Lucene.Net.Util.FixedBitSet;
using InPlaceMergeSorter = Lucene.Net.Util.InPlaceMergeSorter;
using PackedInt32s = Lucene.Net.Util.Packed.PackedInt32s;
using PagedGrowableWriter = Lucene.Net.Util.Packed.PagedGrowableWriter;
using PagedMutable = Lucene.Net.Util.Packed.PagedMutable;
/// <summary>
/// A <see cref="DocValuesFieldUpdates"/> which holds updates of documents, of a single
/// <see cref="BinaryDocValuesField"/>.
/// <para/>
/// @lucene.experimental
/// </summary>
internal class BinaryDocValuesFieldUpdates : DocValuesFieldUpdates
{
new internal sealed class Iterator : DocValuesFieldUpdates.Iterator
{
private readonly PagedGrowableWriter offsets;
private readonly int size;
private readonly PagedGrowableWriter lengths;
private readonly PagedMutable docs;
private readonly FixedBitSet docsWithField;
private long idx = 0; // long so we don't overflow if size == Integer.MAX_VALUE
private int doc = -1;
private readonly BytesRef value;
private int offset, length;
internal Iterator(int size, PagedGrowableWriter offsets, PagedGrowableWriter lengths, PagedMutable docs, BytesRef values, FixedBitSet docsWithField)
{
this.offsets = offsets;
this.size = size;
this.lengths = lengths;
this.docs = docs;
this.docsWithField = docsWithField;
value = (BytesRef)values.Clone();
}
public override object Value
{
get
{
if (offset == -1)
{
return null;
}
else
{
value.Offset = offset;
value.Length = length;
return value;
}
}
}
public override int NextDoc()
{
if (idx >= size)
{
offset = -1;
return doc = DocIdSetIterator.NO_MORE_DOCS;
}
doc = (int)docs.Get(idx);
++idx;
while (idx < size && docs.Get(idx) == doc)
{
++idx;
}
// idx points to the "next" element
long prevIdx = idx - 1;
if (!docsWithField.Get((int)prevIdx))
{
offset = -1;
}
else
{
// cannot change 'value' here because nextDoc is called before the
// value is used, and it's a waste to clone the BytesRef when we
// obtain the value
offset = (int)offsets.Get(prevIdx);
length = (int)lengths.Get(prevIdx);
}
return doc;
}
public override int Doc => doc;
public override void Reset()
{
doc = -1;
offset = -1;
idx = 0;
}
}
private FixedBitSet docsWithField;
private PagedMutable docs;
private PagedGrowableWriter offsets, lengths;
private readonly BytesRef values; // LUCENENET: marked readonly
private int size;
public BinaryDocValuesFieldUpdates(string field, int maxDoc)
: base(field, DocValuesFieldUpdatesType.BINARY)
{
docsWithField = new FixedBitSet(64);
docs = new PagedMutable(1, 1024, PackedInt32s.BitsRequired(maxDoc - 1), PackedInt32s.COMPACT);
offsets = new PagedGrowableWriter(1, 1024, 1, PackedInt32s.FAST);
lengths = new PagedGrowableWriter(1, 1024, 1, PackedInt32s.FAST);
values = new BytesRef(16); // start small
size = 0;
}
public override void Add(int doc, object value)
{
// TODO: if the Sorter interface changes to take long indexes, we can remove that limitation
if (size == int.MaxValue)
{
throw IllegalStateException.Create("cannot support more than System.Int32.MaxValue doc/value entries");
}
BytesRef val = (BytesRef)value;
if (val == null)
{
val = BinaryDocValuesUpdate.MISSING;
}
// grow the structures to have room for more elements
if (docs.Count == size)
{
docs = docs.Grow(size + 1);
offsets = offsets.Grow(size + 1);
lengths = lengths.Grow(size + 1);
docsWithField = FixedBitSet.EnsureCapacity(docsWithField, (int)docs.Count);
}
if (val != BinaryDocValuesUpdate.MISSING)
{
// only mark the document as having a value in that field if the value wasn't set to null (MISSING)
docsWithField.Set(size);
}
docs.Set(size, doc);
offsets.Set(size, values.Length);
lengths.Set(size, val.Length);
values.Append(val);
++size;
}
public override DocValuesFieldUpdates.Iterator GetIterator()
{
PagedMutable docs = this.docs;
PagedGrowableWriter offsets = this.offsets;
PagedGrowableWriter lengths = this.lengths;
BytesRef values = this.values;
FixedBitSet docsWithField = this.docsWithField;
new InPlaceMergeSorterAnonymousClass(docs, offsets, lengths, docsWithField).Sort(0, size);
return new Iterator(size, offsets, lengths, docs, values, docsWithField);
}
private class InPlaceMergeSorterAnonymousClass : InPlaceMergeSorter
{
private readonly PagedMutable docs;
private readonly PagedGrowableWriter offsets;
private readonly PagedGrowableWriter lengths;
private readonly FixedBitSet docsWithField;
public InPlaceMergeSorterAnonymousClass(PagedMutable docs, PagedGrowableWriter offsets, PagedGrowableWriter lengths, FixedBitSet docsWithField)
{
this.docs = docs;
this.offsets = offsets;
this.lengths = lengths;
this.docsWithField = docsWithField;
}
protected override void Swap(int i, int j)
{
long tmpDoc = docs.Get(j);
docs.Set(j, docs.Get(i));
docs.Set(i, tmpDoc);
long tmpOffset = offsets.Get(j);
offsets.Set(j, offsets.Get(i));
offsets.Set(i, tmpOffset);
long tmpLength = lengths.Get(j);
lengths.Set(j, lengths.Get(i));
lengths.Set(i, tmpLength);
bool tmpBool = docsWithField.Get(j);
if (docsWithField.Get(i))
{
docsWithField.Set(j);
}
else
{
docsWithField.Clear(j);
}
if (tmpBool)
{
docsWithField.Set(i);
}
else
{
docsWithField.Clear(i);
}
}
protected override int Compare(int i, int j)
{
int x = (int)docs.Get(i);
int y = (int)docs.Get(j);
return (x < y) ? -1 : ((x == y) ? 0 : 1);
}
}
[MethodImpl(MethodImplOptions.NoInlining)]
public override void Merge(DocValuesFieldUpdates other)
{
BinaryDocValuesFieldUpdates otherUpdates = (BinaryDocValuesFieldUpdates)other;
int newSize = size + otherUpdates.size;
if (newSize > int.MaxValue)
{
throw IllegalStateException.Create("cannot support more than System.Int32.MaxValue doc/value entries; size=" + size + " other.size=" + otherUpdates.size);
}
docs = docs.Grow(newSize);
offsets = offsets.Grow(newSize);
lengths = lengths.Grow(newSize);
docsWithField = FixedBitSet.EnsureCapacity(docsWithField, (int)docs.Count);
for (int i = 0; i < otherUpdates.size; i++)
{
int doc = (int)otherUpdates.docs.Get(i);
if (otherUpdates.docsWithField.Get(i))
{
docsWithField.Set(size);
}
docs.Set(size, doc);
offsets.Set(size, values.Length + otherUpdates.offsets.Get(i)); // correct relative offset
lengths.Set(size, otherUpdates.lengths.Get(i));
++size;
}
values.Append(otherUpdates.values);
}
public override bool Any()
{
return size > 0;
}
}
}
| |
// <copyright file="DelimitedReaderTest.cs" company="Fubar Development Junker">
// Copyright (c) 2016 Fubar Development Junker. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
// </copyright>
using System.IO;
using BeanIO.Stream.Delimited;
using Xunit;
namespace BeanIO.Stream
{
public class DelimitedReaderTest
{
[Fact]
public void TestBasic()
{
DelimitedRecordParserFactory factory = new DelimitedRecordParserFactory();
var expected = new[] { "1", "2", "33", "444", string.Empty };
DelimitedReader reader = CreateReader(factory, "1\t2\t33\t444\t\n");
Assert.Equal(expected, reader.Read());
Assert.Null(reader.Read());
}
[Fact]
public void TestEscapeDisabled()
{
DelimitedRecordParserFactory factory = new DelimitedRecordParserFactory { Escape = null };
DelimitedReader reader = CreateReader(factory, "1\\\\\t2");
Assert.Equal(new[] { "1\\\\", "2" }, reader.Read());
Assert.Null(reader.Read());
}
[Fact]
public void TestEscapeEscape()
{
DelimitedRecordParserFactory factory = new DelimitedRecordParserFactory { Escape = '\\' };
DelimitedReader reader = CreateReader(factory, "1\\\\\t2");
Assert.Equal(new[] { "1\\", "2" }, reader.Read());
Assert.Null(reader.Read());
}
[Fact]
public void TestEscapeDelimiter()
{
DelimitedRecordParserFactory factory = new DelimitedRecordParserFactory { Escape = '\\' };
DelimitedReader reader = CreateReader(factory, "1\\\t\t2\\");
Assert.Equal(new[] { "1\t", "2\\" }, reader.Read());
Assert.Null(reader.Read());
}
[Fact]
public void TestEscapeOther()
{
DelimitedRecordParserFactory factory = new DelimitedRecordParserFactory { Escape = '\\' };
DelimitedReader reader = CreateReader(factory, "1\t2\\2");
Assert.Equal(new[] { "1", "2\\2" }, reader.Read());
Assert.Null(reader.Read());
}
[Fact]
public void TestCustomDelimiter()
{
DelimitedReader reader = new DelimitedReader(new StringReader("1,2,\t3"), ',');
Assert.Equal(new[] { "1", "2", "\t3" }, reader.Read());
Assert.Null(reader.Read());
}
[Fact]
public void TestLineContinuation()
{
DelimitedRecordParserFactory factory = new DelimitedRecordParserFactory
{
Delimiter = ',',
LineContinuationCharacter = '\\'
};
DelimitedReader reader = CreateReader(factory, "1,2,\\\n3,4");
Assert.Equal(new[] { "1", "2", "3", "4" }, reader.Read());
Assert.Equal(1, reader.RecordLineNumber);
Assert.Null(reader.Read());
}
[Fact]
public void TestLineContinuationCRLF()
{
DelimitedRecordParserFactory factory = new DelimitedRecordParserFactory
{
Delimiter = ',',
LineContinuationCharacter = '\\'
};
DelimitedReader reader = CreateReader(factory, "1,2,\\\r\n3,4");
Assert.Equal(new[] { "1", "2", "3", "4" }, reader.Read());
Assert.Equal(1, reader.RecordLineNumber);
Assert.Null(reader.Read());
}
[Fact]
public void TestLineContinuationIgnored()
{
DelimitedRecordParserFactory factory = new DelimitedRecordParserFactory
{
Delimiter = ',',
LineContinuationCharacter = '\\'
};
DelimitedReader reader = CreateReader(factory, "1,2,\\3,4");
Assert.Equal(new[] { "1", "2", "\\3", "4" }, reader.Read());
Assert.Equal(1, reader.RecordLineNumber);
Assert.Null(reader.Read());
}
[Fact]
public void TestLineContinuationAndEscape()
{
DelimitedRecordParserFactory factory = new DelimitedRecordParserFactory
{
Delimiter = ',',
LineContinuationCharacter = '\\',
Escape = '\\'
};
DelimitedReader reader = CreateReader(factory, "1,2,\\3,4");
Assert.Equal(new[] { "1", "2", "\\3", "4" }, reader.Read());
Assert.Equal(1, reader.RecordLineNumber);
Assert.Null(reader.Read());
}
[Fact]
public void TestLineNumber()
{
DelimitedRecordParserFactory factory = new DelimitedRecordParserFactory
{
Delimiter = ',',
LineContinuationCharacter = '\\'
};
DelimitedReader reader = CreateReader(factory, "1,2,\\\n3,4\n5,6");
Assert.Equal(new[] { "1", "2", "3", "4" }, reader.Read());
Assert.Equal("1,2,\\\n3,4", reader.RecordText);
Assert.Equal(1, reader.RecordLineNumber);
Assert.Equal(new[] { "5", "6" }, reader.Read());
Assert.Equal(3, reader.RecordLineNumber);
Assert.Null(reader.Read());
}
[Fact]
public void TestLineContinuationError()
{
DelimitedRecordParserFactory factory = new DelimitedRecordParserFactory
{
Delimiter = ',',
LineContinuationCharacter = '\\'
};
DelimitedReader reader = CreateReader(factory, "1,2,\\");
Assert.Throws<RecordIOException>(() => reader.Read());
}
[Fact]
public void TestCustomLineContinuation()
{
DelimitedRecordParserFactory factory = new DelimitedRecordParserFactory
{
Delimiter = ',',
LineContinuationCharacter = '#'
};
DelimitedReader reader = CreateReader(factory, "1,2,#\n3,4");
Assert.Equal(reader.Read(), new[] { "1", "2", "3", "4" });
Assert.Null(reader.Read());
}
[Fact]
public void TestLF()
{
DelimitedRecordParserFactory factory = new DelimitedRecordParserFactory();
DelimitedReader reader = CreateReader(factory, "1\t2\n3\t4");
Assert.Equal(reader.Read(), new[] { "1", "2" });
Assert.Equal(reader.Read(), new[] { "3", "4" });
Assert.Null(reader.Read());
}
[Fact]
public void TestCRLF()
{
DelimitedRecordParserFactory factory = new DelimitedRecordParserFactory();
DelimitedReader reader = CreateReader(factory, "1\t2\r\n3\t4");
Assert.Equal(reader.Read(), new[] { "1", "2" });
Assert.Equal(reader.Read(), new[] { "3", "4" });
Assert.Null(reader.Read());
}
[Fact]
public void TestCR()
{
DelimitedRecordParserFactory factory = new DelimitedRecordParserFactory();
DelimitedReader reader = CreateReader(factory, "1\t2\r3\t4");
Assert.Equal(reader.Read(), new[] { "1", "2" });
Assert.Equal(reader.Read(), new[] { "3", "4" });
Assert.Null(reader.Read());
}
[Fact]
public void TestRecordTerminator()
{
DelimitedRecordParserFactory factory = new DelimitedRecordParserFactory
{
Delimiter = ',',
LineContinuationCharacter = '\\',
RecordTerminator = "*"
};
DelimitedReader reader = CreateReader(factory, "1,2,*,4\n5,6,\\*7*");
Assert.Equal(new[] { "1", "2", string.Empty, }, reader.Read());
Assert.Equal("1,2,", reader.RecordText);
Assert.Equal(0, reader.RecordLineNumber);
Assert.Equal(new[] { string.Empty, "4\n5", "6", "7" }, reader.Read());
Assert.Equal(0, reader.RecordLineNumber);
Assert.Null(reader.Read());
Assert.Equal(-1, reader.RecordLineNumber);
}
[Fact]
public void TestClose()
{
DelimitedReader reader = new DelimitedReader(new StringReader(string.Empty));
reader.Close();
}
[Fact]
public void TestDelimiterCannotMatchContinuation()
{
DelimitedParserConfiguration config = new DelimitedParserConfiguration(',') { LineContinuationCharacter = ',' };
Assert.Throws<BeanIOConfigurationException>(() => new DelimitedReader(new StringReader(string.Empty), config));
}
[Fact]
public void TestDelimiterCannotMatchEscape()
{
DelimitedParserConfiguration config = new DelimitedParserConfiguration(',') { Escape = ',' };
Assert.Throws<BeanIOConfigurationException>(() => new DelimitedReader(new StringReader(string.Empty), config));
}
[Fact]
public void TestMalformedRecordAtEOF()
{
DelimitedParserConfiguration config = new DelimitedParserConfiguration(',')
{
Delimiter = ',',
LineContinuationCharacter = '\\'
};
var input = new StrictStringReader("hi\\");
RecordIOException error = null;
DelimitedReader reader = new DelimitedReader(input, config);
try
{
reader.Read();
}
catch (RecordIOException ex)
{
error = ex;
}
Assert.NotNull(error);
Assert.Null(reader.Read());
}
private DelimitedReader CreateReader(DelimitedRecordParserFactory factory, string input)
{
return (DelimitedReader)factory.CreateReader(CreateInput(input));
}
private TextReader CreateInput(string s)
{
return new StringReader(s);
}
}
}
| |
//
// ArithmeticExpression.cs.cs
//
// This file was generated by XMLSPY 2004 Enterprise Edition.
//
// YOU SHOULD NOT MODIFY THIS FILE, BECAUSE IT WILL BE
// OVERWRITTEN WHEN YOU RE-RUN CODE GENERATION.
//
// Refer to the XMLSPY Documentation for further details.
// http://www.altova.com/xmlspy
//
using System;
using System.Collections;
using System.Xml;
using Altova.Types;
namespace XMLRules
{
public class ArithmeticExpression : Altova.Node
{
#region Forward constructors
public ArithmeticExpression() : base() { SetCollectionParents(); }
public ArithmeticExpression(XmlDocument doc) : base(doc) { SetCollectionParents(); }
public ArithmeticExpression(XmlNode node) : base(node) { SetCollectionParents(); }
public ArithmeticExpression(Altova.Node node) : base(node) { SetCollectionParents(); }
#endregion // Forward constructors
public override void AdjustPrefix()
{
int nCount;
nCount = DomChildCount(NodeType.Element, "", "SubExpression");
for (int i = 0; i < nCount; i++)
{
XmlNode DOMNode = GetDomChildAt(NodeType.Element, "", "SubExpression", i);
InternalAdjustPrefix(DOMNode, true);
new SubExpressionType(DOMNode).AdjustPrefix();
}
nCount = DomChildCount(NodeType.Element, "", "Value");
for (int i = 0; i < nCount; i++)
{
XmlNode DOMNode = GetDomChildAt(NodeType.Element, "", "Value", i);
InternalAdjustPrefix(DOMNode, true);
new Value(DOMNode).AdjustPrefix();
}
}
#region SubExpression accessor methods
public int GetSubExpressionMinCount()
{
return 1;
}
public int SubExpressionMinCount
{
get
{
return 1;
}
}
public int GetSubExpressionMaxCount()
{
return 1;
}
public int SubExpressionMaxCount
{
get
{
return 1;
}
}
public int GetSubExpressionCount()
{
return DomChildCount(NodeType.Element, "", "SubExpression");
}
public int SubExpressionCount
{
get
{
return DomChildCount(NodeType.Element, "", "SubExpression");
}
}
public bool HasSubExpression()
{
return HasDomChild(NodeType.Element, "", "SubExpression");
}
public SubExpressionType GetSubExpressionAt(int index)
{
return new SubExpressionType(GetDomChildAt(NodeType.Element, "", "SubExpression", index));
}
public SubExpressionType GetSubExpression()
{
return GetSubExpressionAt(0);
}
public SubExpressionType SubExpression
{
get
{
return GetSubExpressionAt(0);
}
}
public void RemoveSubExpressionAt(int index)
{
RemoveDomChildAt(NodeType.Element, "", "SubExpression", index);
}
public void RemoveSubExpression()
{
while (HasSubExpression())
RemoveSubExpressionAt(0);
}
public void AddSubExpression(SubExpressionType newValue)
{
AppendDomElement("", "SubExpression", newValue);
}
public void InsertSubExpressionAt(SubExpressionType newValue, int index)
{
InsertDomElementAt("", "SubExpression", index, newValue);
}
public void ReplaceSubExpressionAt(SubExpressionType newValue, int index)
{
ReplaceDomElementAt("", "SubExpression", index, newValue);
}
#endregion // SubExpression accessor methods
#region SubExpression collection
public SubExpressionCollection MySubExpressions = new SubExpressionCollection( );
public class SubExpressionCollection: IEnumerable
{
ArithmeticExpression parent;
public ArithmeticExpression Parent
{
set
{
parent = value;
}
}
public SubExpressionEnumerator GetEnumerator()
{
return new SubExpressionEnumerator(parent);
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
}
public class SubExpressionEnumerator: IEnumerator
{
int nIndex;
ArithmeticExpression parent;
public SubExpressionEnumerator(ArithmeticExpression par)
{
parent = par;
nIndex = -1;
}
public void Reset()
{
nIndex = -1;
}
public bool MoveNext()
{
nIndex++;
return(nIndex < parent.SubExpressionCount );
}
public SubExpressionType Current
{
get
{
return(parent.GetSubExpressionAt(nIndex));
}
}
object IEnumerator.Current
{
get
{
return(Current);
}
}
}
#endregion // SubExpression collection
#region Value accessor methods
public int GetValueMinCount()
{
return 1;
}
public int ValueMinCount
{
get
{
return 1;
}
}
public int GetValueMaxCount()
{
return 1;
}
public int ValueMaxCount
{
get
{
return 1;
}
}
public int GetValueCount()
{
return DomChildCount(NodeType.Element, "", "Value");
}
public int ValueCount
{
get
{
return DomChildCount(NodeType.Element, "", "Value");
}
}
public bool HasValue()
{
return HasDomChild(NodeType.Element, "", "Value");
}
public Value GetValueAt(int index)
{
return new Value(GetDomChildAt(NodeType.Element, "", "Value", index));
}
public Value GetValue()
{
return GetValueAt(0);
}
public Value Value
{
get
{
return GetValueAt(0);
}
}
public void RemoveValueAt(int index)
{
RemoveDomChildAt(NodeType.Element, "", "Value", index);
}
public void RemoveValue()
{
while (HasValue())
RemoveValueAt(0);
}
public void AddValue(Value newValue)
{
AppendDomElement("", "Value", newValue);
}
public void InsertValueAt(Value newValue, int index)
{
InsertDomElementAt("", "Value", index, newValue);
}
public void ReplaceValueAt(Value newValue, int index)
{
ReplaceDomElementAt("", "Value", index, newValue);
}
#endregion // Value accessor methods
#region Value collection
public ValueCollection MyValues = new ValueCollection( );
public class ValueCollection: IEnumerable
{
ArithmeticExpression parent;
public ArithmeticExpression Parent
{
set
{
parent = value;
}
}
public ValueEnumerator GetEnumerator()
{
return new ValueEnumerator(parent);
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
}
public class ValueEnumerator: IEnumerator
{
int nIndex;
ArithmeticExpression parent;
public ValueEnumerator(ArithmeticExpression par)
{
parent = par;
nIndex = -1;
}
public void Reset()
{
nIndex = -1;
}
public bool MoveNext()
{
nIndex++;
return(nIndex < parent.ValueCount );
}
public Value Current
{
get
{
return(parent.GetValueAt(nIndex));
}
}
object IEnumerator.Current
{
get
{
return(Current);
}
}
}
#endregion // Value collection
private void SetCollectionParents()
{
MySubExpressions.Parent = this;
MyValues.Parent = this;
}
}
}
| |
using Lucene.Net.Analysis;
using Lucene.Net.Diagnostics;
using Lucene.Net.Documents;
using Lucene.Net.Index;
using Lucene.Net.Store;
using Lucene.Net.Util;
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using Assert = Lucene.Net.TestFramework.Assert;
using Directory = Lucene.Net.Store.Directory;
namespace Lucene.Net.Search
{
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/// <summary>
/// This is a <see cref="MultiReader"/> that can be used for randomly wrapping other readers
/// without creating <see cref="FieldCache"/> insanity.
/// The trick is to use an opaque/fake cache key.
/// </summary>
public class FCInvisibleMultiReader : MultiReader
{
internal readonly object cacheKey = new object();
public FCInvisibleMultiReader(params IndexReader[] readers)
: base(readers)
{
}
public override object CoreCacheKey => cacheKey;
public override object CombinedCoreAndDeletesKey => cacheKey;
}
/// <summary>
/// Utility class for sanity-checking queries.
/// </summary>
public static class QueryUtils // LUCENENET specific - made static because all members are static
{
/// <summary>
/// Check the types of things query objects should be able to do. </summary>
public static void Check(Query q)
{
CheckHashEquals(q);
}
/// <summary>
/// Check very basic <see cref="object.GetHashCode()"/> and <see cref="object.Equals(object)"/>. </summary>
public static void CheckHashEquals(Query q)
{
Query q2 = (Query)q.Clone();
CheckEqual(q, q2);
Query q3 = (Query)q.Clone();
q3.Boost = 7.21792348f;
CheckUnequal(q, q3);
// test that a class check is done so that no exception is thrown
// in the implementation of equals()
Query whacky = new QueryAnonymousInnerClassHelper();
whacky.Boost = q.Boost;
CheckUnequal(q, whacky);
// null test
Assert.IsFalse(q.Equals(null));
}
private class QueryAnonymousInnerClassHelper : Query
{
public QueryAnonymousInnerClassHelper()
{
}
public override string ToString(string field)
{
return "My Whacky Query";
}
}
public static void CheckEqual(Query q1, Query q2)
{
Assert.IsTrue(q1.Equals(q2));
Assert.AreEqual(q1, q2);
Assert.AreEqual(q1.GetHashCode(), q2.GetHashCode());
}
public static void CheckUnequal(Query q1, Query q2)
{
Assert.IsFalse(q1.Equals(q2), q1 + " equal to " + q2);
Assert.IsFalse(q2.Equals(q1), q2 + " equal to " + q1);
// possible this test can fail on a hash collision... if that
// happens, please change test to use a different example.
Assert.IsTrue(q1.GetHashCode() != q2.GetHashCode());
}
/// <summary>
/// Deep check that explanations of a query 'score' correctly. </summary>
public static void CheckExplanations(Query q, IndexSearcher s)
{
CheckHits.CheckExplanations(q, null, s, true);
}
#if !FEATURE_INSTANCE_TESTDATA_INITIALIZATION
/// <summary>
/// Various query sanity checks on a searcher, some checks are only done for
/// instance of <see cref="IndexSearcher"/>.
/// </summary>
/// <param name="random">A random instance (usually <see cref="LuceneTestCase.Random"/>).</param>
/// <param name="q1">A <see cref="Query"/>.</param>
/// <param name="s">An <see cref="IndexSearcher"/>.</param>
/// <seealso cref="Check(Query)"/>
/// <seealso cref="CheckFirstSkipTo(Query, IndexSearcher)"/>
/// <seealso cref="CheckSkipTo(Query, IndexSearcher)"/>
/// <seealso cref="CheckExplanations(Query, IndexSearcher)"/>
/// <seealso cref="CheckEqual(Query, Query)"/>
public static void Check(Random random, Query q1, IndexSearcher s)
{
Check(random, q1, s, true);
}
public static void Check(Random random, Query q1, IndexSearcher s, bool wrap)
{
try
{
Check(q1);
if (s != null)
{
CheckFirstSkipTo(q1, s);
CheckSkipTo(q1, s);
if (wrap)
{
Check(random, q1, WrapUnderlyingReader(random, s, -1), false);
Check(random, q1, WrapUnderlyingReader(random, s, 0), false);
Check(random, q1, WrapUnderlyingReader(random, s, +1), false);
}
CheckExplanations(q1, s);
Query q2 = (Query)q1.Clone();
CheckEqual(s.Rewrite(q1), s.Rewrite(q2));
}
}
catch (IOException e)
{
throw new Exception(e.ToString(), e);
}
}
#else
/// <summary>
/// Various query sanity checks on a searcher, some checks are only done for
/// instance of <see cref="IndexSearcher"/>.
/// </summary>
/// <param name="luceneTestCase"> The current test instance. </param>
/// <param name="random">A random instance (usually <see cref="LuceneTestCase.Random"/>).</param>
/// <param name="q1">A <see cref="Query"/>.</param>
/// <param name="s">An <see cref="IndexSearcher"/>.</param>
/// <seealso cref="Check(Query)"/>
/// <seealso cref="CheckFirstSkipTo(LuceneTestCase, Query, IndexSearcher)"/>
/// <seealso cref="CheckSkipTo(LuceneTestCase, Query, IndexSearcher)"/>
/// <seealso cref="CheckExplanations(Query, IndexSearcher)"/>
/// <seealso cref="CheckEqual(Query, Query)"/>
// LUCENENET specific
// Removes static dependency on <see cref="LuceneTestCase.ClassEnvRule.Similarity"/>
public static void Check(LuceneTestCase luceneTestCase, Random random, Query q1, IndexSearcher s)
{
Check(luceneTestCase, random, q1, s, true);
}
/// <param name="luceneTestCase">The current test instance.</param>
// LUCENENET specific
// Removes dependency on <see cref="LuceneTestCase.ClassEnv.Similarity"/>
public static void Check(LuceneTestCase luceneTestCase, Random random, Query q1, IndexSearcher s, bool wrap)
{
try
{
Check(q1);
if (s != null)
{
CheckFirstSkipTo(luceneTestCase, q1, s);
CheckSkipTo(luceneTestCase, q1, s);
if (wrap)
{
Check(luceneTestCase, random, q1, WrapUnderlyingReader(luceneTestCase, random, s, -1), false);
Check(luceneTestCase, random, q1, WrapUnderlyingReader(luceneTestCase, random, s, 0), false);
Check(luceneTestCase, random, q1, WrapUnderlyingReader(luceneTestCase, random, s, +1), false);
}
CheckExplanations(q1, s);
Query q2 = (Query)q1.Clone();
CheckEqual(s.Rewrite(q1), s.Rewrite(q2));
}
}
catch (IOException e)
{
throw new Exception(e.ToString(), e);
}
}
#endif
public static void PurgeFieldCache(IndexReader r)
{
// this is just a hack, to get an atomic reader that contains all subreaders for insanity checks
FieldCache.DEFAULT.PurgeByCacheKey(SlowCompositeReaderWrapper.Wrap(r).CoreCacheKey);
}
// LUCENENET specific - de-nested FCInvisibleMultiReader
#if !FEATURE_INSTANCE_TESTDATA_INITIALIZATION
/// <summary>
/// Given an <see cref="IndexSearcher"/>, returns a new <see cref="IndexSearcher"/> whose <see cref="IndexReader"/>
/// is a <see cref="MultiReader"/> containing the <see cref="IndexReader"/> of the original <see cref="IndexSearcher"/>,
/// as well as several "empty" <see cref="IndexReader"/>s -- some of which will have
/// deleted documents in them. This new <see cref="IndexSearcher"/> should
/// behave exactly the same as the original <see cref="IndexSearcher"/>. </summary>
/// <param name="s"> The searcher to wrap. </param>
/// <param name="edge"> If negative, s will be the first sub; if 0, s will be in the middle, if positive s will be the last sub. </param>
public static IndexSearcher WrapUnderlyingReader(Random random, IndexSearcher s, int edge)
#else
/// <summary>
/// Given an <see cref="IndexSearcher"/>, returns a new <see cref="IndexSearcher"/> whose <see cref="IndexReader"/>
/// is a <see cref="MultiReader"/> containing the <see cref="IndexReader"/> of the original <see cref="IndexSearcher"/>,
/// as well as several "empty" <see cref="IndexReader"/>s -- some of which will have
/// deleted documents in them. This new <see cref="IndexSearcher"/> should
/// behave exactly the same as the original <see cref="IndexSearcher"/>. </summary>
/// <param name="luceneTestCase">The current test instance.</param>
/// <param name="s"> The searcher to wrap. </param>
/// <param name="edge"> If negative, s will be the first sub; if 0, s will be in the middle, if positive s will be the last sub. </param>
// LUCENENET specific
// Removes dependency on <see cref="LuceneTestCase.ClassEnv.Similarity"/>
public static IndexSearcher WrapUnderlyingReader(LuceneTestCase luceneTestCase, Random random, IndexSearcher s, int edge)
#endif
{
IndexReader r = s.IndexReader;
// we can't put deleted docs before the nested reader, because
// it will throw off the docIds
IndexReader[] readers = new IndexReader[] {
edge < 0 ? r : emptyReaders[0],
emptyReaders[0],
new FCInvisibleMultiReader(edge < 0 ? emptyReaders[4] : emptyReaders[0],
emptyReaders[0],
0 == edge ? r : emptyReaders[0]),
0 < edge ? emptyReaders[0] : emptyReaders[7],
emptyReaders[0],
new FCInvisibleMultiReader(0 < edge ? emptyReaders[0] : emptyReaders[5],
emptyReaders[0],
0 < edge ? r : emptyReaders[0])
};
IndexSearcher @out = LuceneTestCase.NewSearcher(
#if FEATURE_INSTANCE_TESTDATA_INITIALIZATION
luceneTestCase,
#endif
new FCInvisibleMultiReader(readers));
@out.Similarity = s.Similarity;
return @out;
}
internal static readonly IndexReader[] emptyReaders = LoadEmptyReaders();
private static IndexReader[] LoadEmptyReaders() // LUCENENET: Avoid static constructors (see https://github.com/apache/lucenenet/pull/224#issuecomment-469284006)
{
var emptyReaders = new IndexReader[8];
try
{
emptyReaders[0] = new MultiReader();
emptyReaders[4] = MakeEmptyIndex(new Random(0), 4);
emptyReaders[5] = MakeEmptyIndex(new Random(0), 5);
emptyReaders[7] = MakeEmptyIndex(new Random(0), 7);
}
catch (IOException ex)
{
throw new Exception(ex.ToString(), ex);
}
return emptyReaders;
}
private static IndexReader MakeEmptyIndex(Random random, int numDocs)
{
if (Debugging.AssertsEnabled) Debugging.Assert(numDocs > 0);
Directory d = new MockDirectoryWrapper(random, new RAMDirectory());
IndexWriter w = new IndexWriter(d, new IndexWriterConfig(LuceneTestCase.TEST_VERSION_CURRENT, new MockAnalyzer(random)));
for (int i = 0; i < numDocs; i++)
{
w.AddDocument(new Document());
}
w.ForceMerge(1);
w.Commit();
w.Dispose();
DirectoryReader reader = DirectoryReader.Open(d);
return new AllDeletedFilterReader(LuceneTestCase.GetOnlySegmentReader(reader));
}
#if !FEATURE_INSTANCE_TESTDATA_INITIALIZATION
/// <summary>
/// Alternate scorer skipTo(),skipTo(),next(),next(),skipTo(),skipTo(), etc
/// and ensure a hitcollector receives same docs and scores.
/// </summary>
public static void CheckSkipTo(Query q, IndexSearcher s)
#else
/// <summary>
/// Alternate scorer skipTo(),skipTo(),next(),next(),skipTo(),skipTo(), etc
/// and ensure a hitcollector receives same docs and scores.
/// </summary>
/// <param name="luceneTestCase">The current test instance.</param>
/// <param name="q"></param>
/// <param name="s"></param>
// LUCENENET specific
// Removes dependency on <see cref="LuceneTestCase.ClassEnv.Similarity"/>
public static void CheckSkipTo(LuceneTestCase luceneTestCase, Query q, IndexSearcher s)
#endif
{
//System.out.println("Checking "+q);
IList<AtomicReaderContext> readerContextArray = s.TopReaderContext.Leaves;
if (s.CreateNormalizedWeight(q).ScoresDocsOutOfOrder) // in this case order of skipTo() might differ from that of next().
{
return;
}
const int skip_op = 0;
const int next_op = 1;
int[][] orders = new int[][] { new int[] { next_op }, new int[] { skip_op }, new int[] { skip_op, next_op }, new int[] { next_op, skip_op }, new int[] { skip_op, skip_op, next_op, next_op }, new int[] { next_op, next_op, skip_op, skip_op }, new int[] { skip_op, skip_op, skip_op, next_op, next_op } };
for (int k = 0; k < orders.Length; k++)
{
int[] order = orders[k];
// System.out.print("Order:");for (int i = 0; i < order.Length; i++)
// System.out.print(order[i]==skip_op ? " skip()":" next()");
// System.out.println();
int[] opidx = new int[] { 0 };
int[] lastDoc = new int[] { -1 };
// FUTURE: ensure scorer.Doc()==-1
const float maxDiff = 1e-5f;
AtomicReader[] lastReader = new AtomicReader[] { null };
s.Search(q, new CollectorAnonymousInnerClassHelper(
#if FEATURE_INSTANCE_TESTDATA_INITIALIZATION
luceneTestCase,
#endif
q, s, readerContextArray, skip_op, order, opidx, lastDoc, maxDiff, lastReader));
if (lastReader[0] != null)
{
// confirm that skipping beyond the last doc, on the
// previous reader, hits NO_MORE_DOCS
AtomicReader previousReader = lastReader[0];
IndexSearcher indexSearcher = LuceneTestCase.NewSearcher(
#if FEATURE_INSTANCE_TESTDATA_INITIALIZATION
luceneTestCase,
#endif
previousReader, false);
indexSearcher.Similarity = s.Similarity;
Weight w = indexSearcher.CreateNormalizedWeight(q);
AtomicReaderContext ctx = (AtomicReaderContext)previousReader.Context;
Scorer scorer = w.GetScorer(ctx, ((AtomicReader)ctx.Reader).LiveDocs);
if (scorer != null)
{
bool more = scorer.Advance(lastDoc[0] + 1) != DocIdSetIterator.NO_MORE_DOCS;
Assert.IsFalse(more, "query's last doc was " + lastDoc[0] + " but skipTo(" + (lastDoc[0] + 1) + ") got to " + scorer.DocID);
}
}
}
}
private class CollectorAnonymousInnerClassHelper : ICollector
{
#if FEATURE_INSTANCE_TESTDATA_INITIALIZATION
private readonly LuceneTestCase luceneTestCase;
#endif
private readonly Query q;
private readonly IndexSearcher s;
private readonly IList<AtomicReaderContext> readerContextArray;
private readonly int skip_op;
private readonly int[] order;
private readonly int[] opidx;
private readonly int[] lastDoc;
private readonly float maxDiff;
private readonly AtomicReader[] lastReader;
public CollectorAnonymousInnerClassHelper(
#if FEATURE_INSTANCE_TESTDATA_INITIALIZATION
LuceneTestCase luceneTestCase,
#endif
Query q, IndexSearcher s, IList<AtomicReaderContext> readerContextArray,
int skip_op, int[] order, int[] opidx, int[] lastDoc, float maxDiff, AtomicReader[] lastReader)
{
#if FEATURE_INSTANCE_TESTDATA_INITIALIZATION
this.luceneTestCase = luceneTestCase;
#endif
this.q = q;
this.s = s;
this.readerContextArray = readerContextArray;
this.skip_op = skip_op;
this.order = order;
this.opidx = opidx;
this.lastDoc = lastDoc;
this.maxDiff = maxDiff;
this.lastReader = lastReader;
}
private Scorer sc;
private Scorer scorer;
private int leafPtr;
public virtual void SetScorer(Scorer scorer)
{
this.sc = scorer;
}
public virtual void Collect(int doc)
{
float score = sc.GetScore();
lastDoc[0] = doc;
try
{
if (scorer == null)
{
Weight w = s.CreateNormalizedWeight(q);
AtomicReaderContext context = readerContextArray[leafPtr];
scorer = w.GetScorer(context, (context.AtomicReader).LiveDocs);
}
int op = order[(opidx[0]++) % order.Length];
// System.out.println(op==skip_op ?
// "skip("+(sdoc[0]+1)+")":"next()");
bool more = op == skip_op ? scorer.Advance(scorer.DocID + 1) != DocIdSetIterator.NO_MORE_DOCS : scorer.NextDoc() != DocIdSetIterator.NO_MORE_DOCS;
int scorerDoc = scorer.DocID;
float scorerScore = scorer.GetScore();
float scorerScore2 = scorer.GetScore();
float scoreDiff = Math.Abs(score - scorerScore);
float scorerDiff = Math.Abs(scorerScore2 - scorerScore);
if (!more || doc != scorerDoc || scoreDiff > maxDiff || scorerDiff > maxDiff)
{
StringBuilder sbord = new StringBuilder();
for (int i = 0; i < order.Length; i++)
{
sbord.Append(order[i] == skip_op ? " skip()" : " next()");
}
throw new Exception("ERROR matching docs:" + "\n\t" + (doc != scorerDoc ? "--> " : "") + "doc=" + doc + ", scorerDoc=" + scorerDoc + "\n\t" + (!more ? "--> " : "") + "tscorer.more=" + more + "\n\t" + (scoreDiff > maxDiff ? "--> " : "") + "scorerScore=" + scorerScore + " scoreDiff=" + scoreDiff + " maxDiff=" + maxDiff + "\n\t" + (scorerDiff > maxDiff ? "--> " : "") + "scorerScore2=" + scorerScore2 + " scorerDiff=" + scorerDiff + "\n\thitCollector.Doc=" + doc + " score=" + score + "\n\t Scorer=" + scorer + "\n\t Query=" + q + " " + q.GetType().Name + "\n\t Searcher=" + s + "\n\t Order=" + sbord + "\n\t Op=" + (op == skip_op ? " skip()" : " next()"));
}
}
catch (IOException e)
{
throw new Exception(e.ToString(), e);
}
}
public virtual void SetNextReader(AtomicReaderContext context)
{
// confirm that skipping beyond the last doc, on the
// previous reader, hits NO_MORE_DOCS
if (lastReader[0] != null)
{
AtomicReader previousReader = lastReader[0];
IndexSearcher indexSearcher = LuceneTestCase.NewSearcher(
#if FEATURE_INSTANCE_TESTDATA_INITIALIZATION
luceneTestCase,
#endif
previousReader);
indexSearcher.Similarity = s.Similarity;
Weight w = indexSearcher.CreateNormalizedWeight(q);
AtomicReaderContext ctx = (AtomicReaderContext)indexSearcher.TopReaderContext;
Scorer scorer = w.GetScorer(ctx, ((AtomicReader)ctx.Reader).LiveDocs);
if (scorer != null)
{
bool more = scorer.Advance(lastDoc[0] + 1) != DocIdSetIterator.NO_MORE_DOCS;
Assert.IsFalse(more, "query's last doc was " + lastDoc[0] + " but skipTo(" + (lastDoc[0] + 1) + ") got to " + scorer.DocID);
}
leafPtr++;
}
lastReader[0] = (AtomicReader)context.Reader;
if (Debugging.AssertsEnabled) Debugging.Assert(readerContextArray[leafPtr].Reader == context.Reader);
this.scorer = null;
lastDoc[0] = -1;
}
public virtual bool AcceptsDocsOutOfOrder => false;
}
#if !FEATURE_INSTANCE_TESTDATA_INITIALIZATION
/// <summary>
/// Check that first skip on just created scorers always goes to the right doc.</summary>
public static void CheckFirstSkipTo(Query q, IndexSearcher s)
#else
/// <summary>
/// Check that first skip on just created scorers always goes to the right doc.</summary>
/// <param name="luceneTestCase"> The current test instance. </param>
/// <param name="q"></param>
/// <param name="s"></param>
// LUCENENET specific
// Removes dependency on <see cref="LuceneTestCase.ClassEnv.Similarity"/>
public static void CheckFirstSkipTo(LuceneTestCase luceneTestCase, Query q, IndexSearcher s)
#endif
{
//System.out.println("checkFirstSkipTo: "+q);
const float maxDiff = 1e-3f;
int[] lastDoc = new int[] { -1 };
AtomicReader[] lastReader = new AtomicReader[] { null };
IList<AtomicReaderContext> context = s.TopReaderContext.Leaves;
s.Search(q, new CollectorAnonymousInnerClassHelper2(
#if FEATURE_INSTANCE_TESTDATA_INITIALIZATION
luceneTestCase,
#endif
q, s, maxDiff, lastDoc, lastReader, context));
if (lastReader[0] != null)
{
// confirm that skipping beyond the last doc, on the
// previous reader, hits NO_MORE_DOCS
AtomicReader previousReader = lastReader[0];
IndexSearcher indexSearcher = LuceneTestCase.NewSearcher(
#if FEATURE_INSTANCE_TESTDATA_INITIALIZATION
luceneTestCase,
#endif
previousReader);
indexSearcher.Similarity = s.Similarity;
Weight w = indexSearcher.CreateNormalizedWeight(q);
Scorer scorer = w.GetScorer((AtomicReaderContext)indexSearcher.TopReaderContext, previousReader.LiveDocs);
if (scorer != null)
{
bool more = scorer.Advance(lastDoc[0] + 1) != DocIdSetIterator.NO_MORE_DOCS;
Assert.IsFalse(more, "query's last doc was " + lastDoc[0] + " but skipTo(" + (lastDoc[0] + 1) + ") got to " + scorer.DocID);
}
}
}
private class CollectorAnonymousInnerClassHelper2 : ICollector
{
#if FEATURE_INSTANCE_TESTDATA_INITIALIZATION
private readonly LuceneTestCase luceneTestCase;
#endif
private readonly Query q;
private readonly IndexSearcher s;
private readonly float maxDiff;
private readonly int[] lastDoc;
private readonly AtomicReader[] lastReader;
private readonly IList<AtomicReaderContext> context;
public CollectorAnonymousInnerClassHelper2(
#if FEATURE_INSTANCE_TESTDATA_INITIALIZATION
LuceneTestCase luceneTestCase,
#endif
Query q, IndexSearcher s, float maxDiff, int[] lastDoc, AtomicReader[] lastReader, IList<AtomicReaderContext> context)
{
#if FEATURE_INSTANCE_TESTDATA_INITIALIZATION
this.luceneTestCase = luceneTestCase;
#endif
this.q = q;
this.s = s;
this.maxDiff = maxDiff;
this.lastDoc = lastDoc;
this.lastReader = lastReader;
this.context = context;
}
private Scorer scorer;
private int leafPtr;
private IBits liveDocs;
public virtual void SetScorer(Scorer scorer)
{
this.scorer = scorer;
}
public virtual void Collect(int doc)
{
float score = scorer.GetScore();
try
{
long startMS = Environment.TickCount;
for (int i = lastDoc[0] + 1; i <= doc; i++)
{
Weight w = s.CreateNormalizedWeight(q);
Scorer scorer_ = w.GetScorer(context[leafPtr], liveDocs);
Assert.IsTrue(scorer_.Advance(i) != DocIdSetIterator.NO_MORE_DOCS, "query collected " + doc + " but skipTo(" + i + ") says no more docs!");
Assert.AreEqual(doc, scorer_.DocID, "query collected " + doc + " but skipTo(" + i + ") got to " + scorer_.DocID);
float skipToScore = scorer_.GetScore();
Assert.AreEqual(skipToScore, scorer_.GetScore(), maxDiff, "unstable skipTo(" + i + ") score!");
Assert.AreEqual(score, skipToScore, maxDiff, "query assigned doc " + doc + " a score of <" + score + "> but skipTo(" + i + ") has <" + skipToScore + ">!");
// Hurry things along if they are going slow (eg
// if you got SimpleText codec this will kick in):
if (i < doc && Environment.TickCount - startMS > 5)
{
i = doc - 1;
}
}
lastDoc[0] = doc;
}
catch (IOException e)
{
throw new Exception(e.ToString(), e);
}
}
public virtual void SetNextReader(AtomicReaderContext context)
{
// confirm that skipping beyond the last doc, on the
// previous reader, hits NO_MORE_DOCS
if (lastReader[0] != null)
{
AtomicReader previousReader = lastReader[0];
IndexSearcher indexSearcher = LuceneTestCase.NewSearcher(
#if FEATURE_INSTANCE_TESTDATA_INITIALIZATION
luceneTestCase,
#endif
previousReader);
indexSearcher.Similarity = s.Similarity;
Weight w = indexSearcher.CreateNormalizedWeight(q);
Scorer scorer = w.GetScorer((AtomicReaderContext)indexSearcher.TopReaderContext, previousReader.LiveDocs);
if (scorer != null)
{
bool more = scorer.Advance(lastDoc[0] + 1) != DocIdSetIterator.NO_MORE_DOCS;
Assert.IsFalse(more, "query's last doc was " + lastDoc[0] + " but skipTo(" + (lastDoc[0] + 1) + ") got to " + scorer.DocID);
}
leafPtr++;
}
lastReader[0] = (AtomicReader)context.Reader;
lastDoc[0] = -1;
liveDocs = ((AtomicReader)context.Reader).LiveDocs;
}
public virtual bool AcceptsDocsOutOfOrder => false;
}
}
}
| |
namespace More
{
using FluentAssertions;
using More.Globalization;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using Xunit;
public class DateTimeFormatProviderTest
{
[Theory]
[MemberData( nameof( NullDateTimeFormatData ) )]
public void date_time_format_provider_should_not_allow_null_format( Action<DateTimeFormatInfo> test )
{
// arrange
var dateTimeFormat = default( DateTimeFormatInfo );
// act
Action @new = () => test( dateTimeFormat );
// assert
@new.ShouldThrow<ArgumentNullException>().And.ParamName.Should().Be( nameof( dateTimeFormat ) );
}
[Theory]
[MemberData( nameof( NullCalendarData ) )]
public void date_time_provider_should_not_allow_null_calendar( Action<Calendar> test )
{
// arrange
var calendar = default( Calendar );
// act
Action @new = () => test( calendar );
// assert
@new.ShouldThrow<ArgumentNullException>().And.ParamName.Should().Be( nameof( calendar ) );
}
[Theory]
[MemberData( nameof( UnsupportedFormatTypesData ) )]
public void get_format_should_return_null_for_unsupported_types( DateTimeFormatProvider provider, Type formatType )
{
// arrange
// act
var format = provider.GetFormat( formatType );
// assert
format.Should().BeNull();
}
[Theory]
[MemberData( nameof( GetFormatData ) )]
public void get_format_should_return_expected_provider( DateTimeFormatProvider provider, Type formatType, object expected )
{
// arrange
// act
var format = provider.GetFormat( formatType );
// assert
format.Should().BeSameAs( expected );
}
[Theory]
[MemberData( nameof( DateTimeFormatProvidersData ) )]
public void format_should_allow_null_format_string( DateTimeFormatProvider provider )
{
// arrange
var date = new DateTime( 2010, 9, 29 );
var culture = CultureInfo.CurrentCulture;
// act
var format = provider.Format( null, date, culture );
// assert
format.Should().Be( date.ToString( culture ) );
}
[Theory]
[MemberData( nameof( DateTimeFormatProvidersData ) )]
public void format_should_allow_empty_format_string( DateTimeFormatProvider provider )
{
// arrange
var date = new DateTime( 2010, 9, 29 );
var culture = CultureInfo.CurrentCulture;
// act
var format = provider.Format( string.Empty, date, culture );
// assert
format.Should().Be( date.ToString( culture ) );
}
[Theory]
[MemberData( nameof( DateTimeFormatProvidersData ) )]
public void format_should_return_original_format_when_argument_is_null( DateTimeFormatProvider provider )
{
// arrange
var culture = CultureInfo.CurrentCulture;
// act
var format = provider.Format( "d", null, culture );
// assert
format.Should().Be( "d" );
}
[Theory]
[MemberData( nameof( DateTimeFormatProvidersData ) )]
public void format_should_return_original_format_when_argument_cannot_be_formatted( DateTimeFormatProvider provider )
{
// arrange
var arg = new object();
var culture = CultureInfo.CurrentCulture;
// act
var format = provider.Format( "d", arg, culture );
// assert
format.Should().Be( arg.ToString() );
}
[Theory]
[MemberData( nameof( MalformedLiteralStringsData ) )]
public void format_should_not_allow_malformed_literal_strings( DateTimeFormatProvider provider, string formatString )
{
// arrange
var date = new DateTime( 2010, 9, 29 );
// act
Action format = () => provider.Format( formatString, date, null );
// assert
format.ShouldThrow<FormatException>();
}
[Theory]
[MemberData( nameof( BuiltInCustomFormatStringData ) )]
public void format_should_return_expected_builtX2Din_custom_format_string( DateTimeFormatProvider provider, string format )
{
// arrange
var date = new DateTime( 2010, 9, 29 );
// act
var result = provider.Format( format, date, null );
// assert
result.Should().Be( date.ToString( format ) );
}
[Theory]
[MemberData( nameof( SemesterFormatData ) )]
public void format_semester_should_return_expected_string( DateTimeFormatProvider provider, string format, string expected )
{
// arrange
var date = new DateTime( 2010, 9, 29 );
// act
var result = provider.Format( format, date, null );
// assert
result.Should().Be( expected );
}
[Theory]
[MemberData( nameof( QuarterFormatData ) )]
public void format_quarter_should_return_expected_string( DateTimeFormatProvider provider, string format, string expected )
{
// arrange
var date = new DateTime( 2010, 9, 29 );
// act
var result = provider.Format( format, date, null );
// assert
result.Should().Be( expected );
}
[Theory]
[MemberData( nameof( CustomFormatData ) )]
public void format_should_return_expected_custom_format_string( Func<DateTime, string> test, string expected )
{
// arrange
var date = new DateTime( 2010, 9, 29 );
// act
var result = test( date );
// assert
result.Should().Be( expected );
}
[Theory]
[MemberData( nameof( CustomFormatAndCalendarData ) )]
public void format_should_return_expected_custom_format_string_with_custom_calendar( Func<DateTime, DateTimeFormatProvider, string> test, string expected )
{
// arrange
var date = new DateTime( 2010, 9, 29 );
var provider = new DateTimeFormatProvider( new GregorianFiscalCalendar( 7 ) );
// act
var result = test( date, provider );
// assert
result.Should().Be( expected );
}
[Theory]
[MemberData( nameof( MultipleFormatParameterData ) )]
public void string_format_should_return_custom_format_string_with_multiple_parameters( DateTimeFormatProvider provider, string format, object arg, string expected )
{
// arrange
var date = new DateTime( 2010, 9, 29 );
var args = new object[] { date, arg };
// act
var result = string.Format( provider, format, args );
// assert
result.Should().Be( expected );
}
[Fact]
public void format_should_return_custom_string_with_escape_sequence()
{
// arrange
var provider = new DateTimeFormatProvider( new GregorianFiscalCalendar( 7 ) );
var date = new DateTime( 2010, 9, 29 );
// act
var result = provider.Format( "'FY'\\'yy", date, null );
// assert
result.Should().Be( "FY'11" );
}
public static IEnumerable<object[]> NullDateTimeFormatData
{
get
{
yield return new object[] { new Action<DateTimeFormatInfo>( dti => new DateTimeFormatProvider( dti ) ) };
yield return new object[] { new Action<DateTimeFormatInfo>( dti => new DateTimeFormatProvider( dti, new GregorianCalendar() ) ) };
}
}
public static IEnumerable<object[]> NullCalendarData
{
get
{
yield return new object[] { new Action<Calendar>( c => new DateTimeFormatProvider( c ) ) };
yield return new object[] { new Action<Calendar>( c => new DateTimeFormatProvider( DateTimeFormatInfo.CurrentInfo, c ) ) };
}
}
public static IEnumerable<object[]> DateTimeFormatProvidersData
{
get
{
yield return new object[] { new DateTimeFormatProvider() };
yield return new object[] { new DateTimeFormatProvider( DateTimeFormatInfo.CurrentInfo ) };
yield return new object[] { new DateTimeFormatProvider( new GregorianCalendar() ) };
yield return new object[] { new DateTimeFormatProvider( DateTimeFormatInfo.CurrentInfo, new GregorianCalendar() ) };
}
}
public static IEnumerable<object[]> UnsupportedFormatTypesData
{
get
{
yield return new object[] { new DateTimeFormatProvider(), null };
yield return new object[] { new DateTimeFormatProvider(), typeof( string ) };
yield return new object[] { new DateTimeFormatProvider( DateTimeFormatInfo.CurrentInfo ), null };
yield return new object[] { new DateTimeFormatProvider( DateTimeFormatInfo.CurrentInfo ), typeof( string ) };
yield return new object[] { new DateTimeFormatProvider( new GregorianCalendar() ), null };
yield return new object[] { new DateTimeFormatProvider( new GregorianCalendar() ), typeof( string ) };
yield return new object[] { new DateTimeFormatProvider( DateTimeFormatInfo.CurrentInfo, new GregorianCalendar() ), null };
yield return new object[] { new DateTimeFormatProvider( DateTimeFormatInfo.CurrentInfo, new GregorianCalendar() ), typeof( string ) };
}
}
public static IEnumerable<object[]> GetFormatData
{
get
{
yield return new object[] { new DateTimeFormatProvider(), typeof( DateTimeFormatInfo ), DateTimeFormatInfo.CurrentInfo };
var expected = new DateTimeFormatProvider();
yield return new object[] { expected, typeof( ICustomFormatter ), expected };
yield return new object[] { new DateTimeFormatProvider( DateTimeFormatInfo.CurrentInfo ), typeof( DateTimeFormatInfo ), DateTimeFormatInfo.CurrentInfo };
expected = new DateTimeFormatProvider( DateTimeFormatInfo.CurrentInfo );
yield return new object[] { expected, typeof( ICustomFormatter ), expected };
yield return new object[] { new DateTimeFormatProvider( new GregorianCalendar() ), typeof( DateTimeFormatInfo ), DateTimeFormatInfo.CurrentInfo };
expected = new DateTimeFormatProvider( new GregorianCalendar() );
yield return new object[] { expected, typeof( ICustomFormatter ), expected };
yield return new object[] { new DateTimeFormatProvider( DateTimeFormatInfo.CurrentInfo, new GregorianCalendar() ), typeof( DateTimeFormatInfo ), DateTimeFormatInfo.CurrentInfo };
expected = new DateTimeFormatProvider( DateTimeFormatInfo.CurrentInfo, new GregorianCalendar() );
yield return new object[] { expected, typeof( ICustomFormatter ), expected };
}
}
public static IEnumerable<object[]> MalformedLiteralStringsData
{
get
{
foreach ( var provider in DateTimeFormatProvidersData.Select( d => d[0] ).Cast<DateTimeFormatProvider>() )
{
// missing closing ' in custom format string
yield return new object[] { provider, "'MM-dd-yyyy" };
// missing opening ' in custom format string
yield return new object[] { provider, "MM-dd-yyyy'" };
// missing closing " in custom format string
yield return new object[] { provider, "\"MM-dd-yyyy" };
// missing opening " in custom format string
yield return new object[] { provider, "MM-dd-yyyy\"" };
}
}
}
public static IEnumerable<object[]> BuiltInCustomFormatStringData
{
get
{
// custom string formats with one character must be prefixed with % to prevent confusion with the standard format strings
// REF: http://msdn.microsoft.com/en-us/library/8kb3ddd4.aspx#UsingSingleSpecifiers
var formats = new[]
{
"%d", "dd", "ddd", "dddd", "%f", "ff", "fff", "ffff", "fffff", "ffffff", "fffffff",
"%F", "FF", "FFF", "FFFF", "FFFFF", "FFFFFF", "FFFFFFF", "%g", "gg", "%h", "hh", "%H",
"HH", "%K", "%m", "mm", "%M", "MM", "MMM", "MMMM", "%s", "ss", "%t", "tt", "%y", "yy",
"yyy", "yyyy", "%z", "zz", "zzz"
};
foreach ( var provider in DateTimeFormatProvidersData.Select( d => d[0] ).Cast<DateTimeFormatProvider>() )
{
foreach ( var format in formats )
yield return new object[] { provider, format };
}
}
}
public static IEnumerable<object[]> SemesterFormatData
{
get
{
foreach ( var provider in DateTimeFormatProvidersData.Select( d => d[0] ).Cast<DateTimeFormatProvider>() )
{
yield return new object[] { provider, "S", "2" };
yield return new object[] { provider, "SS", "02" };
yield return new object[] { provider, "SSS", "H2" };
yield return new object[] { provider, "SSSS", "Semester 2" };
}
}
}
public static IEnumerable<object[]> QuarterFormatData
{
get
{
foreach ( var provider in DateTimeFormatProvidersData.Select( d => d[0] ).Cast<DateTimeFormatProvider>() )
{
yield return new object[] { provider, "q", "3" };
yield return new object[] { provider, "qq", "03" };
yield return new object[] { provider, "qqq", "Q3" };
yield return new object[] { provider, "qqqq", "Quarter 3" };
}
}
}
public static IEnumerable<object[]> CustomFormatData
{
get
{
foreach ( var provider in DateTimeFormatProvidersData.Select( d => d[0] ).Cast<DateTimeFormatProvider>() )
{
yield return new object[] { new Func<DateTime, string>( d => provider.Format( "'Year' yyyy, 'Semester' S, 'Quarter' q, 'Month' M, 'Day' d", d, null ) ), "Year 2010, Semester 2, Quarter 3, Month 9, Day 29" };
yield return new object[] { new Func<DateTime, string>( d => d.ToString( provider, "'Year' yyyy, 'Semester' S, 'Quarter' q, 'Month' M, 'Day' d" ) ), "Year 2010, Semester 2, Quarter 3, Month 9, Day 29" };
yield return new object[] { new Func<DateTime, string>( d => string.Format( provider, "{0:'Year' yyyy, 'Semester' S, 'Quarter' q, 'Month' M, 'Day' d}", d ) ), "Year 2010, Semester 2, Quarter 3, Month 9, Day 29" };
yield return new object[] { new Func<DateTime, string>( d => provider.Format( "'Year' yyyy, 'Semester' SS, 'Quarter' qq, 'Month' MM, 'Day' dd", d, null ) ), "Year 2010, Semester 02, Quarter 03, Month 09, Day 29" };
yield return new object[] { new Func<DateTime, string>( d => d.ToString( provider, "'Year' yyyy, 'Semester' SS, 'Quarter' qq, 'Month' MM, 'Day' dd" ) ), "Year 2010, Semester 02, Quarter 03, Month 09, Day 29" };
yield return new object[] { new Func<DateTime, string>( d => string.Format( provider, "{0:'Year' yyyy, 'Semester' SS, 'Quarter' qq, 'Month' MM, 'Day' dd}", d ) ), "Year 2010, Semester 02, Quarter 03, Month 09, Day 29" };
yield return new object[] { new Func<DateTime, string>( d => provider.Format( "\"Year\" yyyy, SSS, qqq, MMM, dd", d, null ) ), "Year 2010, H2, Q3, Sep, 29" };
yield return new object[] { new Func<DateTime, string>( d => d.ToString( provider, "\"Year\" yyyy, SSS, qqq, MMM, dd" ) ), "Year 2010, H2, Q3, Sep, 29" };
yield return new object[] { new Func<DateTime, string>( d => string.Format( provider, "{0:\"Year\" yyyy, SSS, qqq, MMM, dd}", d ) ), "Year 2010, H2, Q3, Sep, 29" };
yield return new object[] { new Func<DateTime, string>( d => provider.Format( "\"Year\" yyyy, SSSS, qqqq, MMMM, dd", d, null ) ), "Year 2010, Semester 2, Quarter 3, September, 29" };
yield return new object[] { new Func<DateTime, string>( d => d.ToString( provider, "\"Year\" yyyy, SSSS, qqqq, MMMM, dd" ) ), "Year 2010, Semester 2, Quarter 3, September, 29" };
yield return new object[] { new Func<DateTime, string>( d => string.Format( provider, "{0:\"Year\" yyyy, SSSS, qqqq, MMMM, dd}", d ) ), "Year 2010, Semester 2, Quarter 3, September, 29" };
}
}
}
public static IEnumerable<object[]> CustomFormatAndCalendarData
{
get
{
yield return new object[] { new Func<DateTime, DateTimeFormatProvider, string>( ( d, p ) => p.Format( "'Year' yyyy, 'Semester' S, 'Quarter' q, 'Month' M, 'Day' d", d, null ) ), "Year 2011, Semester 1, Quarter 1, Month 3, Day 29" };
yield return new object[] { new Func<DateTime, DateTimeFormatProvider, string>( ( d, p ) => d.ToString( p, "'Year' yyyy, 'Semester' S, 'Quarter' q, 'Month' M, 'Day' d" ) ), "Year 2011, Semester 1, Quarter 1, Month 3, Day 29" };
yield return new object[] { new Func<DateTime, DateTimeFormatProvider, string>( ( d, p ) => string.Format( p, "{0:'Year' yyyy, 'Semester' S, 'Quarter' q, 'Month' M, 'Day' d}", d ) ), "Year 2011, Semester 1, Quarter 1, Month 3, Day 29" };
yield return new object[] { new Func<DateTime, DateTimeFormatProvider, string>( ( d, p ) => p.Format( "'Year' yyyy, 'Semester' SS, 'Quarter' qq, 'Month' MM, 'Day' dd", d, null ) ), "Year 2011, Semester 01, Quarter 01, Month 03, Day 29" };
yield return new object[] { new Func<DateTime, DateTimeFormatProvider, string>( ( d, p ) => d.ToString( p, "'Year' yyyy, 'Semester' SS, 'Quarter' qq, 'Month' MM, 'Day' dd" ) ), "Year 2011, Semester 01, Quarter 01, Month 03, Day 29" };
yield return new object[] { new Func<DateTime, DateTimeFormatProvider, string>( ( d, p ) => string.Format( p, "{0:'Year' yyyy, 'Semester' SS, 'Quarter' qq, 'Month' MM, 'Day' dd}", d ) ), "Year 2011, Semester 01, Quarter 01, Month 03, Day 29" };
yield return new object[] { new Func<DateTime, DateTimeFormatProvider, string>( ( d, p ) => p.Format( "\"Year\" yyyy, SSS, qqq, MMM, dd", d, null ) ), "Year 2011, H1, Q1, Sep, 29" };
yield return new object[] { new Func<DateTime, DateTimeFormatProvider, string>( ( d, p ) => d.ToString( p, "\"Year\" yyyy, SSS, qqq, MMM, dd" ) ), "Year 2011, H1, Q1, Sep, 29" };
yield return new object[] { new Func<DateTime, DateTimeFormatProvider, string>( ( d, p ) => string.Format( p, "{0:\"Year\" yyyy, SSS, qqq, MMM, dd}", d ) ), "Year 2011, H1, Q1, Sep, 29" };
yield return new object[] { new Func<DateTime, DateTimeFormatProvider, string>( ( d, p ) => p.Format( "\"Year\" yyyy, SSSS, qqqq, MMMM, dd", d, null ) ), "Year 2011, Semester 1, Quarter 1, September, 29" };
yield return new object[] { new Func<DateTime, DateTimeFormatProvider, string>( ( d, p ) => d.ToString( p, "\"Year\" yyyy, SSSS, qqqq, MMMM, dd" ) ), "Year 2011, Semester 1, Quarter 1, September, 29" };
yield return new object[] { new Func<DateTime, DateTimeFormatProvider, string>( ( d, p ) => string.Format( p, "{0:\"Year\" yyyy, SSSS, qqqq, MMMM, dd}", d ) ), "Year 2011, Semester 1, Quarter 1, September, 29" };
}
}
public static IEnumerable<object[]> MultipleFormatParameterData
{
get
{
foreach ( var provider in DateTimeFormatProvidersData.Select( d => d[0] ).Cast<DateTimeFormatProvider>() )
{
yield return new object[] { provider, "{0:} - {1}", "A", "9/29/2010 12:00:00 AM - A" };
yield return new object[] { provider, "{0:'FY'yy} - {1}", "A", "FY10 - A" };
yield return new object[] { provider, "{0:qqq} - {1:N1}", 1, "Q3 - 1.0" };
}
}
}
}
}
| |
'From Squeak 1.21c of Aug 4, 1997 on 2 October 1997 at 1:21:31 am'!
"Change Set: TextMorphMods
Date: 1 October 1997
Author: Dan Ingalls
This is a complete rework of TextMorphs including...
InstVar paragraph is now only a cache - it can be nilled out at any time,
especially prior to duplicating or storing on a file.
All rectangles are now in morphic coordinates.
Text selection and type-in use morphic events throughout, so that (multiple)
remote hands will work in editing.
All changes propagate immediately out to the variables text and textStyle.
Lazy paragraph means that no layout gets wasted on default initial
contents when a textMorph is being created with other contents.
Bounds properly track growth and shrinkage due to editing, and
command halos track this properly.
Alignment can now be changed from a menu.
"
TextMorphEditor removeSelector: #processRedButton!
Object subclass: #KeyboardBuffer
instanceVariableNames: 'event eventUsed '
classVariableNames: ''
poolDictionaries: ''
category: 'Morphic-Support'!
Morph subclass: #TextMorph
instanceVariableNames: 'textStyle text wrapFlag paragraph editor '
classVariableNames: ''
poolDictionaries: ''
category: 'Morphic-Basic'!
ParagraphEditor subclass: #TextMorphEditor
instanceVariableNames: 'morph oldInterval pivotBlock '
classVariableNames: ''
poolDictionaries: ''
category: 'Morphic-Support'!
!HandMorph methodsFor: 'event dispatching' stamp: 'di 9/29/97 14:24'!
keyboardFocus
^ keyboardFocus! !
!HandMorph methodsFor: 'event dispatching' stamp: 'di 9/29/97 13:03'!
newKeyboardFocus: aMorphOrNil
"Make the given morph the new keyboard focus, canceling the previous keyboard focus if any. If the argument is nil, the current keyboard focus is cancelled."
| oldFocus |
oldFocus _ keyboardFocus.
keyboardFocus _ aMorphOrNil.
oldFocus ifNotNil: [oldFocus == aMorphOrNil ifFalse: [oldFocus keyboardFocusChange: false]].
aMorphOrNil ifNotNil: [aMorphOrNil keyboardFocusChange: true].! !
!KeyboardBuffer methodsFor: 'all' stamp: 'di 9/30/97 19:53'!
commandKeyPressed
^ event commandKeyPressed! !
!KeyboardBuffer methodsFor: 'all' stamp: 'di 9/30/97 19:54'!
controlKeyPressed
^ event controlKeyPressed! !
!KeyboardBuffer methodsFor: 'all' stamp: 'di 9/29/97 12:34'!
flushKeyboard
eventUsed ifFalse: [^ eventUsed _ true].! !
!KeyboardBuffer methodsFor: 'all' stamp: 'di 9/29/97 12:34'!
keyboard
eventUsed ifFalse: [eventUsed _ true. ^ event keyCharacter].
^ nil! !
!KeyboardBuffer methodsFor: 'all' stamp: 'di 9/29/97 12:34'!
keyboardPeek
eventUsed ifFalse: [^ event keyCharacter].
^ nil! !
!KeyboardBuffer methodsFor: 'all' stamp: 'di 9/29/97 12:34'!
keyboardPressed
^ eventUsed not! !
!KeyboardBuffer methodsFor: 'all' stamp: 'di 9/30/97 19:54'!
leftShiftDown
^ event shiftPressed! !
!ParagraphEditor methodsFor: 'menu messages' stamp: 'di 9/30/97 10:23'!
changeAlignment
| aList reply |
aList _ #(leftFlush centered justified rightFlush).
reply _ (SelectionMenu labelList: aList selections: aList) startUp.
reply ~~ nil ifTrue:
[paragraph perform: reply.
paragraph composeAll.
self recomputeSelection.
Display fill: paragraph clippingRectangle
fillColor: view backgroundColor. "very brute force"
self display.
"paragraph changed"].
^ true! !
!TextMorph methodsFor: 'initialization' stamp: 'di 9/30/97 09:25'!
initialize
super initialize.
color _ Color black.
textStyle _ TextStyle default copy.
wrapFlag _ true.
! !
!TextMorph methodsFor: 'initialization' stamp: 'di 9/29/97 11:48'!
text: t textStyle: s
"Private -- for use only in morphic duplication"
text _ t.
textStyle _ s! !
!TextMorph methodsFor: 'accessing' stamp: 'di 9/30/97 15:48'!
contents: stringOrText
^ self contentsAsIs: stringOrText! !
!TextMorph methodsFor: 'accessing' stamp: 'di 9/30/97 15:48'!
contentsAsIs: stringOrText
"Accept new text contents with line breaks only as in the text.
Fit my width and height to the result."
wrapFlag _ false.
self newContents: stringOrText! !
!TextMorph methodsFor: 'accessing' stamp: 'di 9/30/97 09:51'!
contentsWrapped: stringOrText
"Accept new text contents. Lay it out, wrapping within my current width.
Then fit my height to the result."
wrapFlag _ true.
self newContents: stringOrText! !
!TextMorph methodsFor: 'accessing' stamp: 'di 9/29/97 11:47'!
copyRecordingIn: dict
"Overridden to copy deeper text structure."
^ (super copyRecordingIn: dict)
text: text copy textStyle: textStyle copy! !
!TextMorph methodsFor: 'accessing' stamp: 'di 9/30/97 15:37'!
newContents: stringOrText
"Accept new text contents."
| newText |
newText _ stringOrText asText.
text = newText ifTrue: [^ self]. "No substantive change"
text _ newText.
self releaseParagraph. "update the paragraph cache"
self paragraph. "re-instantiate to set bounds"! !
!TextMorph methodsFor: 'alignment' stamp: 'di 9/29/97 13:21'!
centered
textStyle centered.
self changed! !
!TextMorph methodsFor: 'alignment' stamp: 'di 9/29/97 13:22'!
justified
textStyle justified.
self changed! !
!TextMorph methodsFor: 'alignment' stamp: 'di 9/29/97 13:21'!
leftFlush
textStyle leftFlush.
self changed! !
!TextMorph methodsFor: 'alignment' stamp: 'di 9/29/97 13:22'!
rightFlush
textStyle rightFlush.
self changed! !
!TextMorph methodsFor: 'drawing'!
drawOn: aCanvas
self hasFocus ifTrue:
[aCanvas fillRectangle: bounds color: Color white.
editor selectionRects do:
[:rect | aCanvas fillRectangle: rect color: self selectionColor]].
aCanvas paragraph: self paragraph bounds: bounds color: color.! !
!TextMorph methodsFor: 'drawing' stamp: 'di 9/30/97 10:40'!
selectionColor
^ Color lightRed
! !
!TextMorph methodsFor: 'editing' stamp: 'di 9/30/97 10:26'!
acceptContents
"The message is sent when the user hits enter or Cmd-S. Accept the current contents and end editing. This default implementation does nothing."
self updateFromParagraph! !
!TextMorph methodsFor: 'editing' stamp: 'di 9/30/97 10:27'!
chooseAlignment
self installEditor changeAlignment.
self updateFromParagraph! !
!TextMorph methodsFor: 'editing' stamp: 'di 9/30/97 10:27'!
chooseEmphasis
self installEditor changeEmphasis.
self updateFromParagraph! !
!TextMorph methodsFor: 'editing' stamp: 'di 9/30/97 10:28'!
chooseFont
self installEditor offerFontMenu.
self updateFromParagraph! !
!TextMorph methodsFor: 'editing' stamp: 'di 9/30/97 10:28'!
chooseStyle
self installEditor changeStyle.
self updateFromParagraph! !
!TextMorph methodsFor: 'editing' stamp: 'di 9/29/97 12:34'!
handlesMouseDown: evt
^ self uncoveredAt: evt cursorPoint! !
!TextMorph methodsFor: 'editing' stamp: 'di 9/29/97 11:46'!
hasFocus
^ editor ~~ nil! !
!TextMorph methodsFor: 'editing' stamp: 'di 9/29/97 11:58'!
keyboardFocusChange: aBoolean
aBoolean
ifTrue: ["A hand is wanting to send us characters..."
self hasFocus ifFalse: [self installEditor.
self changed]]
ifFalse: ["A hand has clicked elsewhere...".
((self world hands collect: [:h | h keyboardFocus]) includes: self)
ifFalse: [self releaseEditor.
self changed]].
! !
!TextMorph methodsFor: 'editing'!
keyStroke: evt
"Handle a keystroke event."
self installEditor.
editor sensor: (KeyboardBuffer new startingEvent: evt). "Make a version that takes an event"
editor readKeyboard.
self updateFromParagraph! !
!TextMorph methodsFor: 'editing' stamp: 'di 9/29/97 12:39'!
mouseDown: evt
"Make this TextMorph be the keyboard input focus, if it isn't already, and repond to the text selection gesture."
evt hand newKeyboardFocus: self. "This will install editor if nil"
editor mouseDown: evt.
self changed! !
!TextMorph methodsFor: 'editing' stamp: 'di 9/29/97 12:34'!
mouseMove: evt
evt redButtonPressed
ifTrue: [editor mouseMove: evt.
self changed].
! !
!TextMorph methodsFor: 'editing' stamp: 'di 9/29/97 12:34'!
mouseUp: evt
editor mouseUp: evt.
self changed! !
!TextMorph methodsFor: 'anchors' stamp: 'di 9/29/97 18:09'!
anchor: aMorph
"Set an anchor for this morph in the current text selection"
| anchor index |
editor ifNil: [^ self halt]. "No can do"
anchor _ TextMorphAnchor new
anchoredObject: aMorph
location: (self paragraph characterBlockForIndex: editor selectionInterval first) topLeft
- self position.
index _ editor selectionInterval first.
self removeAllAnchorsTo: aMorph.
text addAttribute: anchor from: index to: index! !
!TextMorph methodsFor: 'anchors' stamp: 'di 9/29/97 18:16'!
updateAnchors
| anchors ranges |
anchors _ OrderedCollection new.
text runsDoStartStopAndAttributes:
[:start :stop :attributes |
attributes do: [:att | (att isMemberOf: TextMorphAnchor) ifTrue: [anchors add: att]]].
anchors isEmpty ifTrue: [^ self].
anchors do:
[:a |
ranges _ text findAttribute: a.
"Update anchor location"
a newLocation: (self paragraph characterBlockForIndex: ranges first first) topLeft
- self position.
ranges size > 1 ifTrue:
[ranges allButFirst do: "Remove any other fragmentary references"
[:range | text removeAttribute: a from: range first to: range last]]].
self layoutChanged! !
!TextMorph methodsFor: 'geometry' stamp: 'di 9/30/97 15:36'!
extent: aPoint
self releaseEditor.
self releaseParagraph. "invalidate the paragraph cache"
super extent: (aPoint max: 20@20).
self fit! !
!TextMorph methodsFor: 'geometry' stamp: 'di 9/29/97 12:55'!
privateMoveBy: delta
self releaseEditor.
super privateMoveBy: delta.
! !
!TextMorph methodsFor: 'geometry' stamp: 'di 9/30/97 15:36'!
privateOwner: aMorph
self releaseParagraph. "invalidate the paragraph cache"
super privateOwner: aMorph! !
!TextMorph methodsFor: 'menu' stamp: 'di 9/30/97 10:15'!
addCustomMenuItems: aCustomMenu hand: aHandMorph
(submorphs isEmpty and: [editor ~~nil]) ifFalse:
[aCustomMenu add: 'set anchor' action: #anchorMorph:].
aCustomMenu add: 'remove all anchors' action: #removeAllAnchors.
aCustomMenu add: 'set font...' action: #chooseFont.
aCustomMenu add: 'set style...' action: #chooseStyle.
aCustomMenu add: 'set alignment...' action: #chooseAlignment.
! !
!TextMorph methodsFor: 'private' stamp: 'di 9/30/97 15:25'!
fit
"Adjust bounds vertically to fit the text."
| height extent |
wrapFlag ifTrue:
[height _ self paragraph height.
height ~= bounds height ifTrue: [super extent: bounds width @ height]]
ifFalse:
[extent _ self paragraph extent.
extent ~= bounds extent ifTrue: [super extent: extent]].
self updateAnchors.
self changed! !
!TextMorph methodsFor: 'private'!
installEditor
"Install an editor for my paragraph. This constitutes 'hasFocus'."
| editView |
editor ifNotNil: [^ self].
editor _ TextMorphEditor new morph: self.
editView _ DisplayTextView new model: self paragraph controller: editor.
editView window: self bounds viewport: self bounds.
editor changeParagraph: self paragraph.
^ editor! !
!TextMorph methodsFor: 'private'!
paragraph
"Paragraph instantiation is lazy -- create it only when needed"
| compWidth fullWidth |
paragraph ifNotNil: [^ paragraph].
text ifNil: [text _ 'Text' asText allBold]. "Default contents"
"...Code here to recreate the paragraph..."
compWidth _ wrapFlag ifTrue: [bounds width] ifFalse: [999999].
paragraph _ Paragraph basicNew.
fullWidth _ paragraph setWithText: text style: textStyle
compositionRectangle: (bounds topLeft extent: compWidth @ 999999)
clippingRectangle: bounds
foreColor: color backColor: Color white.
wrapFlag ifFalse:
[paragraph compositionRectangle:
(paragraph compositionRectangle withWidth: fullWidth)].
self fit.
^ paragraph! !
!TextMorph methodsFor: 'private' stamp: 'di 10/1/97 19:48'!
prepareToBeSaved
self releaseEditor; releaseParagraph! !
!TextMorph methodsFor: 'private'!
releaseEditor
"Release the editor for my paragraph. This morph no longer 'hasFocus'."
editor ifNotNil:
[self paragraph release.
editor _ nil].
self releaseParagraph "THIS IS A TEST!!"! !
!TextMorph methodsFor: 'private' stamp: 'di 9/30/97 15:35'!
releaseParagraph
"Paragraph instantiation is lazy -- it will be created only when needed"
paragraph ifNotNil:
[paragraph release.
paragraph _ nil]! !
!TextMorph methodsFor: 'private' stamp: 'di 10/2/97 01:20'!
updateFromParagraph
paragraph ifNil: [^ self].
wrapFlag ifNil: [wrapFlag _ true].
text _ paragraph text.
textStyle _ paragraph textStyle.
self fit! !
!TextMorph methodsFor: 'object fileIn' stamp: 'di 10/1/97 19:47'!
convertbosfceptthpeh0: varDict bosfcepttwpe0: smartRefStrm
"These variables are automatically stored into the new instance ('textStyle' 'text' 'paragraph' 'editor' ).
This method is for additional changes. Use statements like (foo _ varDict at: 'foo')."
"Be sure to to fill in ('wrapFlag' ) and deal with the information in ('hasFocus' 'hideSelection' )"
wrapFlag _ true.
editor _ nil.
self updateFromParagraph; releaseParagraph.! !
!TextMorphEditor methodsFor: 'all'!
mouseDown: evt
"An attempt to break up the old processRedButton code into threee phases"
| clickPoint |
oldInterval _ startBlock stringIndex to: stopBlock stringIndex - 1.
clickPoint _ evt cursorPoint.
(paragraph clickAt: clickPoint for: nil) ifTrue: [^ self].
self closeTypeIn. "probably not necess"
sensor leftShiftDown
ifFalse:
[stopBlock _ startBlock _ pivotBlock _
paragraph characterBlockAtPoint: clickPoint]
ifTrue:
[(self characterBlockAtPoint: clickPoint) <= startBlock
ifTrue: [stopBlock _ startBlock.
pivotBlock _ stopBlock]
ifFalse: [startBlock _ stopBlock.
pivotBlock _ startBlock]].
! !
!TextMorphEditor methodsFor: 'all'!
mouseMove: evt
"An attempt to break up the old processRedButton code into threee phases"
| dragBlock |
dragBlock _ paragraph characterBlockAtPoint: (evt cursorPoint).
dragBlock > pivotBlock
ifTrue: [stopBlock _ dragBlock. startBlock _ pivotBlock]
ifFalse: [startBlock _ dragBlock. stopBlock _ pivotBlock]! !
!TextMorphEditor methodsFor: 'all' stamp: 'di 9/29/97 12:34'!
mouseUp: evt
"An attempt to break up the old processRedButton code into threee phases"
(startBlock = stopBlock
and: [oldInterval = (startBlock stringIndex to: startBlock stringIndex-1)])
ifTrue: [self selectWord].
self setEmphasisHere.
(self isDisjointFrom: oldInterval) ifTrue:
[otherInterval _ oldInterval]! !
!TextMorphEditor methodsFor: 'all'!
scrollBy: ignore
"Ignore scroll requests."
self halt.! !
!TextMorphEditor methodsFor: 'all'!
select
"Ignore selection redraw requests."! !
!TextMorphEditor methodsFor: 'all' stamp: 'di 9/29/97 12:34'!
selectionRects
"Return an array of rectangles comprising the selection"
^ paragraph selectionRectsFrom: startBlock to: stopBlock! !
!TextMorphEditor methodsFor: 'all'!
updateMarker
"Ignore scrollbar redraw requests."
! !
!TextMorphEditor methodsFor: 'all' stamp: 'di 10/1/97 17:00'!
zapSelectionWith: aText
"**overridden to inhibit old-style display"
| start stop |
self deselect.
start _ startBlock stringIndex.
stop _ stopBlock stringIndex.
(start = stop and: [aText size = 0]) ifFalse:
[paragraph replaceFrom: start to: stop - 1
with: aText displaying: false. "** was true in super"
self computeIntervalFrom: start to: start + aText size - 1.
UndoInterval _ otherInterval _ self selectionInterval]! !
ParagraphEditor removeSelector: #selectionRects!
TextMorph removeSelector: #contentsClipped:!
TextMorph removeSelector: #screenRect!
TextMorph removeSelector: #text:textStyle:paragraph:!
TextMorphEditor removeSelector: #processRedButton!
TextMorphEditor removeSelector: #controlTerminate!
TextMorphEditor removeSelector: #clearStartAndStopBlocks!
TextMorph allSubInstancesDo: [:m | m updateFromParagraph; releaseParagraph]!
| |
using System;
using System.Runtime.InteropServices;
using Internal.Runtime.CompilerServices;
using System.Runtime.Serialization;
enum DataContractKind
{
Unknown ,
BooleanDataContract ,
ByteArrayDataContract ,
CharDataContract ,
DateTimeDataContract ,
DecimalDataContract ,
DoubleDataContract ,
FloatDataContract ,
GuidDataContract ,
IntDataContract ,
LongDataContract ,
ObjectDataContract ,
QNameDataContract ,
ShortDataContract ,
SignedByteDataContract ,
StringDataContract ,
TimeSpanDataContract ,
UnsignedByteDataContract ,
UnsignedIntDataContract ,
UnsignedLongDataContract ,
UnsignedShortDataContract,
UriDataContract ,
InvalidDataContract ,
};
struct CommonContractEntry
{
public bool HasRoot;
public bool IsBuiltInDataContract;
public bool IsISerializable;
public bool IsReference;
public bool IsValueType;
public bool TypeIsCollectionInterface;
public bool TypeIsInterface;
public int NameIndex;
public int NamespaceIndex;
public int StableNameIndex;
public int StableNameNamespaceIndex;
public int TopLevelElementNameIndex;
public int TopLevelElementNamespaceIndex;
public int KnownDataContractsListIndex; // indexes into s_knownContractsLists array, -1 terminated
public FixupRuntimeTypeHandle OriginalUnderlyingType;
public FixupRuntimeTypeHandle UnderlyingType;
public FixupRuntimeTypeHandle GenericTypeDefinition;
}
// PrimitiveDataContract / InvalidDataContract
struct DataContractEntry
{
public CommonContractEntry Common;
public int ErrorMessageIndex;
public DataContractKind Kind;
}
struct ClassDataContractEntry
{
public CommonContractEntry Common;
// ClasssDataContract / CollectionDataContract
public IntPtr XmlFormatReaderDelegate;
public IntPtr XmlFormatWriterDelegate;
// ClassDataContract
public bool HasDataContract;
public bool HasExtensionData;
public int ChildElementNamespacesListIndex; // indexes into s_xmlDictionaryStrings array, -1 terminated
public int ContractNamespacesListIndex; // indexes into s_xmlDictionaryStrings array, -1 terminated
public int MemberNamesListIndex; // indexes into s_xmlDictionaryStrings array, -1 terminated
public int MemberNamespacesListIndex; // indexes into s_xmlDictionaryStrings array, -1 terminated
}
struct CollectionDataContractEntry
{
public CommonContractEntry Common;
// ClasssDataContract / CollectionDataContract
public IntPtr XmlFormatReaderDelegate;
public IntPtr XmlFormatWriterDelegate;
// CollectionDataContract
public CollectionKind CollectionContractKind;
public int CollectionItemNameIndex;
public int KeyNameIndex;
public int ItemNameIndex;
public int ValueNameIndex;
public FixupRuntimeTypeHandle ItemType;
public IntPtr XmlFormatGetOnlyCollectionReaderDelegate;
}
struct EnumDataContractEntry
{
public CommonContractEntry Common;
// EnumDataContract
public bool IsFlags;
public bool IsULong;
public int BaseContractNameIndex;
public int BaseContractNamespaceIndex;
public int ChildElementNamesListIndex; // indexes into s_xmlDictionaryStrings array, -1 terminated
public int MemberCount;
public int MemberListIndex;
}
struct XmlDataContractEntry
{
public CommonContractEntry Common;
// XmlDataContract
public IntPtr CreateXmlSerializableDelegate;
}
struct MemberEntry
{
public bool EmitDefaultValue;
public bool HasConflictingNameAndType;
public bool IsGetOnlyCollection;
public bool IsNullable;
public bool IsRequired;
public int Order;
public int NameIndex;
public long Value;
}
struct DataContractMapEntry
{
public FixupRuntimeTypeHandle UserCodeType;
public int TableIndex; // (index_in_table << 4) | table_index
}
namespace System.Runtime.CompilerServices
{
internal sealed class __BlockReflectionAttribute : global::System.Attribute
{
}
}
namespace System.Runtime.InteropServices
{
[AttributeUsage((System.AttributeTargets.Method | System.AttributeTargets.Class))]
internal class McgIntrinsicsAttribute : Attribute
{
}
}
[McgIntrinsics]
static class SgIntrinsics
{
internal static IntPtr AddrOf<T>(T ftn)
{
// This method is implemented elsewhere in the toolchain
return default(IntPtr);
}
}
namespace System.Runtime.Serialization.Generated
{
using System.Diagnostics;
using System.Collections.Generic;
using System.Runtime.Serialization.Json;
using System.Threading;
using System.Xml;
using System.Runtime.CompilerServices;
using TodoList = System.Collections.Generic.List<System.Collections.Generic.KeyValuePair<DataContract, int>>;
public static partial class DataContractSerializerHelper
{
// ROOTS
// s_dataContractMap
// s_dataContracts
// s_classDataContracts
// s_collectionDataContracts
// s_enumDataContracts
// s_xmlDataContracts
// s_jsonDelegatesList
//
// POOLS
// s_stringPool
// s_xmlDictionaryStrings
// s_dataMemberLists
// s_knownContractsLists
static DataContractMapEntry[] DataContractMap { get { return s_dataContractMap; } }
static DataContractEntry[] DataContracts { get { return s_dataContracts; } }
static ClassDataContractEntry[] ClassDataContracts { get { return s_classDataContracts; } }
static CollectionDataContractEntry[] CollectionDataContracts { get { return s_collectionDataContracts; } }
static EnumDataContractEntry[] EnumDataContracts { get { return s_enumDataContracts; } }
static XmlDataContractEntry[] XmlDataContracts { get { return s_xmlDataContracts; } }
static char[] StringPool { get { return s_stringPool; } }
static int[] XmlDictionaryStrings { get { return s_xmlDictionaryStrings; } }
static MemberEntry[] DataMemberLists { get { return s_dataMemberLists; } }
static int[] KnownContractLists { get { return s_knownContractsLists; } }
public static void PopulateContractDictionary(
Dictionary<Type, DataContract> dataContracts)
{
// fill in dictionaries from pre-initialized data
XmlDictionary xmlDict = new XmlDictionary();
TodoList knownContractsTodoList = new TodoList();
for (int i = 0; i < DataContractMap.Length; i++)
{
int encodedTableIndex = DataContractMap[i].TableIndex;
Type type = Type.GetTypeFromHandle(DataContractMap[i].UserCodeType.RuntimeTypeHandle);
DataContract decodedContract = DecodeContract(encodedTableIndex, xmlDict, knownContractsTodoList);
if (!type.IsRemovedByDR())
dataContracts.Add(type, decodedContract);
// Silly optimization to mimick previous implementation: If the next entry refers to the same data
// contract, let's add that one to the map too without decoding a new DataContract instance.
if (((i + 1) < DataContractMap.Length)
&& (DataContractMap[i + 1].TableIndex == encodedTableIndex))
{
Type otherType = Type.GetTypeFromHandle(DataContractMap[i + 1].UserCodeType.RuntimeTypeHandle);
if (!otherType.IsRemovedByDR())
dataContracts.Add(otherType, decodedContract);
i++;
}
}
foreach (KeyValuePair<DataContract, int> entry in knownContractsTodoList)
{
DataContract contract = entry.Key;
int knownDataContractsListIndex = entry.Value;
contract.KnownDataContracts = DecodeKnownContractsList(dataContracts, knownDataContractsListIndex);
}
}
static int DecodeTableIndex(int encodedTableIndex, out int whichTable)
{
whichTable = encodedTableIndex & 0xF;
return encodedTableIndex >> 4;
}
static DataContract DecodeContract(int encodedTableIndex, XmlDictionary xmlDict, TodoList knownContractsTodoList)
{
int whichTable;
int indexWithinTable = DecodeTableIndex(encodedTableIndex, out whichTable);
switch (whichTable)
{
case 0: return DecodeDataContract(indexWithinTable, xmlDict, knownContractsTodoList);
case 1: return DecodeClassDataContract(indexWithinTable, xmlDict, knownContractsTodoList);
case 2: return DecodeCollectionDataContract(indexWithinTable, xmlDict, knownContractsTodoList);
case 3: return DecodeEnumDataContract(indexWithinTable, xmlDict, knownContractsTodoList);
case 4: return DecodeXmlDataContract(indexWithinTable, xmlDict, knownContractsTodoList);
default:
throw new Exception("unexpected table index");
}
}
static DataContract DecodeDataContract(int index, XmlDictionary xmlDict, TodoList knownContractsTodoList)
{
DataContract contract = AllocateSimpleDataContract(DataContracts[index].Kind);
DecodeCommon(xmlDict, contract, ref DataContracts[index].Common, knownContractsTodoList);
if (contract is InvalidDataContract)
{
((InvalidDataContract)contract).ErrorMessage = GetString(DataContracts[index].ErrorMessageIndex);
}
return contract;
}
static DataContract DecodeClassDataContract(int index, XmlDictionary xmlDict, TodoList knownContractsTodoList)
{
ClassDataContract contract = new ClassDataContract();
DecodeCommon(xmlDict, contract, ref ClassDataContracts[index].Common, knownContractsTodoList);
contract.XmlFormatReaderDelegate = (XmlFormatClassReaderDelegate)DelegateFromIntPtr(typeof(XmlFormatClassReaderDelegate), ClassDataContracts[index].XmlFormatReaderDelegate);
contract.XmlFormatWriterDelegate = (XmlFormatClassWriterDelegate)DelegateFromIntPtr(typeof(XmlFormatClassWriterDelegate), ClassDataContracts[index].XmlFormatWriterDelegate);
contract.HasDataContract = ClassDataContracts[index].HasDataContract;
contract.HasExtensionData = ClassDataContracts[index].HasExtensionData;
contract.ChildElementNamespaces = DecodeDictStringList(xmlDict, ClassDataContracts[index].ChildElementNamespacesListIndex);
contract.ContractNamespaces = DecodeDictStringList(xmlDict, ClassDataContracts[index].ContractNamespacesListIndex);
contract.MemberNames = DecodeDictStringList(xmlDict, ClassDataContracts[index].MemberNamesListIndex);
contract.MemberNamespaces = DecodeDictStringList(xmlDict, ClassDataContracts[index].MemberNamespacesListIndex);
return contract;
}
static DataContract DecodeCollectionDataContract(int index, XmlDictionary xmlDict, TodoList knownContractsTodoList)
{
CollectionDataContract contract = new CollectionDataContract(CollectionDataContracts[index].CollectionContractKind);
DecodeCommon(xmlDict, contract, ref CollectionDataContracts[index].Common, knownContractsTodoList);
contract.XmlFormatReaderDelegate = (XmlFormatCollectionReaderDelegate)DelegateFromIntPtr(typeof(XmlFormatCollectionReaderDelegate), CollectionDataContracts[index].XmlFormatReaderDelegate);
contract.XmlFormatWriterDelegate = (XmlFormatCollectionWriterDelegate)DelegateFromIntPtr(typeof(XmlFormatCollectionWriterDelegate), CollectionDataContracts[index].XmlFormatWriterDelegate);
contract.CollectionItemName = GetDictString(xmlDict, CollectionDataContracts[index].CollectionItemNameIndex);
contract.KeyName = GetString(CollectionDataContracts[index].KeyNameIndex);
contract.ItemName = GetString(CollectionDataContracts[index].ItemNameIndex);
contract.ValueName = GetString(CollectionDataContracts[index].ValueNameIndex);
contract.ItemType = Type.GetTypeFromHandle(CollectionDataContracts[index].ItemType.RuntimeTypeHandle);
contract.XmlFormatGetOnlyCollectionReaderDelegate = (XmlFormatGetOnlyCollectionReaderDelegate)DelegateFromIntPtr(typeof(XmlFormatGetOnlyCollectionReaderDelegate), CollectionDataContracts[index].XmlFormatGetOnlyCollectionReaderDelegate);
return contract;
}
static DataContract DecodeEnumDataContract(int index, XmlDictionary xmlDict, TodoList knownContractsTodoList)
{
List<long> values;
EnumDataContract contract = new EnumDataContract();
DecodeCommon(xmlDict, contract, ref EnumDataContracts[index].Common, knownContractsTodoList);
contract.IsFlags = EnumDataContracts[index].IsFlags;
contract.IsULong = EnumDataContracts[index].IsULong;
contract.BaseContractName = GetQualifiedName(EnumDataContracts[index].BaseContractNameIndex, EnumDataContracts[index].BaseContractNamespaceIndex);
contract.ChildElementNames = DecodeDictStringList(xmlDict, EnumDataContracts[index].ChildElementNamesListIndex);
contract.Members = DecodeMembersAndValues(EnumDataContracts[index].MemberCount, EnumDataContracts[index].MemberListIndex, out values);
contract.Values = values;
return contract;
}
static DataContract DecodeXmlDataContract(int index, XmlDictionary xmlDict, TodoList knownContractsTodoList)
{
XmlDataContract contract = new XmlDataContract();
DecodeCommon(xmlDict, contract, ref XmlDataContracts[index].Common, knownContractsTodoList);
contract.CreateXmlSerializableDelegate = (CreateXmlSerializableDelegate)DelegateFromIntPtr(typeof(CreateXmlSerializableDelegate), XmlDataContracts[index].CreateXmlSerializableDelegate);
return contract;
}
static Delegate DelegateFromIntPtr(Type delegateType, IntPtr pfnStaticManagedMethod)
{
if (pfnStaticManagedMethod == IntPtr.Zero)
return null;
return FunctionPointerHelpers.UnsafeDelegateFromStaticMethodFunctionPointer(delegateType, pfnStaticManagedMethod);
}
//
// These decode methods are factored out in the hopes that the compiler will fold them together, as they should
// be identical code since they only vary by the type of the second parameter and the layout of those structs
// should match for the fields being accessed
//
static void DecodeCommon(XmlDictionary xmlDict, DataContract contract, ref CommonContractEntry entry, TodoList knownContractsTodoList)
{
contract.HasRoot = entry.HasRoot;
contract.IsBuiltInDataContract = entry.IsBuiltInDataContract;
contract.IsISerializable = entry.IsISerializable;
contract.IsReference = entry.IsReference;
contract.IsValueType = entry.IsValueType;
contract.TypeIsCollectionInterface = entry.TypeIsCollectionInterface;
contract.TypeIsInterface = entry.TypeIsInterface;
contract.Name = GetDictString(xmlDict, entry.NameIndex);
contract.Namespace = GetDictString(xmlDict, entry.NamespaceIndex);
contract.StableName = GetQualifiedName(entry.StableNameIndex, entry.StableNameNamespaceIndex);
contract.TopLevelElementName = GetDictString(xmlDict, entry.TopLevelElementNameIndex);
contract.TopLevelElementNamespace = GetDictString(xmlDict, entry.TopLevelElementNamespaceIndex);
contract.OriginalUnderlyingType = Type.GetTypeFromHandle(entry.OriginalUnderlyingType.RuntimeTypeHandle);
contract.UnderlyingType = Type.GetTypeFromHandle(entry.UnderlyingType.RuntimeTypeHandle);
contract.GenericTypeDefinition = Type.GetTypeFromHandle(entry.GenericTypeDefinition.RuntimeTypeHandle);
knownContractsTodoList.Add(new KeyValuePair<DataContract, int>(contract, entry.KnownDataContractsListIndex));
}
unsafe static string GetString(int stringPoolIndex)
{
if (stringPoolIndex == -1)
return null;
fixed (char* pData = &StringPool[stringPoolIndex])
{
return new string(pData);
}
}
static XmlDictionaryString GetDictString(XmlDictionary xmlDict, int stringPoolIndex)
{
if (stringPoolIndex == -1)
return null;
return xmlDict.Add(GetString(stringPoolIndex));
}
static XmlQualifiedName GetQualifiedName(int nameIndex, int namespaceIndex)
{
if (nameIndex == -1)
return null;
return new XmlQualifiedName(GetString(nameIndex), GetString(namespaceIndex));
}
static XmlDictionaryString[] DecodeDictStringList(XmlDictionary xmlDict, int listIndex)
{
int curIndex = listIndex;
int length = XmlDictionaryStrings[curIndex++];
XmlDictionaryString[] result = new XmlDictionaryString[length];
for (int i = 0; i < length; i++)
{
result[i] = GetDictString(xmlDict, XmlDictionaryStrings[curIndex++]);
}
return result;
}
static List<DataMember> DecodeMembersAndValues(int memberCount, int memberListIndex, out List<long> values)
{
List<DataMember> members = new List<DataMember>(memberCount);
values = new List<long>(memberCount);
for (int i = memberListIndex; i < (memberListIndex + memberCount); i++)
{
DataMember member = new DataMember();
member.EmitDefaultValue = DataMemberLists[i].EmitDefaultValue;
member.HasConflictingNameAndType = DataMemberLists[i].HasConflictingNameAndType;
member.IsGetOnlyCollection = DataMemberLists[i].IsGetOnlyCollection;
member.IsNullable = DataMemberLists[i].IsNullable;
member.IsRequired = DataMemberLists[i].IsRequired;
member.Order = DataMemberLists[i].Order;
member.Name = GetString(DataMemberLists[i].NameIndex);
members.Add(member);
values.Add(DataMemberLists[i].Value);
}
return members;
}
static Dictionary<XmlQualifiedName, DataContract> DecodeKnownContractsList(
Dictionary<Type, DataContract> dataContracts,
int knownDataContractsListIndex)
{
Dictionary<XmlQualifiedName, DataContract> result = new Dictionary<XmlQualifiedName, DataContract>();
int curListIndex = knownDataContractsListIndex;
int mapIndex = KnownContractLists[curListIndex++];
while (mapIndex != -1)
{
// The list entries are indexes into the DataContractMap
Type type = Type.GetTypeFromHandle(DataContractMap[mapIndex].UserCodeType.RuntimeTypeHandle);
// All contracts have been loaded now, so we fetch the referenced contract from the passed-in collection
// using it's user type as the key.
DataContract otherContract = dataContracts[type];
// Now form the key for the KnownDataContracts dictionary
XmlQualifiedName otherContractKey
= new XmlQualifiedName(otherContract.Name.Value, otherContract.Namespace.Value);
// And add the entry to the KnownDataContracts dictionary
result.Add(otherContractKey, otherContract);
mapIndex = KnownContractLists[curListIndex++];
}
return result;
}
static DataContract AllocateSimpleDataContract(DataContractKind kind)
{
switch (kind)
{
case DataContractKind.BooleanDataContract : return new BooleanDataContract ();
case DataContractKind.ByteArrayDataContract : return new ByteArrayDataContract ();
case DataContractKind.CharDataContract : return new CharDataContract ();
case DataContractKind.DateTimeDataContract : return new DateTimeDataContract ();
case DataContractKind.DecimalDataContract : return new DecimalDataContract ();
case DataContractKind.DoubleDataContract : return new DoubleDataContract ();
case DataContractKind.FloatDataContract : return new FloatDataContract ();
case DataContractKind.GuidDataContract : return new GuidDataContract ();
case DataContractKind.IntDataContract : return new IntDataContract ();
case DataContractKind.LongDataContract : return new LongDataContract ();
case DataContractKind.ObjectDataContract : return new ObjectDataContract ();
case DataContractKind.QNameDataContract : return new QNameDataContract ();
case DataContractKind.ShortDataContract : return new ShortDataContract ();
case DataContractKind.SignedByteDataContract : return new SignedByteDataContract ();
case DataContractKind.StringDataContract : return new StringDataContract ();
case DataContractKind.TimeSpanDataContract : return new TimeSpanDataContract ();
case DataContractKind.UnsignedByteDataContract : return new UnsignedByteDataContract ();
case DataContractKind.UnsignedIntDataContract : return new UnsignedIntDataContract ();
case DataContractKind.UnsignedLongDataContract : return new UnsignedLongDataContract ();
case DataContractKind.UnsignedShortDataContract : return new UnsignedShortDataContract();
case DataContractKind.UriDataContract : return new UriDataContract ();
case DataContractKind.InvalidDataContract : return new InvalidDataContract ();
}
throw new Exception("unknown data contract kind");
}
static bool IsRemovedByDR(this Type type)
{
return (type == typeof(System.Runtime.CompilerServices.DependencyReductionTypeRemoved));
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator 1.0.1.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Management.RecoveryServices.Backup
{
using Microsoft.Azure;
using Microsoft.Azure.Management;
using Microsoft.Azure.Management.RecoveryServices;
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Microsoft.Rest.Azure.OData;
using Models;
using Newtonsoft.Json;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// BackupEnginesOperations operations.
/// </summary>
internal partial class BackupEnginesOperations : IServiceOperations<RecoveryServicesBackupClient>, IBackupEnginesOperations
{
/// <summary>
/// Initializes a new instance of the BackupEnginesOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
internal BackupEnginesOperations(RecoveryServicesBackupClient client)
{
if (client == null)
{
throw new System.ArgumentNullException("client");
}
Client = client;
}
/// <summary>
/// Gets a reference to the RecoveryServicesBackupClient
/// </summary>
public RecoveryServicesBackupClient Client { get; private set; }
/// <summary>
/// Backup management servers registered to Recovery Services Vault. Returns a
/// pageable list of servers.
/// </summary>
/// <param name='vaultName'>
/// The name of the recovery services vault.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group where the recovery services vault is
/// present.
/// </param>
/// <param name='odataQuery'>
/// OData parameters to apply to the operation.
/// </param>
/// <param name='skipToken'>
/// skipToken Filter.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<IPage<BackupEngineBaseResource>>> ListWithHttpMessagesAsync(string vaultName, string resourceGroupName, ODataQuery<BMSBackupEnginesQueryObject> odataQuery = default(ODataQuery<BMSBackupEnginesQueryObject>), string skipToken = default(string), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (vaultName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "vaultName");
}
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
string apiVersion = "2016-12-01";
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("odataQuery", odataQuery);
tracingParameters.Add("apiVersion", apiVersion);
tracingParameters.Add("vaultName", vaultName);
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("skipToken", skipToken);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "List", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "Subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.RecoveryServices/vaults/{vaultName}/backupEngines").ToString();
_url = _url.Replace("{vaultName}", System.Uri.EscapeDataString(vaultName));
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (odataQuery != null)
{
var _odataFilter = odataQuery.ToString();
if (!string.IsNullOrEmpty(_odataFilter))
{
_queryParameters.Add(_odataFilter);
}
}
if (apiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion)));
}
if (skipToken != null)
{
_queryParameters.Add(string.Format("$skipToken={0}", System.Uri.EscapeDataString(skipToken)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<IPage<BackupEngineBaseResource>>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page1<BackupEngineBaseResource>>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Returns backup management server registered to Recovery Services Vault.
/// </summary>
/// <param name='vaultName'>
/// The name of the recovery services vault.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group where the recovery services vault is
/// present.
/// </param>
/// <param name='backupEngineName'>
/// Name of the backup management server.
/// </param>
/// <param name='odataQuery'>
/// OData parameters to apply to the operation.
/// </param>
/// <param name='skipToken'>
/// skipToken Filter.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<BackupEngineBaseResource>> GetWithHttpMessagesAsync(string vaultName, string resourceGroupName, string backupEngineName, ODataQuery<BMSBackupEngineQueryObject> odataQuery = default(ODataQuery<BMSBackupEngineQueryObject>), string skipToken = default(string), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (vaultName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "vaultName");
}
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
if (backupEngineName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "backupEngineName");
}
string apiVersion = "2016-12-01";
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("odataQuery", odataQuery);
tracingParameters.Add("apiVersion", apiVersion);
tracingParameters.Add("vaultName", vaultName);
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("backupEngineName", backupEngineName);
tracingParameters.Add("skipToken", skipToken);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "Get", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "Subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.RecoveryServices/vaults/{vaultName}/backupEngines/{backupEngineName}").ToString();
_url = _url.Replace("{vaultName}", System.Uri.EscapeDataString(vaultName));
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
_url = _url.Replace("{backupEngineName}", System.Uri.EscapeDataString(backupEngineName));
List<string> _queryParameters = new List<string>();
if (odataQuery != null)
{
var _odataFilter = odataQuery.ToString();
if (!string.IsNullOrEmpty(_odataFilter))
{
_queryParameters.Add(_odataFilter);
}
}
if (apiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion)));
}
if (skipToken != null)
{
_queryParameters.Add(string.Format("$skipToken={0}", System.Uri.EscapeDataString(skipToken)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<BackupEngineBaseResource>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<BackupEngineBaseResource>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Backup management servers registered to Recovery Services Vault. Returns a
/// pageable list of servers.
/// </summary>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<IPage<BackupEngineBaseResource>>> ListNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (nextPageLink == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "nextPageLink");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("nextPageLink", nextPageLink);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "ListNext", tracingParameters);
}
// Construct URL
string _url = "{nextLink}";
_url = _url.Replace("{nextLink}", nextPageLink);
List<string> _queryParameters = new List<string>();
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<IPage<BackupEngineBaseResource>>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page1<BackupEngineBaseResource>>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
}
}
| |
using System.IO;
using Signum.Utilities.Reflection;
using System.Globalization;
using System.Collections;
namespace Signum.Utilities;
public static class Tsv
{
// Default changed since Excel exports not to UTF8 and https://stackoverflow.com/questions/49215791/vs-code-c-sharp-system-notsupportedexception-no-data-is-available-for-encodin
public static Encoding DefaultEncoding = Encoding.UTF8;
public static CultureInfo DefaultCulture = CultureInfo.InvariantCulture;
public static string ToTsvFile<T>(T[,] collection, string fileName, Encoding? encoding = null, bool autoFlush = false, bool append = false,
Func<TsvColumnInfo<T>, Func<object, string>>? toStringFactory = null)
{
encoding = encoding ?? DefaultEncoding;
using (FileStream fs = append ? new FileStream(fileName, FileMode.Append, FileAccess.Write) : File.Create(fileName))
{
using (StreamWriter sw = new StreamWriter(fs, encoding) { AutoFlush = autoFlush })
{
for (int i = 0; i < collection.GetLength(0); i++)
{
for (int j = 0; j < collection.GetLength(1); j++)
{
sw.Write(collection[i, j]);
sw.Write(tab);
}
if (i < collection.GetLength(0))
sw.WriteLine();
}
}
}
return fileName;
}
public static string ToTsvFile<T>(this IEnumerable<T> collection, string fileName, Encoding? encoding = null, CultureInfo? culture = null, bool writeHeaders = true, bool autoFlush = false, bool append = false,
Func<TsvColumnInfo<T>, Func<object?, string?>>? toStringFactory = null)
{
using (FileStream fs = append ? new FileStream(fileName, FileMode.Append, FileAccess.Write) : File.Create(fileName))
ToTsv<T>(collection, fs, encoding, culture, writeHeaders, autoFlush, toStringFactory);
return fileName;
}
public static byte[] ToTsvBytes<T>(this IEnumerable<T> collection, Encoding? encoding = null, CultureInfo? culture = null, bool writeHeaders = true, bool autoFlush = false,
Func<TsvColumnInfo<T>, Func<object?, string?>>? toStringFactory = null)
{
using (MemoryStream ms = new MemoryStream())
{
collection.ToTsv(ms, encoding, culture, writeHeaders, autoFlush, toStringFactory);
return ms.ToArray();
}
}
private const string tab = "\t";
public static void ToTsv<T>(this IEnumerable<T> collection, Stream stream, Encoding? encoding = null, CultureInfo? culture = null, bool writeHeaders = true, bool autoFlush = false,
Func<TsvColumnInfo<T>, Func<object?, string?>>? toStringFactory = null)
{
encoding = encoding ?? DefaultEncoding;
var defCulture = culture ?? DefaultCulture;
if (typeof(IList).IsAssignableFrom(typeof(T)))
{
using (StreamWriter sw = new StreamWriter(stream, encoding) { AutoFlush = autoFlush })
{
foreach (IList? row in collection)
{
for (int i = 0; i < row!.Count; i++)
{
var obj = row![i];
var str = ConvertToString(obj, defCulture);
sw.Write(str);
if (i < row!.Count - 1)
sw.Write(tab);
else
sw.WriteLine();
}
}
}
}
else
{
var columns = ColumnInfoCache<T>.Columns;
var members = columns.Select(c => c.MemberEntry).ToList();
var toString = columns.Select(c => GetToString(c, defCulture, toStringFactory)).ToList();
using (StreamWriter sw = new StreamWriter(stream, encoding) { AutoFlush = autoFlush })
{
if (writeHeaders)
sw.WriteLine(members.ToString(m => HandleSpaces(m.Name), tab));
foreach (var item in collection)
{
for (int i = 0; i < members.Count; i++)
{
var obj = members[i].Getter!(item);
var str = toString[i](obj);
sw.Write(str);
if (i < members.Count - 1)
sw.Write(tab);
else
sw.WriteLine();
}
}
}
}
}
private static Func<object?, string?> GetToString<T>(TsvColumnInfo<T> column, CultureInfo culture, Func<TsvColumnInfo<T>, Func<object?, string?>>? toStringFactory)
{
if (toStringFactory != null)
{
var result = toStringFactory(column);
if (result != null)
return result;
}
return obj => ConvertToString(obj, culture);
}
static string ConvertToString(object? obj, CultureInfo culture)
{
if (obj == null)
return "";
if (obj is IFormattable f)
return f.ToString(null, culture);
else
{
var p = obj!.ToString();
if (p != null && p.Contains(tab))
throw new InvalidDataException("TSV fields can't contain the tab character, found one in value: " + p);
return p!;
}
}
static string HandleSpaces(string p)
{
return p.Replace("__", "^").Replace("_", " ").Replace("^", "_");
}
public static List<T> ReadFile<T>(string fileName, Encoding? encoding = null, int skipLines = 1, CultureInfo? culture = null, TsvReadOptions<T>? options = null) where T : class, new()
{
encoding = encoding ?? DefaultEncoding;
using (FileStream fs = File.OpenRead(fileName))
return ReadStream<T>(fs, encoding, skipLines, culture, options).ToList();
}
public static List<T> ReadBytes<T>(byte[] data, Encoding? encoding = null, int skipLines = 1, CultureInfo? culture = null, TsvReadOptions<T>? options = null) where T : class, new()
{
using (MemoryStream ms = new MemoryStream(data))
return ReadStream<T>(ms, encoding, skipLines, culture, options).ToList();
}
public static IEnumerable<T> ReadStream<T>(Stream stream, Encoding? encoding = null, int skipLines = 1, CultureInfo? culture = null, TsvReadOptions<T>? options = null) where T : class, new()
{
encoding = encoding ?? DefaultEncoding;
var defOptions = options ?? new TsvReadOptions<T>();
var defCulture = culture ?? DefaultCulture;
var columns = ColumnInfoCache<T>.Columns;
var members = columns.Select(c => c.MemberEntry).ToList();
var parsers = columns.Select(c => GetParser(c, defCulture, defOptions.ParserFactory)).ToList();
using (StreamReader sr = new StreamReader(stream, encoding))
{
for (int i = 0; i < skipLines; i++)
sr.ReadLine();
var line = skipLines;
while (true)
{
string? tsvLine = sr.ReadLine();
if (tsvLine == null)
yield break;
T? t = null;
try
{
t = ReadObject<T>(tsvLine, members, parsers);
}
catch (Exception e)
{
e.Data["row"] = line;
if (defOptions.SkipError?.Invoke(e, tsvLine) != true)
throw new ParseCsvException(e);
}
if (t != null)
yield return t;
}
}
}
public static T ReadLine<T>(string tsvLine, CultureInfo? culture = null, TsvReadOptions<T>? options = null)
where T : class, new()
{
var defOptions = options ?? new TsvReadOptions<T>();
var defCulture = culture ?? DefaultCulture;
var columns = ColumnInfoCache<T>.Columns;
return ReadObject<T>(tsvLine,
columns.Select(c => c.MemberEntry).ToList(),
columns.Select(c => GetParser(c, defCulture, defOptions.ParserFactory)).ToList());
}
private static Func<string, object?> GetParser<T>(TsvColumnInfo<T> column, CultureInfo culture, Func<TsvColumnInfo<T>, Func<string, object?>>? parserFactory)
{
if (parserFactory != null)
{
var result = parserFactory(column);
if (result != null)
return result;
}
return str => ConvertTo(str, column.MemberInfo.ReturningType(), column.Format, culture);
}
static T ReadObject<T>(string line, List<MemberEntry<T>> members, List<Func<string, object?>> parsers) where T : new()
{
var vals = line.Split(new[] { tab }, StringSplitOptions.None).ToList();
if (vals.Count < members.Count)
throw new FormatException("Only {0} columns found (instead of {1}) in line: {2}".FormatWith(vals.Count, members.Count, line));
T t = new T();
for (int i = 0; i < members.Count; i++)
{
string? str = null;
try
{
str = vals[i];
object? val = parsers[i](str);
members[i].Setter!(t, val);
}
catch (Exception e)
{
e.Data["value"] = str;
e.Data["member"] = members[i].MemberInfo.Name;
throw;
}
}
return t;
}
static class ColumnInfoCache<T>
{
public static List<TsvColumnInfo<T>> Columns = MemberEntryFactory.GenerateList<T>(MemberOptions.Fields | MemberOptions.Properties | MemberOptions.Setters | MemberOptions.Getter)
.Select((me, i) => new TsvColumnInfo<T>(i, me, me.MemberInfo.GetCustomAttribute<FormatAttribute>()?.Format)).ToList();
}
static object? ConvertTo(string s, Type type, string? format, CultureInfo culture)
{
Type? baseType = Nullable.GetUnderlyingType(type);
if (baseType != null)
{
if (!s.HasText())
return null;
type = baseType;
}
if (type.IsEnum)
return Enum.Parse(type, s);
if (type == typeof(DateTime))
if (format == null)
return DateTime.Parse(s, culture);
else
return DateTime.ParseExact(s, format, culture);
return Convert.ChangeType(s, type, culture);
}
}
public class TsvReadOptions<T> where T : class
{
public Func<TsvColumnInfo<T>, Func<string, object>>? ParserFactory;
public Func<Exception, string, bool>? SkipError;
}
public class TsvColumnInfo<T>
{
public readonly int Index;
public readonly MemberEntry<T> MemberEntry;
public readonly string? Format;
public MemberInfo MemberInfo
{
get { return this.MemberEntry.MemberInfo; }
}
internal TsvColumnInfo(int index, MemberEntry<T> memberEntry, string? format)
{
this.Index = index;
this.MemberEntry = memberEntry;
this.Format = format;
}
}
public class ParseTsvException : Exception
{
public int? Row { get; set; }
public string? Member { get; set; }
public string? Value { get; set; }
public ParseTsvException() { }
public ParseTsvException(Exception inner) : base(inner.Message, inner)
{
this.Row = (int?)inner.Data["row"];
this.Value = (string)inner.Data["value"]!;
this.Member = (string)inner.Data["member"]!;
}
protected ParseTsvException(
System.Runtime.Serialization.SerializationInfo info,
System.Runtime.Serialization.StreamingContext context) : base(info, context)
{ }
public override string Message
{
get
{
return $"(Row: {this.Row}, Member: {this.Member}, Value: '{this.Value}') {base.Message})";
}
}
}
| |
using System;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using Steamworks.Data;
namespace Steamworks
{
internal unsafe class ISteamUGC : SteamInterface
{
internal ISteamUGC( bool IsGameServer )
{
SetupInterface( IsGameServer );
}
[DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_SteamUGC_v016", CallingConvention = Platform.CC)]
internal static extern IntPtr SteamAPI_SteamUGC_v016();
public override IntPtr GetUserInterfacePointer() => SteamAPI_SteamUGC_v016();
[DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_SteamGameServerUGC_v016", CallingConvention = Platform.CC)]
internal static extern IntPtr SteamAPI_SteamGameServerUGC_v016();
public override IntPtr GetServerInterfacePointer() => SteamAPI_SteamGameServerUGC_v016();
#region FunctionMeta
[DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_ISteamUGC_CreateQueryUserUGCRequest", CallingConvention = Platform.CC)]
private static extern UGCQueryHandle_t _CreateQueryUserUGCRequest( IntPtr self, AccountID_t unAccountID, UserUGCList eListType, UgcType eMatchingUGCType, UserUGCListSortOrder eSortOrder, AppId nCreatorAppID, AppId nConsumerAppID, uint unPage );
#endregion
internal UGCQueryHandle_t CreateQueryUserUGCRequest( AccountID_t unAccountID, UserUGCList eListType, UgcType eMatchingUGCType, UserUGCListSortOrder eSortOrder, AppId nCreatorAppID, AppId nConsumerAppID, uint unPage )
{
var returnValue = _CreateQueryUserUGCRequest( Self, unAccountID, eListType, eMatchingUGCType, eSortOrder, nCreatorAppID, nConsumerAppID, unPage );
return returnValue;
}
#region FunctionMeta
[DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_ISteamUGC_CreateQueryAllUGCRequestPage", CallingConvention = Platform.CC)]
private static extern UGCQueryHandle_t _CreateQueryAllUGCRequest( IntPtr self, UGCQuery eQueryType, UgcType eMatchingeMatchingUGCTypeFileType, AppId nCreatorAppID, AppId nConsumerAppID, uint unPage );
#endregion
internal UGCQueryHandle_t CreateQueryAllUGCRequest( UGCQuery eQueryType, UgcType eMatchingeMatchingUGCTypeFileType, AppId nCreatorAppID, AppId nConsumerAppID, uint unPage )
{
var returnValue = _CreateQueryAllUGCRequest( Self, eQueryType, eMatchingeMatchingUGCTypeFileType, nCreatorAppID, nConsumerAppID, unPage );
return returnValue;
}
#region FunctionMeta
[DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_ISteamUGC_CreateQueryAllUGCRequestCursor", CallingConvention = Platform.CC)]
private static extern UGCQueryHandle_t _CreateQueryAllUGCRequest( IntPtr self, UGCQuery eQueryType, UgcType eMatchingeMatchingUGCTypeFileType, AppId nCreatorAppID, AppId nConsumerAppID, [MarshalAs( UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof( Utf8StringToNative ) )] string pchCursor );
#endregion
internal UGCQueryHandle_t CreateQueryAllUGCRequest( UGCQuery eQueryType, UgcType eMatchingeMatchingUGCTypeFileType, AppId nCreatorAppID, AppId nConsumerAppID, [MarshalAs( UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof( Utf8StringToNative ) )] string pchCursor )
{
var returnValue = _CreateQueryAllUGCRequest( Self, eQueryType, eMatchingeMatchingUGCTypeFileType, nCreatorAppID, nConsumerAppID, pchCursor );
return returnValue;
}
#region FunctionMeta
[DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_ISteamUGC_CreateQueryUGCDetailsRequest", CallingConvention = Platform.CC)]
private static extern UGCQueryHandle_t _CreateQueryUGCDetailsRequest( IntPtr self, [In,Out] PublishedFileId[] pvecPublishedFileID, uint unNumPublishedFileIDs );
#endregion
internal UGCQueryHandle_t CreateQueryUGCDetailsRequest( [In,Out] PublishedFileId[] pvecPublishedFileID, uint unNumPublishedFileIDs )
{
var returnValue = _CreateQueryUGCDetailsRequest( Self, pvecPublishedFileID, unNumPublishedFileIDs );
return returnValue;
}
#region FunctionMeta
[DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_ISteamUGC_SendQueryUGCRequest", CallingConvention = Platform.CC)]
private static extern SteamAPICall_t _SendQueryUGCRequest( IntPtr self, UGCQueryHandle_t handle );
#endregion
internal CallResult<SteamUGCQueryCompleted_t> SendQueryUGCRequest( UGCQueryHandle_t handle )
{
var returnValue = _SendQueryUGCRequest( Self, handle );
return new CallResult<SteamUGCQueryCompleted_t>( returnValue, IsServer );
}
#region FunctionMeta
[DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_ISteamUGC_GetQueryUGCResult", CallingConvention = Platform.CC)]
[return: MarshalAs( UnmanagedType.I1 )]
private static extern bool _GetQueryUGCResult( IntPtr self, UGCQueryHandle_t handle, uint index, ref SteamUGCDetails_t pDetails );
#endregion
internal bool GetQueryUGCResult( UGCQueryHandle_t handle, uint index, ref SteamUGCDetails_t pDetails )
{
var returnValue = _GetQueryUGCResult( Self, handle, index, ref pDetails );
return returnValue;
}
#region FunctionMeta
[DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_ISteamUGC_GetQueryUGCNumTags", CallingConvention = Platform.CC)]
private static extern uint _GetQueryUGCNumTags( IntPtr self, UGCQueryHandle_t handle, uint index );
#endregion
internal uint GetQueryUGCNumTags( UGCQueryHandle_t handle, uint index )
{
var returnValue = _GetQueryUGCNumTags( Self, handle, index );
return returnValue;
}
#region FunctionMeta
[DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_ISteamUGC_GetQueryUGCTag", CallingConvention = Platform.CC)]
[return: MarshalAs( UnmanagedType.I1 )]
private static extern bool _GetQueryUGCTag( IntPtr self, UGCQueryHandle_t handle, uint index, uint indexTag, IntPtr pchValue, uint cchValueSize );
#endregion
internal bool GetQueryUGCTag( UGCQueryHandle_t handle, uint index, uint indexTag, out string pchValue )
{
using var mempchValue = Helpers.TakeMemory();
var returnValue = _GetQueryUGCTag( Self, handle, index, indexTag, mempchValue, (1024 * 32) );
pchValue = Helpers.MemoryToString( mempchValue );
return returnValue;
}
#region FunctionMeta
[DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_ISteamUGC_GetQueryUGCTagDisplayName", CallingConvention = Platform.CC)]
[return: MarshalAs( UnmanagedType.I1 )]
private static extern bool _GetQueryUGCTagDisplayName( IntPtr self, UGCQueryHandle_t handle, uint index, uint indexTag, IntPtr pchValue, uint cchValueSize );
#endregion
internal bool GetQueryUGCTagDisplayName( UGCQueryHandle_t handle, uint index, uint indexTag, out string pchValue )
{
using var mempchValue = Helpers.TakeMemory();
var returnValue = _GetQueryUGCTagDisplayName( Self, handle, index, indexTag, mempchValue, (1024 * 32) );
pchValue = Helpers.MemoryToString( mempchValue );
return returnValue;
}
#region FunctionMeta
[DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_ISteamUGC_GetQueryUGCPreviewURL", CallingConvention = Platform.CC)]
[return: MarshalAs( UnmanagedType.I1 )]
private static extern bool _GetQueryUGCPreviewURL( IntPtr self, UGCQueryHandle_t handle, uint index, IntPtr pchURL, uint cchURLSize );
#endregion
internal bool GetQueryUGCPreviewURL( UGCQueryHandle_t handle, uint index, out string pchURL )
{
using var mempchURL = Helpers.TakeMemory();
var returnValue = _GetQueryUGCPreviewURL( Self, handle, index, mempchURL, (1024 * 32) );
pchURL = Helpers.MemoryToString( mempchURL );
return returnValue;
}
#region FunctionMeta
[DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_ISteamUGC_GetQueryUGCMetadata", CallingConvention = Platform.CC)]
[return: MarshalAs( UnmanagedType.I1 )]
private static extern bool _GetQueryUGCMetadata( IntPtr self, UGCQueryHandle_t handle, uint index, IntPtr pchMetadata, uint cchMetadatasize );
#endregion
internal bool GetQueryUGCMetadata( UGCQueryHandle_t handle, uint index, out string pchMetadata )
{
using var mempchMetadata = Helpers.TakeMemory();
var returnValue = _GetQueryUGCMetadata( Self, handle, index, mempchMetadata, (1024 * 32) );
pchMetadata = Helpers.MemoryToString( mempchMetadata );
return returnValue;
}
#region FunctionMeta
[DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_ISteamUGC_GetQueryUGCChildren", CallingConvention = Platform.CC)]
[return: MarshalAs( UnmanagedType.I1 )]
private static extern bool _GetQueryUGCChildren( IntPtr self, UGCQueryHandle_t handle, uint index, [In,Out] PublishedFileId[] pvecPublishedFileID, uint cMaxEntries );
#endregion
internal bool GetQueryUGCChildren( UGCQueryHandle_t handle, uint index, [In,Out] PublishedFileId[] pvecPublishedFileID, uint cMaxEntries )
{
var returnValue = _GetQueryUGCChildren( Self, handle, index, pvecPublishedFileID, cMaxEntries );
return returnValue;
}
#region FunctionMeta
[DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_ISteamUGC_GetQueryUGCStatistic", CallingConvention = Platform.CC)]
[return: MarshalAs( UnmanagedType.I1 )]
private static extern bool _GetQueryUGCStatistic( IntPtr self, UGCQueryHandle_t handle, uint index, ItemStatistic eStatType, ref ulong pStatValue );
#endregion
internal bool GetQueryUGCStatistic( UGCQueryHandle_t handle, uint index, ItemStatistic eStatType, ref ulong pStatValue )
{
var returnValue = _GetQueryUGCStatistic( Self, handle, index, eStatType, ref pStatValue );
return returnValue;
}
#region FunctionMeta
[DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_ISteamUGC_GetQueryUGCNumAdditionalPreviews", CallingConvention = Platform.CC)]
private static extern uint _GetQueryUGCNumAdditionalPreviews( IntPtr self, UGCQueryHandle_t handle, uint index );
#endregion
internal uint GetQueryUGCNumAdditionalPreviews( UGCQueryHandle_t handle, uint index )
{
var returnValue = _GetQueryUGCNumAdditionalPreviews( Self, handle, index );
return returnValue;
}
#region FunctionMeta
[DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_ISteamUGC_GetQueryUGCAdditionalPreview", CallingConvention = Platform.CC)]
[return: MarshalAs( UnmanagedType.I1 )]
private static extern bool _GetQueryUGCAdditionalPreview( IntPtr self, UGCQueryHandle_t handle, uint index, uint previewIndex, IntPtr pchURLOrVideoID, uint cchURLSize, IntPtr pchOriginalFileName, uint cchOriginalFileNameSize, ref ItemPreviewType pPreviewType );
#endregion
internal bool GetQueryUGCAdditionalPreview( UGCQueryHandle_t handle, uint index, uint previewIndex, out string pchURLOrVideoID, out string pchOriginalFileName, ref ItemPreviewType pPreviewType )
{
using var mempchURLOrVideoID = Helpers.TakeMemory();
using var mempchOriginalFileName = Helpers.TakeMemory();
var returnValue = _GetQueryUGCAdditionalPreview( Self, handle, index, previewIndex, mempchURLOrVideoID, (1024 * 32), mempchOriginalFileName, (1024 * 32), ref pPreviewType );
pchURLOrVideoID = Helpers.MemoryToString( mempchURLOrVideoID );
pchOriginalFileName = Helpers.MemoryToString( mempchOriginalFileName );
return returnValue;
}
#region FunctionMeta
[DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_ISteamUGC_GetQueryUGCNumKeyValueTags", CallingConvention = Platform.CC)]
private static extern uint _GetQueryUGCNumKeyValueTags( IntPtr self, UGCQueryHandle_t handle, uint index );
#endregion
internal uint GetQueryUGCNumKeyValueTags( UGCQueryHandle_t handle, uint index )
{
var returnValue = _GetQueryUGCNumKeyValueTags( Self, handle, index );
return returnValue;
}
#region FunctionMeta
[DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_ISteamUGC_GetQueryUGCKeyValueTag", CallingConvention = Platform.CC)]
[return: MarshalAs( UnmanagedType.I1 )]
private static extern bool _GetQueryUGCKeyValueTag( IntPtr self, UGCQueryHandle_t handle, uint index, uint keyValueTagIndex, IntPtr pchKey, uint cchKeySize, IntPtr pchValue, uint cchValueSize );
#endregion
internal bool GetQueryUGCKeyValueTag( UGCQueryHandle_t handle, uint index, uint keyValueTagIndex, out string pchKey, out string pchValue )
{
using var mempchKey = Helpers.TakeMemory();
using var mempchValue = Helpers.TakeMemory();
var returnValue = _GetQueryUGCKeyValueTag( Self, handle, index, keyValueTagIndex, mempchKey, (1024 * 32), mempchValue, (1024 * 32) );
pchKey = Helpers.MemoryToString( mempchKey );
pchValue = Helpers.MemoryToString( mempchValue );
return returnValue;
}
#region FunctionMeta
[DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_ISteamUGC_GetQueryFirstUGCKeyValueTag", CallingConvention = Platform.CC)]
[return: MarshalAs( UnmanagedType.I1 )]
private static extern bool _GetQueryUGCKeyValueTag( IntPtr self, UGCQueryHandle_t handle, uint index, [MarshalAs( UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof( Utf8StringToNative ) )] string pchKey, IntPtr pchValue, uint cchValueSize );
#endregion
internal bool GetQueryUGCKeyValueTag( UGCQueryHandle_t handle, uint index, [MarshalAs( UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof( Utf8StringToNative ) )] string pchKey, out string pchValue )
{
using var mempchValue = Helpers.TakeMemory();
var returnValue = _GetQueryUGCKeyValueTag( Self, handle, index, pchKey, mempchValue, (1024 * 32) );
pchValue = Helpers.MemoryToString( mempchValue );
return returnValue;
}
#region FunctionMeta
[DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_ISteamUGC_ReleaseQueryUGCRequest", CallingConvention = Platform.CC)]
[return: MarshalAs( UnmanagedType.I1 )]
private static extern bool _ReleaseQueryUGCRequest( IntPtr self, UGCQueryHandle_t handle );
#endregion
internal bool ReleaseQueryUGCRequest( UGCQueryHandle_t handle )
{
var returnValue = _ReleaseQueryUGCRequest( Self, handle );
return returnValue;
}
#region FunctionMeta
[DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_ISteamUGC_AddRequiredTag", CallingConvention = Platform.CC)]
[return: MarshalAs( UnmanagedType.I1 )]
private static extern bool _AddRequiredTag( IntPtr self, UGCQueryHandle_t handle, [MarshalAs( UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof( Utf8StringToNative ) )] string pTagName );
#endregion
internal bool AddRequiredTag( UGCQueryHandle_t handle, [MarshalAs( UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof( Utf8StringToNative ) )] string pTagName )
{
var returnValue = _AddRequiredTag( Self, handle, pTagName );
return returnValue;
}
#region FunctionMeta
[DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_ISteamUGC_AddRequiredTagGroup", CallingConvention = Platform.CC)]
[return: MarshalAs( UnmanagedType.I1 )]
private static extern bool _AddRequiredTagGroup( IntPtr self, UGCQueryHandle_t handle, ref SteamParamStringArray_t pTagGroups );
#endregion
internal bool AddRequiredTagGroup( UGCQueryHandle_t handle, ref SteamParamStringArray_t pTagGroups )
{
var returnValue = _AddRequiredTagGroup( Self, handle, ref pTagGroups );
return returnValue;
}
#region FunctionMeta
[DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_ISteamUGC_AddExcludedTag", CallingConvention = Platform.CC)]
[return: MarshalAs( UnmanagedType.I1 )]
private static extern bool _AddExcludedTag( IntPtr self, UGCQueryHandle_t handle, [MarshalAs( UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof( Utf8StringToNative ) )] string pTagName );
#endregion
internal bool AddExcludedTag( UGCQueryHandle_t handle, [MarshalAs( UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof( Utf8StringToNative ) )] string pTagName )
{
var returnValue = _AddExcludedTag( Self, handle, pTagName );
return returnValue;
}
#region FunctionMeta
[DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_ISteamUGC_SetReturnOnlyIDs", CallingConvention = Platform.CC)]
[return: MarshalAs( UnmanagedType.I1 )]
private static extern bool _SetReturnOnlyIDs( IntPtr self, UGCQueryHandle_t handle, [MarshalAs( UnmanagedType.U1 )] bool bReturnOnlyIDs );
#endregion
internal bool SetReturnOnlyIDs( UGCQueryHandle_t handle, [MarshalAs( UnmanagedType.U1 )] bool bReturnOnlyIDs )
{
var returnValue = _SetReturnOnlyIDs( Self, handle, bReturnOnlyIDs );
return returnValue;
}
#region FunctionMeta
[DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_ISteamUGC_SetReturnKeyValueTags", CallingConvention = Platform.CC)]
[return: MarshalAs( UnmanagedType.I1 )]
private static extern bool _SetReturnKeyValueTags( IntPtr self, UGCQueryHandle_t handle, [MarshalAs( UnmanagedType.U1 )] bool bReturnKeyValueTags );
#endregion
internal bool SetReturnKeyValueTags( UGCQueryHandle_t handle, [MarshalAs( UnmanagedType.U1 )] bool bReturnKeyValueTags )
{
var returnValue = _SetReturnKeyValueTags( Self, handle, bReturnKeyValueTags );
return returnValue;
}
#region FunctionMeta
[DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_ISteamUGC_SetReturnLongDescription", CallingConvention = Platform.CC)]
[return: MarshalAs( UnmanagedType.I1 )]
private static extern bool _SetReturnLongDescription( IntPtr self, UGCQueryHandle_t handle, [MarshalAs( UnmanagedType.U1 )] bool bReturnLongDescription );
#endregion
internal bool SetReturnLongDescription( UGCQueryHandle_t handle, [MarshalAs( UnmanagedType.U1 )] bool bReturnLongDescription )
{
var returnValue = _SetReturnLongDescription( Self, handle, bReturnLongDescription );
return returnValue;
}
#region FunctionMeta
[DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_ISteamUGC_SetReturnMetadata", CallingConvention = Platform.CC)]
[return: MarshalAs( UnmanagedType.I1 )]
private static extern bool _SetReturnMetadata( IntPtr self, UGCQueryHandle_t handle, [MarshalAs( UnmanagedType.U1 )] bool bReturnMetadata );
#endregion
internal bool SetReturnMetadata( UGCQueryHandle_t handle, [MarshalAs( UnmanagedType.U1 )] bool bReturnMetadata )
{
var returnValue = _SetReturnMetadata( Self, handle, bReturnMetadata );
return returnValue;
}
#region FunctionMeta
[DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_ISteamUGC_SetReturnChildren", CallingConvention = Platform.CC)]
[return: MarshalAs( UnmanagedType.I1 )]
private static extern bool _SetReturnChildren( IntPtr self, UGCQueryHandle_t handle, [MarshalAs( UnmanagedType.U1 )] bool bReturnChildren );
#endregion
internal bool SetReturnChildren( UGCQueryHandle_t handle, [MarshalAs( UnmanagedType.U1 )] bool bReturnChildren )
{
var returnValue = _SetReturnChildren( Self, handle, bReturnChildren );
return returnValue;
}
#region FunctionMeta
[DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_ISteamUGC_SetReturnAdditionalPreviews", CallingConvention = Platform.CC)]
[return: MarshalAs( UnmanagedType.I1 )]
private static extern bool _SetReturnAdditionalPreviews( IntPtr self, UGCQueryHandle_t handle, [MarshalAs( UnmanagedType.U1 )] bool bReturnAdditionalPreviews );
#endregion
internal bool SetReturnAdditionalPreviews( UGCQueryHandle_t handle, [MarshalAs( UnmanagedType.U1 )] bool bReturnAdditionalPreviews )
{
var returnValue = _SetReturnAdditionalPreviews( Self, handle, bReturnAdditionalPreviews );
return returnValue;
}
#region FunctionMeta
[DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_ISteamUGC_SetReturnTotalOnly", CallingConvention = Platform.CC)]
[return: MarshalAs( UnmanagedType.I1 )]
private static extern bool _SetReturnTotalOnly( IntPtr self, UGCQueryHandle_t handle, [MarshalAs( UnmanagedType.U1 )] bool bReturnTotalOnly );
#endregion
internal bool SetReturnTotalOnly( UGCQueryHandle_t handle, [MarshalAs( UnmanagedType.U1 )] bool bReturnTotalOnly )
{
var returnValue = _SetReturnTotalOnly( Self, handle, bReturnTotalOnly );
return returnValue;
}
#region FunctionMeta
[DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_ISteamUGC_SetReturnPlaytimeStats", CallingConvention = Platform.CC)]
[return: MarshalAs( UnmanagedType.I1 )]
private static extern bool _SetReturnPlaytimeStats( IntPtr self, UGCQueryHandle_t handle, uint unDays );
#endregion
internal bool SetReturnPlaytimeStats( UGCQueryHandle_t handle, uint unDays )
{
var returnValue = _SetReturnPlaytimeStats( Self, handle, unDays );
return returnValue;
}
#region FunctionMeta
[DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_ISteamUGC_SetLanguage", CallingConvention = Platform.CC)]
[return: MarshalAs( UnmanagedType.I1 )]
private static extern bool _SetLanguage( IntPtr self, UGCQueryHandle_t handle, [MarshalAs( UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof( Utf8StringToNative ) )] string pchLanguage );
#endregion
internal bool SetLanguage( UGCQueryHandle_t handle, [MarshalAs( UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof( Utf8StringToNative ) )] string pchLanguage )
{
var returnValue = _SetLanguage( Self, handle, pchLanguage );
return returnValue;
}
#region FunctionMeta
[DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_ISteamUGC_SetAllowCachedResponse", CallingConvention = Platform.CC)]
[return: MarshalAs( UnmanagedType.I1 )]
private static extern bool _SetAllowCachedResponse( IntPtr self, UGCQueryHandle_t handle, uint unMaxAgeSeconds );
#endregion
internal bool SetAllowCachedResponse( UGCQueryHandle_t handle, uint unMaxAgeSeconds )
{
var returnValue = _SetAllowCachedResponse( Self, handle, unMaxAgeSeconds );
return returnValue;
}
#region FunctionMeta
[DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_ISteamUGC_SetCloudFileNameFilter", CallingConvention = Platform.CC)]
[return: MarshalAs( UnmanagedType.I1 )]
private static extern bool _SetCloudFileNameFilter( IntPtr self, UGCQueryHandle_t handle, [MarshalAs( UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof( Utf8StringToNative ) )] string pMatchCloudFileName );
#endregion
internal bool SetCloudFileNameFilter( UGCQueryHandle_t handle, [MarshalAs( UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof( Utf8StringToNative ) )] string pMatchCloudFileName )
{
var returnValue = _SetCloudFileNameFilter( Self, handle, pMatchCloudFileName );
return returnValue;
}
#region FunctionMeta
[DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_ISteamUGC_SetMatchAnyTag", CallingConvention = Platform.CC)]
[return: MarshalAs( UnmanagedType.I1 )]
private static extern bool _SetMatchAnyTag( IntPtr self, UGCQueryHandle_t handle, [MarshalAs( UnmanagedType.U1 )] bool bMatchAnyTag );
#endregion
internal bool SetMatchAnyTag( UGCQueryHandle_t handle, [MarshalAs( UnmanagedType.U1 )] bool bMatchAnyTag )
{
var returnValue = _SetMatchAnyTag( Self, handle, bMatchAnyTag );
return returnValue;
}
#region FunctionMeta
[DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_ISteamUGC_SetSearchText", CallingConvention = Platform.CC)]
[return: MarshalAs( UnmanagedType.I1 )]
private static extern bool _SetSearchText( IntPtr self, UGCQueryHandle_t handle, [MarshalAs( UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof( Utf8StringToNative ) )] string pSearchText );
#endregion
internal bool SetSearchText( UGCQueryHandle_t handle, [MarshalAs( UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof( Utf8StringToNative ) )] string pSearchText )
{
var returnValue = _SetSearchText( Self, handle, pSearchText );
return returnValue;
}
#region FunctionMeta
[DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_ISteamUGC_SetRankedByTrendDays", CallingConvention = Platform.CC)]
[return: MarshalAs( UnmanagedType.I1 )]
private static extern bool _SetRankedByTrendDays( IntPtr self, UGCQueryHandle_t handle, uint unDays );
#endregion
internal bool SetRankedByTrendDays( UGCQueryHandle_t handle, uint unDays )
{
var returnValue = _SetRankedByTrendDays( Self, handle, unDays );
return returnValue;
}
#region FunctionMeta
[DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_ISteamUGC_SetTimeCreatedDateRange", CallingConvention = Platform.CC)]
[return: MarshalAs( UnmanagedType.I1 )]
private static extern bool _SetTimeCreatedDateRange( IntPtr self, UGCQueryHandle_t handle, RTime32 rtStart, RTime32 rtEnd );
#endregion
internal bool SetTimeCreatedDateRange( UGCQueryHandle_t handle, RTime32 rtStart, RTime32 rtEnd )
{
var returnValue = _SetTimeCreatedDateRange( Self, handle, rtStart, rtEnd );
return returnValue;
}
#region FunctionMeta
[DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_ISteamUGC_SetTimeUpdatedDateRange", CallingConvention = Platform.CC)]
[return: MarshalAs( UnmanagedType.I1 )]
private static extern bool _SetTimeUpdatedDateRange( IntPtr self, UGCQueryHandle_t handle, RTime32 rtStart, RTime32 rtEnd );
#endregion
internal bool SetTimeUpdatedDateRange( UGCQueryHandle_t handle, RTime32 rtStart, RTime32 rtEnd )
{
var returnValue = _SetTimeUpdatedDateRange( Self, handle, rtStart, rtEnd );
return returnValue;
}
#region FunctionMeta
[DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_ISteamUGC_AddRequiredKeyValueTag", CallingConvention = Platform.CC)]
[return: MarshalAs( UnmanagedType.I1 )]
private static extern bool _AddRequiredKeyValueTag( IntPtr self, UGCQueryHandle_t handle, [MarshalAs( UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof( Utf8StringToNative ) )] string pKey, [MarshalAs( UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof( Utf8StringToNative ) )] string pValue );
#endregion
internal bool AddRequiredKeyValueTag( UGCQueryHandle_t handle, [MarshalAs( UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof( Utf8StringToNative ) )] string pKey, [MarshalAs( UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof( Utf8StringToNative ) )] string pValue )
{
var returnValue = _AddRequiredKeyValueTag( Self, handle, pKey, pValue );
return returnValue;
}
#region FunctionMeta
[DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_ISteamUGC_CreateItem", CallingConvention = Platform.CC)]
private static extern SteamAPICall_t _CreateItem( IntPtr self, AppId nConsumerAppId, WorkshopFileType eFileType );
#endregion
internal CallResult<CreateItemResult_t> CreateItem( AppId nConsumerAppId, WorkshopFileType eFileType )
{
var returnValue = _CreateItem( Self, nConsumerAppId, eFileType );
return new CallResult<CreateItemResult_t>( returnValue, IsServer );
}
#region FunctionMeta
[DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_ISteamUGC_StartItemUpdate", CallingConvention = Platform.CC)]
private static extern UGCUpdateHandle_t _StartItemUpdate( IntPtr self, AppId nConsumerAppId, PublishedFileId nPublishedFileID );
#endregion
internal UGCUpdateHandle_t StartItemUpdate( AppId nConsumerAppId, PublishedFileId nPublishedFileID )
{
var returnValue = _StartItemUpdate( Self, nConsumerAppId, nPublishedFileID );
return returnValue;
}
#region FunctionMeta
[DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_ISteamUGC_SetItemTitle", CallingConvention = Platform.CC)]
[return: MarshalAs( UnmanagedType.I1 )]
private static extern bool _SetItemTitle( IntPtr self, UGCUpdateHandle_t handle, [MarshalAs( UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof( Utf8StringToNative ) )] string pchTitle );
#endregion
internal bool SetItemTitle( UGCUpdateHandle_t handle, [MarshalAs( UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof( Utf8StringToNative ) )] string pchTitle )
{
var returnValue = _SetItemTitle( Self, handle, pchTitle );
return returnValue;
}
#region FunctionMeta
[DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_ISteamUGC_SetItemDescription", CallingConvention = Platform.CC)]
[return: MarshalAs( UnmanagedType.I1 )]
private static extern bool _SetItemDescription( IntPtr self, UGCUpdateHandle_t handle, [MarshalAs( UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof( Utf8StringToNative ) )] string pchDescription );
#endregion
internal bool SetItemDescription( UGCUpdateHandle_t handle, [MarshalAs( UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof( Utf8StringToNative ) )] string pchDescription )
{
var returnValue = _SetItemDescription( Self, handle, pchDescription );
return returnValue;
}
#region FunctionMeta
[DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_ISteamUGC_SetItemUpdateLanguage", CallingConvention = Platform.CC)]
[return: MarshalAs( UnmanagedType.I1 )]
private static extern bool _SetItemUpdateLanguage( IntPtr self, UGCUpdateHandle_t handle, [MarshalAs( UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof( Utf8StringToNative ) )] string pchLanguage );
#endregion
internal bool SetItemUpdateLanguage( UGCUpdateHandle_t handle, [MarshalAs( UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof( Utf8StringToNative ) )] string pchLanguage )
{
var returnValue = _SetItemUpdateLanguage( Self, handle, pchLanguage );
return returnValue;
}
#region FunctionMeta
[DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_ISteamUGC_SetItemMetadata", CallingConvention = Platform.CC)]
[return: MarshalAs( UnmanagedType.I1 )]
private static extern bool _SetItemMetadata( IntPtr self, UGCUpdateHandle_t handle, [MarshalAs( UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof( Utf8StringToNative ) )] string pchMetaData );
#endregion
internal bool SetItemMetadata( UGCUpdateHandle_t handle, [MarshalAs( UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof( Utf8StringToNative ) )] string pchMetaData )
{
var returnValue = _SetItemMetadata( Self, handle, pchMetaData );
return returnValue;
}
#region FunctionMeta
[DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_ISteamUGC_SetItemVisibility", CallingConvention = Platform.CC)]
[return: MarshalAs( UnmanagedType.I1 )]
private static extern bool _SetItemVisibility( IntPtr self, UGCUpdateHandle_t handle, RemoteStoragePublishedFileVisibility eVisibility );
#endregion
internal bool SetItemVisibility( UGCUpdateHandle_t handle, RemoteStoragePublishedFileVisibility eVisibility )
{
var returnValue = _SetItemVisibility( Self, handle, eVisibility );
return returnValue;
}
#region FunctionMeta
[DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_ISteamUGC_SetItemTags", CallingConvention = Platform.CC)]
[return: MarshalAs( UnmanagedType.I1 )]
private static extern bool _SetItemTags( IntPtr self, UGCUpdateHandle_t updateHandle, ref SteamParamStringArray_t pTags );
#endregion
internal bool SetItemTags( UGCUpdateHandle_t updateHandle, ref SteamParamStringArray_t pTags )
{
var returnValue = _SetItemTags( Self, updateHandle, ref pTags );
return returnValue;
}
#region FunctionMeta
[DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_ISteamUGC_SetItemContent", CallingConvention = Platform.CC)]
[return: MarshalAs( UnmanagedType.I1 )]
private static extern bool _SetItemContent( IntPtr self, UGCUpdateHandle_t handle, [MarshalAs( UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof( Utf8StringToNative ) )] string pszContentFolder );
#endregion
internal bool SetItemContent( UGCUpdateHandle_t handle, [MarshalAs( UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof( Utf8StringToNative ) )] string pszContentFolder )
{
var returnValue = _SetItemContent( Self, handle, pszContentFolder );
return returnValue;
}
#region FunctionMeta
[DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_ISteamUGC_SetItemPreview", CallingConvention = Platform.CC)]
[return: MarshalAs( UnmanagedType.I1 )]
private static extern bool _SetItemPreview( IntPtr self, UGCUpdateHandle_t handle, [MarshalAs( UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof( Utf8StringToNative ) )] string pszPreviewFile );
#endregion
internal bool SetItemPreview( UGCUpdateHandle_t handle, [MarshalAs( UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof( Utf8StringToNative ) )] string pszPreviewFile )
{
var returnValue = _SetItemPreview( Self, handle, pszPreviewFile );
return returnValue;
}
#region FunctionMeta
[DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_ISteamUGC_SetAllowLegacyUpload", CallingConvention = Platform.CC)]
[return: MarshalAs( UnmanagedType.I1 )]
private static extern bool _SetAllowLegacyUpload( IntPtr self, UGCUpdateHandle_t handle, [MarshalAs( UnmanagedType.U1 )] bool bAllowLegacyUpload );
#endregion
internal bool SetAllowLegacyUpload( UGCUpdateHandle_t handle, [MarshalAs( UnmanagedType.U1 )] bool bAllowLegacyUpload )
{
var returnValue = _SetAllowLegacyUpload( Self, handle, bAllowLegacyUpload );
return returnValue;
}
#region FunctionMeta
[DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_ISteamUGC_RemoveAllItemKeyValueTags", CallingConvention = Platform.CC)]
[return: MarshalAs( UnmanagedType.I1 )]
private static extern bool _RemoveAllItemKeyValueTags( IntPtr self, UGCUpdateHandle_t handle );
#endregion
internal bool RemoveAllItemKeyValueTags( UGCUpdateHandle_t handle )
{
var returnValue = _RemoveAllItemKeyValueTags( Self, handle );
return returnValue;
}
#region FunctionMeta
[DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_ISteamUGC_RemoveItemKeyValueTags", CallingConvention = Platform.CC)]
[return: MarshalAs( UnmanagedType.I1 )]
private static extern bool _RemoveItemKeyValueTags( IntPtr self, UGCUpdateHandle_t handle, [MarshalAs( UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof( Utf8StringToNative ) )] string pchKey );
#endregion
internal bool RemoveItemKeyValueTags( UGCUpdateHandle_t handle, [MarshalAs( UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof( Utf8StringToNative ) )] string pchKey )
{
var returnValue = _RemoveItemKeyValueTags( Self, handle, pchKey );
return returnValue;
}
#region FunctionMeta
[DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_ISteamUGC_AddItemKeyValueTag", CallingConvention = Platform.CC)]
[return: MarshalAs( UnmanagedType.I1 )]
private static extern bool _AddItemKeyValueTag( IntPtr self, UGCUpdateHandle_t handle, [MarshalAs( UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof( Utf8StringToNative ) )] string pchKey, [MarshalAs( UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof( Utf8StringToNative ) )] string pchValue );
#endregion
internal bool AddItemKeyValueTag( UGCUpdateHandle_t handle, [MarshalAs( UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof( Utf8StringToNative ) )] string pchKey, [MarshalAs( UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof( Utf8StringToNative ) )] string pchValue )
{
var returnValue = _AddItemKeyValueTag( Self, handle, pchKey, pchValue );
return returnValue;
}
#region FunctionMeta
[DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_ISteamUGC_AddItemPreviewFile", CallingConvention = Platform.CC)]
[return: MarshalAs( UnmanagedType.I1 )]
private static extern bool _AddItemPreviewFile( IntPtr self, UGCUpdateHandle_t handle, [MarshalAs( UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof( Utf8StringToNative ) )] string pszPreviewFile, ItemPreviewType type );
#endregion
internal bool AddItemPreviewFile( UGCUpdateHandle_t handle, [MarshalAs( UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof( Utf8StringToNative ) )] string pszPreviewFile, ItemPreviewType type )
{
var returnValue = _AddItemPreviewFile( Self, handle, pszPreviewFile, type );
return returnValue;
}
#region FunctionMeta
[DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_ISteamUGC_AddItemPreviewVideo", CallingConvention = Platform.CC)]
[return: MarshalAs( UnmanagedType.I1 )]
private static extern bool _AddItemPreviewVideo( IntPtr self, UGCUpdateHandle_t handle, [MarshalAs( UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof( Utf8StringToNative ) )] string pszVideoID );
#endregion
internal bool AddItemPreviewVideo( UGCUpdateHandle_t handle, [MarshalAs( UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof( Utf8StringToNative ) )] string pszVideoID )
{
var returnValue = _AddItemPreviewVideo( Self, handle, pszVideoID );
return returnValue;
}
#region FunctionMeta
[DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_ISteamUGC_UpdateItemPreviewFile", CallingConvention = Platform.CC)]
[return: MarshalAs( UnmanagedType.I1 )]
private static extern bool _UpdateItemPreviewFile( IntPtr self, UGCUpdateHandle_t handle, uint index, [MarshalAs( UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof( Utf8StringToNative ) )] string pszPreviewFile );
#endregion
internal bool UpdateItemPreviewFile( UGCUpdateHandle_t handle, uint index, [MarshalAs( UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof( Utf8StringToNative ) )] string pszPreviewFile )
{
var returnValue = _UpdateItemPreviewFile( Self, handle, index, pszPreviewFile );
return returnValue;
}
#region FunctionMeta
[DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_ISteamUGC_UpdateItemPreviewVideo", CallingConvention = Platform.CC)]
[return: MarshalAs( UnmanagedType.I1 )]
private static extern bool _UpdateItemPreviewVideo( IntPtr self, UGCUpdateHandle_t handle, uint index, [MarshalAs( UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof( Utf8StringToNative ) )] string pszVideoID );
#endregion
internal bool UpdateItemPreviewVideo( UGCUpdateHandle_t handle, uint index, [MarshalAs( UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof( Utf8StringToNative ) )] string pszVideoID )
{
var returnValue = _UpdateItemPreviewVideo( Self, handle, index, pszVideoID );
return returnValue;
}
#region FunctionMeta
[DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_ISteamUGC_RemoveItemPreview", CallingConvention = Platform.CC)]
[return: MarshalAs( UnmanagedType.I1 )]
private static extern bool _RemoveItemPreview( IntPtr self, UGCUpdateHandle_t handle, uint index );
#endregion
internal bool RemoveItemPreview( UGCUpdateHandle_t handle, uint index )
{
var returnValue = _RemoveItemPreview( Self, handle, index );
return returnValue;
}
#region FunctionMeta
[DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_ISteamUGC_SubmitItemUpdate", CallingConvention = Platform.CC)]
private static extern SteamAPICall_t _SubmitItemUpdate( IntPtr self, UGCUpdateHandle_t handle, [MarshalAs( UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof( Utf8StringToNative ) )] string pchChangeNote );
#endregion
internal CallResult<SubmitItemUpdateResult_t> SubmitItemUpdate( UGCUpdateHandle_t handle, [MarshalAs( UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof( Utf8StringToNative ) )] string pchChangeNote )
{
var returnValue = _SubmitItemUpdate( Self, handle, pchChangeNote );
return new CallResult<SubmitItemUpdateResult_t>( returnValue, IsServer );
}
#region FunctionMeta
[DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_ISteamUGC_GetItemUpdateProgress", CallingConvention = Platform.CC)]
private static extern ItemUpdateStatus _GetItemUpdateProgress( IntPtr self, UGCUpdateHandle_t handle, ref ulong punBytesProcessed, ref ulong punBytesTotal );
#endregion
internal ItemUpdateStatus GetItemUpdateProgress( UGCUpdateHandle_t handle, ref ulong punBytesProcessed, ref ulong punBytesTotal )
{
var returnValue = _GetItemUpdateProgress( Self, handle, ref punBytesProcessed, ref punBytesTotal );
return returnValue;
}
#region FunctionMeta
[DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_ISteamUGC_SetUserItemVote", CallingConvention = Platform.CC)]
private static extern SteamAPICall_t _SetUserItemVote( IntPtr self, PublishedFileId nPublishedFileID, [MarshalAs( UnmanagedType.U1 )] bool bVoteUp );
#endregion
internal CallResult<SetUserItemVoteResult_t> SetUserItemVote( PublishedFileId nPublishedFileID, [MarshalAs( UnmanagedType.U1 )] bool bVoteUp )
{
var returnValue = _SetUserItemVote( Self, nPublishedFileID, bVoteUp );
return new CallResult<SetUserItemVoteResult_t>( returnValue, IsServer );
}
#region FunctionMeta
[DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_ISteamUGC_GetUserItemVote", CallingConvention = Platform.CC)]
private static extern SteamAPICall_t _GetUserItemVote( IntPtr self, PublishedFileId nPublishedFileID );
#endregion
internal CallResult<GetUserItemVoteResult_t> GetUserItemVote( PublishedFileId nPublishedFileID )
{
var returnValue = _GetUserItemVote( Self, nPublishedFileID );
return new CallResult<GetUserItemVoteResult_t>( returnValue, IsServer );
}
#region FunctionMeta
[DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_ISteamUGC_AddItemToFavorites", CallingConvention = Platform.CC)]
private static extern SteamAPICall_t _AddItemToFavorites( IntPtr self, AppId nAppId, PublishedFileId nPublishedFileID );
#endregion
internal CallResult<UserFavoriteItemsListChanged_t> AddItemToFavorites( AppId nAppId, PublishedFileId nPublishedFileID )
{
var returnValue = _AddItemToFavorites( Self, nAppId, nPublishedFileID );
return new CallResult<UserFavoriteItemsListChanged_t>( returnValue, IsServer );
}
#region FunctionMeta
[DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_ISteamUGC_RemoveItemFromFavorites", CallingConvention = Platform.CC)]
private static extern SteamAPICall_t _RemoveItemFromFavorites( IntPtr self, AppId nAppId, PublishedFileId nPublishedFileID );
#endregion
internal CallResult<UserFavoriteItemsListChanged_t> RemoveItemFromFavorites( AppId nAppId, PublishedFileId nPublishedFileID )
{
var returnValue = _RemoveItemFromFavorites( Self, nAppId, nPublishedFileID );
return new CallResult<UserFavoriteItemsListChanged_t>( returnValue, IsServer );
}
#region FunctionMeta
[DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_ISteamUGC_SubscribeItem", CallingConvention = Platform.CC)]
private static extern SteamAPICall_t _SubscribeItem( IntPtr self, PublishedFileId nPublishedFileID );
#endregion
internal CallResult<RemoteStorageSubscribePublishedFileResult_t> SubscribeItem( PublishedFileId nPublishedFileID )
{
var returnValue = _SubscribeItem( Self, nPublishedFileID );
return new CallResult<RemoteStorageSubscribePublishedFileResult_t>( returnValue, IsServer );
}
#region FunctionMeta
[DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_ISteamUGC_UnsubscribeItem", CallingConvention = Platform.CC)]
private static extern SteamAPICall_t _UnsubscribeItem( IntPtr self, PublishedFileId nPublishedFileID );
#endregion
internal CallResult<RemoteStorageUnsubscribePublishedFileResult_t> UnsubscribeItem( PublishedFileId nPublishedFileID )
{
var returnValue = _UnsubscribeItem( Self, nPublishedFileID );
return new CallResult<RemoteStorageUnsubscribePublishedFileResult_t>( returnValue, IsServer );
}
#region FunctionMeta
[DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_ISteamUGC_GetNumSubscribedItems", CallingConvention = Platform.CC)]
private static extern uint _GetNumSubscribedItems( IntPtr self );
#endregion
internal uint GetNumSubscribedItems()
{
var returnValue = _GetNumSubscribedItems( Self );
return returnValue;
}
#region FunctionMeta
[DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_ISteamUGC_GetSubscribedItems", CallingConvention = Platform.CC)]
private static extern uint _GetSubscribedItems( IntPtr self, [In,Out] PublishedFileId[] pvecPublishedFileID, uint cMaxEntries );
#endregion
internal uint GetSubscribedItems( [In,Out] PublishedFileId[] pvecPublishedFileID, uint cMaxEntries )
{
var returnValue = _GetSubscribedItems( Self, pvecPublishedFileID, cMaxEntries );
return returnValue;
}
#region FunctionMeta
[DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_ISteamUGC_GetItemState", CallingConvention = Platform.CC)]
private static extern uint _GetItemState( IntPtr self, PublishedFileId nPublishedFileID );
#endregion
internal uint GetItemState( PublishedFileId nPublishedFileID )
{
var returnValue = _GetItemState( Self, nPublishedFileID );
return returnValue;
}
#region FunctionMeta
[DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_ISteamUGC_GetItemInstallInfo", CallingConvention = Platform.CC)]
[return: MarshalAs( UnmanagedType.I1 )]
private static extern bool _GetItemInstallInfo( IntPtr self, PublishedFileId nPublishedFileID, ref ulong punSizeOnDisk, IntPtr pchFolder, uint cchFolderSize, ref uint punTimeStamp );
#endregion
internal bool GetItemInstallInfo( PublishedFileId nPublishedFileID, ref ulong punSizeOnDisk, out string pchFolder, ref uint punTimeStamp )
{
using var mempchFolder = Helpers.TakeMemory();
var returnValue = _GetItemInstallInfo( Self, nPublishedFileID, ref punSizeOnDisk, mempchFolder, (1024 * 32), ref punTimeStamp );
pchFolder = Helpers.MemoryToString( mempchFolder );
return returnValue;
}
#region FunctionMeta
[DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_ISteamUGC_GetItemDownloadInfo", CallingConvention = Platform.CC)]
[return: MarshalAs( UnmanagedType.I1 )]
private static extern bool _GetItemDownloadInfo( IntPtr self, PublishedFileId nPublishedFileID, ref ulong punBytesDownloaded, ref ulong punBytesTotal );
#endregion
internal bool GetItemDownloadInfo( PublishedFileId nPublishedFileID, ref ulong punBytesDownloaded, ref ulong punBytesTotal )
{
var returnValue = _GetItemDownloadInfo( Self, nPublishedFileID, ref punBytesDownloaded, ref punBytesTotal );
return returnValue;
}
#region FunctionMeta
[DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_ISteamUGC_DownloadItem", CallingConvention = Platform.CC)]
[return: MarshalAs( UnmanagedType.I1 )]
private static extern bool _DownloadItem( IntPtr self, PublishedFileId nPublishedFileID, [MarshalAs( UnmanagedType.U1 )] bool bHighPriority );
#endregion
internal bool DownloadItem( PublishedFileId nPublishedFileID, [MarshalAs( UnmanagedType.U1 )] bool bHighPriority )
{
var returnValue = _DownloadItem( Self, nPublishedFileID, bHighPriority );
return returnValue;
}
#region FunctionMeta
[DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_ISteamUGC_BInitWorkshopForGameServer", CallingConvention = Platform.CC)]
[return: MarshalAs( UnmanagedType.I1 )]
private static extern bool _BInitWorkshopForGameServer( IntPtr self, DepotId_t unWorkshopDepotID, [MarshalAs( UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof( Utf8StringToNative ) )] string pszFolder );
#endregion
internal bool BInitWorkshopForGameServer( DepotId_t unWorkshopDepotID, [MarshalAs( UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof( Utf8StringToNative ) )] string pszFolder )
{
var returnValue = _BInitWorkshopForGameServer( Self, unWorkshopDepotID, pszFolder );
return returnValue;
}
#region FunctionMeta
[DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_ISteamUGC_SuspendDownloads", CallingConvention = Platform.CC)]
private static extern void _SuspendDownloads( IntPtr self, [MarshalAs( UnmanagedType.U1 )] bool bSuspend );
#endregion
internal void SuspendDownloads( [MarshalAs( UnmanagedType.U1 )] bool bSuspend )
{
_SuspendDownloads( Self, bSuspend );
}
#region FunctionMeta
[DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_ISteamUGC_StartPlaytimeTracking", CallingConvention = Platform.CC)]
private static extern SteamAPICall_t _StartPlaytimeTracking( IntPtr self, [In,Out] PublishedFileId[] pvecPublishedFileID, uint unNumPublishedFileIDs );
#endregion
internal CallResult<StartPlaytimeTrackingResult_t> StartPlaytimeTracking( [In,Out] PublishedFileId[] pvecPublishedFileID, uint unNumPublishedFileIDs )
{
var returnValue = _StartPlaytimeTracking( Self, pvecPublishedFileID, unNumPublishedFileIDs );
return new CallResult<StartPlaytimeTrackingResult_t>( returnValue, IsServer );
}
#region FunctionMeta
[DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_ISteamUGC_StopPlaytimeTracking", CallingConvention = Platform.CC)]
private static extern SteamAPICall_t _StopPlaytimeTracking( IntPtr self, [In,Out] PublishedFileId[] pvecPublishedFileID, uint unNumPublishedFileIDs );
#endregion
internal CallResult<StopPlaytimeTrackingResult_t> StopPlaytimeTracking( [In,Out] PublishedFileId[] pvecPublishedFileID, uint unNumPublishedFileIDs )
{
var returnValue = _StopPlaytimeTracking( Self, pvecPublishedFileID, unNumPublishedFileIDs );
return new CallResult<StopPlaytimeTrackingResult_t>( returnValue, IsServer );
}
#region FunctionMeta
[DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_ISteamUGC_StopPlaytimeTrackingForAllItems", CallingConvention = Platform.CC)]
private static extern SteamAPICall_t _StopPlaytimeTrackingForAllItems( IntPtr self );
#endregion
internal CallResult<StopPlaytimeTrackingResult_t> StopPlaytimeTrackingForAllItems()
{
var returnValue = _StopPlaytimeTrackingForAllItems( Self );
return new CallResult<StopPlaytimeTrackingResult_t>( returnValue, IsServer );
}
#region FunctionMeta
[DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_ISteamUGC_AddDependency", CallingConvention = Platform.CC)]
private static extern SteamAPICall_t _AddDependency( IntPtr self, PublishedFileId nParentPublishedFileID, PublishedFileId nChildPublishedFileID );
#endregion
internal CallResult<AddUGCDependencyResult_t> AddDependency( PublishedFileId nParentPublishedFileID, PublishedFileId nChildPublishedFileID )
{
var returnValue = _AddDependency( Self, nParentPublishedFileID, nChildPublishedFileID );
return new CallResult<AddUGCDependencyResult_t>( returnValue, IsServer );
}
#region FunctionMeta
[DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_ISteamUGC_RemoveDependency", CallingConvention = Platform.CC)]
private static extern SteamAPICall_t _RemoveDependency( IntPtr self, PublishedFileId nParentPublishedFileID, PublishedFileId nChildPublishedFileID );
#endregion
internal CallResult<RemoveUGCDependencyResult_t> RemoveDependency( PublishedFileId nParentPublishedFileID, PublishedFileId nChildPublishedFileID )
{
var returnValue = _RemoveDependency( Self, nParentPublishedFileID, nChildPublishedFileID );
return new CallResult<RemoveUGCDependencyResult_t>( returnValue, IsServer );
}
#region FunctionMeta
[DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_ISteamUGC_AddAppDependency", CallingConvention = Platform.CC)]
private static extern SteamAPICall_t _AddAppDependency( IntPtr self, PublishedFileId nPublishedFileID, AppId nAppID );
#endregion
internal CallResult<AddAppDependencyResult_t> AddAppDependency( PublishedFileId nPublishedFileID, AppId nAppID )
{
var returnValue = _AddAppDependency( Self, nPublishedFileID, nAppID );
return new CallResult<AddAppDependencyResult_t>( returnValue, IsServer );
}
#region FunctionMeta
[DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_ISteamUGC_RemoveAppDependency", CallingConvention = Platform.CC)]
private static extern SteamAPICall_t _RemoveAppDependency( IntPtr self, PublishedFileId nPublishedFileID, AppId nAppID );
#endregion
internal CallResult<RemoveAppDependencyResult_t> RemoveAppDependency( PublishedFileId nPublishedFileID, AppId nAppID )
{
var returnValue = _RemoveAppDependency( Self, nPublishedFileID, nAppID );
return new CallResult<RemoveAppDependencyResult_t>( returnValue, IsServer );
}
#region FunctionMeta
[DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_ISteamUGC_GetAppDependencies", CallingConvention = Platform.CC)]
private static extern SteamAPICall_t _GetAppDependencies( IntPtr self, PublishedFileId nPublishedFileID );
#endregion
internal CallResult<GetAppDependenciesResult_t> GetAppDependencies( PublishedFileId nPublishedFileID )
{
var returnValue = _GetAppDependencies( Self, nPublishedFileID );
return new CallResult<GetAppDependenciesResult_t>( returnValue, IsServer );
}
#region FunctionMeta
[DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_ISteamUGC_DeleteItem", CallingConvention = Platform.CC)]
private static extern SteamAPICall_t _DeleteItem( IntPtr self, PublishedFileId nPublishedFileID );
#endregion
internal CallResult<DeleteItemResult_t> DeleteItem( PublishedFileId nPublishedFileID )
{
var returnValue = _DeleteItem( Self, nPublishedFileID );
return new CallResult<DeleteItemResult_t>( returnValue, IsServer );
}
#region FunctionMeta
[DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_ISteamUGC_ShowWorkshopEULA", CallingConvention = Platform.CC)]
[return: MarshalAs( UnmanagedType.I1 )]
private static extern bool _ShowWorkshopEULA( IntPtr self );
#endregion
internal bool ShowWorkshopEULA()
{
var returnValue = _ShowWorkshopEULA( Self );
return returnValue;
}
#region FunctionMeta
[DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_ISteamUGC_GetWorkshopEULAStatus", CallingConvention = Platform.CC)]
private static extern SteamAPICall_t _GetWorkshopEULAStatus( IntPtr self );
#endregion
internal CallResult<WorkshopEULAStatus_t> GetWorkshopEULAStatus()
{
var returnValue = _GetWorkshopEULAStatus( Self );
return new CallResult<WorkshopEULAStatus_t>( returnValue, IsServer );
}
}
}
| |
using System;
using System.Diagnostics;
using System.Text;
using Pgno = System.UInt32;
using u32 = System.UInt32;
namespace System.Data.SQLite
{
using sqlite3_stmt = Sqlite3.Vdbe;
internal partial class Sqlite3
{
/*
** 2003 April 6
**
** The author disclaims copyright to this source code. In place of
** a legal notice, here is a blessing:
**
** May you do good and not evil.
** May you find forgiveness for yourself and forgive others.
** May you share freely, never taking more than you give.
**
*************************************************************************
** This file contains code used to implement the VACUUM command.
**
** Most of the code in this file may be omitted by defining the
** SQLITE_OMIT_VACUUM macro.
*************************************************************************
** Included in SQLite3 port to C#-SQLite; 2008 Noah B Hart
** C#-SQLite is an independent reimplementation of the SQLite software library
**
** SQLITE_SOURCE_ID: 2011-05-19 13:26:54 ed1da510a239ea767a01dc332b667119fa3c908e
**
*************************************************************************
*/
//#include "sqliteInt.h"
//#include "vdbeInt.h"
#if !SQLITE_OMIT_VACUUM && !SQLITE_OMIT_ATTACH
/*
** Finalize a prepared statement. If there was an error, store the
** text of the error message in *pzErrMsg. Return the result code.
*/
static int vacuumFinalize(sqlite3 db, sqlite3_stmt pStmt, string pzErrMsg)
{
int rc;
rc = sqlite3VdbeFinalize(ref pStmt);
if (rc != 0)
{
sqlite3SetString(ref pzErrMsg, db, sqlite3_errmsg(db));
}
return rc;
}
/*
** Execute zSql on database db. Return an error code.
*/
static int execSql(sqlite3 db, string pzErrMsg, string zSql)
{
sqlite3_stmt pStmt = null;
#if !NDEBUG
int rc;
//VVA_ONLY( int rc; )
#endif
if (zSql == null)
{
return SQLITE_NOMEM;
}
if (SQLITE_OK != sqlite3_prepare(db, zSql, -1, ref pStmt, 0))
{
sqlite3SetString(ref pzErrMsg, db, sqlite3_errmsg(db));
return sqlite3_errcode(db);
}
#if !NDEBUG
rc = sqlite3_step( pStmt );
//VVA_ONLY( rc = ) sqlite3_step(pStmt);
Debug.Assert( rc != SQLITE_ROW );
#else
sqlite3_step(pStmt);
#endif
return vacuumFinalize(db, pStmt, pzErrMsg);
}
/*
** Execute zSql on database db. The statement returns exactly
** one column. Execute this as SQL on the same database.
*/
static int execExecSql(sqlite3 db, string pzErrMsg, string zSql)
{
sqlite3_stmt pStmt = null;
int rc;
rc = sqlite3_prepare(db, zSql, -1, ref pStmt, 0);
if (rc != SQLITE_OK)
return rc;
while (SQLITE_ROW == sqlite3_step(pStmt))
{
rc = execSql(db, pzErrMsg, sqlite3_column_text(pStmt, 0));
if (rc != SQLITE_OK)
{
vacuumFinalize(db, pStmt, pzErrMsg);
return rc;
}
}
return vacuumFinalize(db, pStmt, pzErrMsg);
}
/*
** The non-standard VACUUM command is used to clean up the database,
** collapse free space, etc. It is modelled after the VACUUM command
** in PostgreSQL.
**
** In version 1.0.x of SQLite, the VACUUM command would call
** gdbm_reorganize() on all the database tables. But beginning
** with 2.0.0, SQLite no longer uses GDBM so this command has
** become a no-op.
*/
static void sqlite3Vacuum(Parse pParse)
{
Vdbe v = sqlite3GetVdbe(pParse);
if (v != null)
{
sqlite3VdbeAddOp2(v, OP_Vacuum, 0, 0);
}
return;
}
/*
** This routine implements the OP_Vacuum opcode of the VDBE.
*/
static int sqlite3RunVacuum(ref string pzErrMsg, sqlite3 db)
{
int rc = SQLITE_OK; /* Return code from service routines */
Btree pMain; /* The database being vacuumed */
Btree pTemp; /* The temporary database we vacuum into */
string zSql = ""; /* SQL statements */
int saved_flags; /* Saved value of the db.flags */
int saved_nChange; /* Saved value of db.nChange */
int saved_nTotalChange; /* Saved value of db.nTotalChange */
dxTrace saved_xTrace; //void (*saved_xTrace)(void*,const char*); /* Saved db->xTrace */
Db pDb = null; /* Database to detach at end of vacuum */
bool isMemDb; /* True if vacuuming a :memory: database */
int nRes; /* Bytes of reserved space at the end of each page */
int nDb; /* Number of attached databases */
if (0 == db.autoCommit)
{
sqlite3SetString(ref pzErrMsg, db, "cannot VACUUM from within a transaction");
return SQLITE_ERROR;
}
if (db.activeVdbeCnt > 1)
{
sqlite3SetString(ref pzErrMsg, db, "cannot VACUUM - SQL statements in progress");
return SQLITE_ERROR;
}
/* Save the current value of the database flags so that it can be
** restored before returning. Then set the writable-schema flag, and
** disable CHECK and foreign key constraints. */
saved_flags = db.flags;
saved_nChange = db.nChange;
saved_nTotalChange = db.nTotalChange;
saved_xTrace = db.xTrace;
db.flags |= SQLITE_WriteSchema | SQLITE_IgnoreChecks | SQLITE_PreferBuiltin;
db.flags &= ~(SQLITE_ForeignKeys | SQLITE_ReverseOrder);
db.xTrace = null;
pMain = db.aDb[0].pBt;
isMemDb = sqlite3PagerIsMemdb(sqlite3BtreePager(pMain));
/* Attach the temporary database as 'vacuum_db'. The synchronous pragma
** can be set to 'off' for this file, as it is not recovered if a crash
** occurs anyway. The integrity of the database is maintained by a
** (possibly synchronous) transaction opened on the main database before
** sqlite3BtreeCopyFile() is called.
**
** An optimisation would be to use a non-journaled pager.
** (Later:) I tried setting "PRAGMA vacuum_db.journal_mode=OFF" but
** that actually made the VACUUM run slower. Very little journalling
** actually occurs when doing a vacuum since the vacuum_db is initially
** empty. Only the journal header is written. Apparently it takes more
** time to parse and run the PRAGMA to turn journalling off than it does
** to write the journal header file.
*/
nDb = db.nDb;
if (sqlite3TempInMemory(db))
{
zSql = "ATTACH ':memory:' AS vacuum_db;";
}
else
{
zSql = "ATTACH '' AS vacuum_db;";
}
rc = execSql(db, pzErrMsg, zSql);
if (db.nDb > nDb)
{
pDb = db.aDb[db.nDb - 1];
Debug.Assert(pDb.zName == "vacuum_db");
}
if (rc != SQLITE_OK)
goto end_of_vacuum;
pDb = db.aDb[db.nDb - 1];
Debug.Assert(db.aDb[db.nDb - 1].zName == "vacuum_db");
pTemp = db.aDb[db.nDb - 1].pBt;
/* The call to execSql() to attach the temp database has left the file
** locked (as there was more than one active statement when the transaction
** to read the schema was concluded. Unlock it here so that this doesn't
** cause problems for the call to BtreeSetPageSize() below. */
sqlite3BtreeCommit(pTemp);
nRes = sqlite3BtreeGetReserve(pMain);
/* A VACUUM cannot change the pagesize of an encrypted database. */
#if SQLITE_HAS_CODEC
if ( db.nextPagesize != 0 )
{
//extern void sqlite3CodecGetKey(sqlite3*, int, void**, int*);
int nKey;
string zKey;
sqlite3CodecGetKey( db, 0, out zKey, out nKey ); // sqlite3CodecGetKey(db, 0, (void**)&zKey, nKey);
if ( nKey != 0 )
db.nextPagesize = 0;
}
#endif
/* Do not attempt to change the page size for a WAL database */
if (sqlite3PagerGetJournalMode(sqlite3BtreePager(pMain))
== PAGER_JOURNALMODE_WAL)
{
db.nextPagesize = 0;
}
if (sqlite3BtreeSetPageSize(pTemp, sqlite3BtreeGetPageSize(pMain), nRes, 0) != 0
|| (!isMemDb && sqlite3BtreeSetPageSize(pTemp, db.nextPagesize, nRes, 0) != 0)
//|| NEVER( db.mallocFailed != 0 )
)
{
rc = SQLITE_NOMEM;
goto end_of_vacuum;
}
rc = execSql(db, pzErrMsg, "PRAGMA vacuum_db.synchronous=OFF");
if (rc != SQLITE_OK)
{
goto end_of_vacuum;
}
#if !SQLITE_OMIT_AUTOVACUUM
sqlite3BtreeSetAutoVacuum(pTemp, db.nextAutovac >= 0 ? db.nextAutovac :
sqlite3BtreeGetAutoVacuum(pMain));
#endif
/* Begin a transaction */
rc = execSql(db, pzErrMsg, "BEGIN EXCLUSIVE;");
if (rc != SQLITE_OK)
goto end_of_vacuum;
/* Query the schema of the main database. Create a mirror schema
** in the temporary database.
*/
rc = execExecSql(db, pzErrMsg,
"SELECT 'CREATE TABLE vacuum_db.' || substr(sql,14) " +
" FROM sqlite_master WHERE type='table' AND name!='sqlite_sequence'" +
" AND rootpage>0"
);
if (rc != SQLITE_OK)
goto end_of_vacuum;
rc = execExecSql(db, pzErrMsg,
"SELECT 'CREATE INDEX vacuum_db.' || substr(sql,14)" +
" FROM sqlite_master WHERE sql LIKE 'CREATE INDEX %' ");
if (rc != SQLITE_OK)
goto end_of_vacuum;
rc = execExecSql(db, pzErrMsg,
"SELECT 'CREATE UNIQUE INDEX vacuum_db.' || substr(sql,21) " +
" FROM sqlite_master WHERE sql LIKE 'CREATE UNIQUE INDEX %'");
if (rc != SQLITE_OK)
goto end_of_vacuum;
/* Loop through the tables in the main database. For each, do
** an "INSERT INTO vacuum_db.xxx SELECT * FROM main.xxx;" to copy
** the contents to the temporary database.
*/
rc = execExecSql(db, pzErrMsg,
"SELECT 'INSERT INTO vacuum_db.' || quote(name) " +
"|| ' SELECT * FROM main.' || quote(name) || ';'" +
"FROM main.sqlite_master " +
"WHERE type = 'table' AND name!='sqlite_sequence' " +
" AND rootpage>0"
);
if (rc != SQLITE_OK)
goto end_of_vacuum;
/* Copy over the sequence table
*/
rc = execExecSql(db, pzErrMsg,
"SELECT 'DELETE FROM vacuum_db.' || quote(name) || ';' " +
"FROM vacuum_db.sqlite_master WHERE name='sqlite_sequence' "
);
if (rc != SQLITE_OK)
goto end_of_vacuum;
rc = execExecSql(db, pzErrMsg,
"SELECT 'INSERT INTO vacuum_db.' || quote(name) " +
"|| ' SELECT * FROM main.' || quote(name) || ';' " +
"FROM vacuum_db.sqlite_master WHERE name=='sqlite_sequence';"
);
if (rc != SQLITE_OK)
goto end_of_vacuum;
/* Copy the triggers, views, and virtual tables from the main database
** over to the temporary database. None of these objects has any
** associated storage, so all we have to do is copy their entries
** from the SQLITE_MASTER table.
*/
rc = execSql(db, pzErrMsg,
"INSERT INTO vacuum_db.sqlite_master " +
" SELECT type, name, tbl_name, rootpage, sql" +
" FROM main.sqlite_master" +
" WHERE type='view' OR type='trigger'" +
" OR (type='table' AND rootpage=0)"
);
if (rc != 0)
goto end_of_vacuum;
/* At this point, unless the main db was completely empty, there is now a
** transaction open on the vacuum database, but not on the main database.
** Open a btree level transaction on the main database. This allows a
** call to sqlite3BtreeCopyFile(). The main database btree level
** transaction is then committed, so the SQL level never knows it was
** opened for writing. This way, the SQL transaction used to create the
** temporary database never needs to be committed.
*/
{
u32 meta = 0;
int i;
/* This array determines which meta meta values are preserved in the
** vacuum. Even entries are the meta value number and odd entries
** are an increment to apply to the meta value after the vacuum.
** The increment is used to increase the schema cookie so that other
** connections to the same database will know to reread the schema.
*/
byte[] aCopy = new byte[] {
BTREE_SCHEMA_VERSION, 1, /* Add one to the old schema cookie */
BTREE_DEFAULT_CACHE_SIZE, 0, /* Preserve the default page cache size */
BTREE_TEXT_ENCODING, 0, /* Preserve the text encoding */
BTREE_USER_VERSION, 0, /* Preserve the user version */
};
Debug.Assert(sqlite3BtreeIsInTrans(pTemp));
Debug.Assert(sqlite3BtreeIsInTrans(pMain));
/* Copy Btree meta values */
for (i = 0; i < ArraySize(aCopy); i += 2)
{
/* GetMeta() and UpdateMeta() cannot fail in this context because
** we already have page 1 loaded into cache and marked dirty. */
sqlite3BtreeGetMeta(pMain, aCopy[i], ref meta);
rc = sqlite3BtreeUpdateMeta(pTemp, aCopy[i], (u32)(meta + aCopy[i + 1]));
if (NEVER(rc != SQLITE_OK))
goto end_of_vacuum;
}
rc = sqlite3BtreeCopyFile(pMain, pTemp);
if (rc != SQLITE_OK)
goto end_of_vacuum;
rc = sqlite3BtreeCommit(pTemp);
if (rc != SQLITE_OK)
goto end_of_vacuum;
#if !SQLITE_OMIT_AUTOVACUUM
sqlite3BtreeSetAutoVacuum(pMain, sqlite3BtreeGetAutoVacuum(pTemp));
#endif
}
Debug.Assert(rc == SQLITE_OK);
rc = sqlite3BtreeSetPageSize(pMain, sqlite3BtreeGetPageSize(pTemp), nRes, 1);
end_of_vacuum:
/* Restore the original value of db.flags */
db.flags = saved_flags;
db.nChange = saved_nChange;
db.nTotalChange = saved_nTotalChange;
db.xTrace = saved_xTrace;
sqlite3BtreeSetPageSize(pMain, -1, -1, 1);
/* Currently there is an SQL level transaction open on the vacuum
** database. No locks are held on any other files (since the main file
** was committed at the btree level). So it safe to end the transaction
** by manually setting the autoCommit flag to true and detaching the
** vacuum database. The vacuum_db journal file is deleted when the pager
** is closed by the DETACH.
*/
db.autoCommit = 1;
if (pDb != null)
{
sqlite3BtreeClose(ref pDb.pBt);
pDb.pBt = null;
pDb.pSchema = null;
}
/* This both clears the schemas and reduces the size of the db->aDb[]
** array. */
sqlite3ResetInternalSchema(db, -1);
return rc;
}
#endif // * SQLITE_OMIT_VACUUM && SQLITE_OMIT_ATTACH */
}
}
| |
using System;
using System.Collections.Generic;
using System.Threading;
using EcsRx.Collections;
using EcsRx.Entities;
using EcsRx.Groups;
using EcsRx.Groups.Observable;
using EcsRx.MicroRx.Subjects;
using EcsRx.Plugins.ReactiveSystems.Handlers;
using EcsRx.Plugins.ReactiveSystems.Systems;
using EcsRx.Systems;
using NSubstitute;
using Xunit;
namespace EcsRx.Tests.Plugins.ReactiveSystems.Handlers
{
public class SetupSystemHandlerTests
{
[Fact]
public void should_correctly_handle_systems()
{
var mockCollectionManager = Substitute.For<IEntityCollectionManager>();
var reactToEntitySystemHandler = new SetupSystemHandler(mockCollectionManager);
var fakeMatchingSystem = Substitute.For<ISetupSystem>();
var fakeNonMatchingSystem1 = Substitute.For<IReactToEntitySystem>();
var fakeNonMatchingSystem2 = Substitute.For<ISystem>();
Assert.True(reactToEntitySystemHandler.CanHandleSystem(fakeMatchingSystem));
Assert.False(reactToEntitySystemHandler.CanHandleSystem(fakeNonMatchingSystem1));
Assert.False(reactToEntitySystemHandler.CanHandleSystem(fakeNonMatchingSystem2));
}
[Fact]
public void should_execute_system_without_predicate()
{
var fakeEntity1 = Substitute.For<IEntity>();
var fakeEntity2 = Substitute.For<IEntity>();
fakeEntity1.Id.Returns(1);
fakeEntity2.Id.Returns(2);
var fakeEntities = new List<IEntity> { fakeEntity1, fakeEntity2 };
var mockObservableGroup = Substitute.For<IObservableGroup>();
mockObservableGroup.OnEntityAdded.Returns(new Subject<IEntity>());
mockObservableGroup.OnEntityRemoved.Returns(new Subject<IEntity>());
mockObservableGroup.GetEnumerator().Returns(fakeEntities.GetEnumerator());
var mockCollectionManager = Substitute.For<IEntityCollectionManager>();
var fakeGroup = Substitute.For<IGroup>();
fakeGroup.RequiredComponents.Returns(new Type[0]);
mockCollectionManager.GetObservableGroup(Arg.Is(fakeGroup), Arg.Any<int[]>()).Returns(mockObservableGroup);
var mockSystem = Substitute.For<ISetupSystem>();
mockSystem.Group.Returns(fakeGroup);
var systemHandler = new SetupSystemHandler(mockCollectionManager);
systemHandler.SetupSystem(mockSystem);
mockSystem.Received(1).Setup(Arg.Is(fakeEntity1));
mockSystem.Received(1).Setup(Arg.Is(fakeEntity2));
Assert.Equal(1, systemHandler._systemSubscriptions.Count);
Assert.NotNull(systemHandler._systemSubscriptions[mockSystem]);
Assert.Equal(1, systemHandler._entitySubscriptions.Count);
Assert.Equal(0, systemHandler._entitySubscriptions[mockSystem].Count);
}
[Fact]
public void should_execute_system_when_entity_added_without_predicate()
{
var fakeEntity1 = Substitute.For<IEntity>();
var fakeEntity2 = Substitute.For<IEntity>();
fakeEntity1.Id.Returns(1);
fakeEntity2.Id.Returns(2);
var fakeEntities = new List<IEntity>();
var mockObservableGroup = Substitute.For<IObservableGroup>();
var addingSubject = new Subject<IEntity>();
mockObservableGroup.OnEntityAdded.Returns(addingSubject);
mockObservableGroup.OnEntityRemoved.Returns(new Subject<IEntity>());
mockObservableGroup.GetEnumerator().Returns(fakeEntities.GetEnumerator());
var mockCollectionManager = Substitute.For<IEntityCollectionManager>();
var fakeGroup = Substitute.For<IGroup>();
fakeGroup.RequiredComponents.Returns(new Type[0]);
mockCollectionManager.GetObservableGroup(Arg.Is(fakeGroup), Arg.Any<int[]>()).Returns(mockObservableGroup);
var mockSystem = Substitute.For<ISetupSystem>();
mockSystem.Group.Returns(fakeGroup);
var systemHandler = new SetupSystemHandler(mockCollectionManager);
systemHandler.SetupSystem(mockSystem);
mockSystem.Received(0).Setup(Arg.Is(fakeEntity1));
mockSystem.Received(0).Setup(Arg.Is(fakeEntity2));
Assert.Equal(1, systemHandler._systemSubscriptions.Count);
Assert.NotNull(systemHandler._systemSubscriptions[mockSystem]);
Assert.Equal(1, systemHandler._entitySubscriptions.Count);
Assert.Equal(0, systemHandler._entitySubscriptions[mockSystem].Count);
addingSubject.OnNext(fakeEntity1);
addingSubject.OnNext(fakeEntity2);
mockSystem.Received(1).Setup(Arg.Is(fakeEntity1));
mockSystem.Received(1).Setup(Arg.Is(fakeEntity2));
Assert.Equal(1, systemHandler._systemSubscriptions.Count);
Assert.NotNull(systemHandler._systemSubscriptions[mockSystem]);
Assert.Equal(1, systemHandler._entitySubscriptions.Count);
Assert.Equal(0, systemHandler._entitySubscriptions[mockSystem].Count);
}
[Fact]
public void should_dispose_observables_when_entity_removed()
{
var fakeEntity1 = Substitute.For<IEntity>();
fakeEntity1.Id.Returns(1);
var fakeEntities = new List<IEntity>();
var mockObservableGroup = Substitute.For<IObservableGroup>();
var removingSubject = new Subject<IEntity>();
mockObservableGroup.OnEntityAdded.Returns(new Subject<IEntity>());
mockObservableGroup.OnEntityRemoved.Returns(removingSubject);
mockObservableGroup.GetEnumerator().Returns(fakeEntities.GetEnumerator());
var mockCollectionManager = Substitute.For<IEntityCollectionManager>();
var fakeGroup = Substitute.For<IGroup>();
fakeGroup.RequiredComponents.Returns(new Type[0]);
mockCollectionManager.GetObservableGroup(Arg.Is(fakeGroup), Arg.Any<int[]>()).Returns(mockObservableGroup);
var mockSystem = Substitute.For<ISetupSystem>();
mockSystem.Group.Returns(fakeGroup);
var systemHandler = new SetupSystemHandler(mockCollectionManager);
systemHandler.SetupSystem(mockSystem);
var mockDisposable = Substitute.For<IDisposable>();
systemHandler._entitySubscriptions[mockSystem].Add(fakeEntity1.Id, mockDisposable);
removingSubject.OnNext(fakeEntity1);
mockDisposable.Received(1).Dispose();
Assert.Equal(1, systemHandler._systemSubscriptions.Count);
Assert.NotNull(systemHandler._systemSubscriptions[mockSystem]);
Assert.Equal(1, systemHandler._entitySubscriptions.Count);
Assert.Equal(0, systemHandler._entitySubscriptions[mockSystem].Count);
}
[Fact]
public void should_execute_systems_when_predicate_met()
{
var id1 = 1;
var id2 = 2;
var fakeEntity1 = Substitute.For<IEntity>();
var fakeEntity2 = Substitute.For<IEntity>();
var fakeEntities = new List<IEntity> { fakeEntity1, fakeEntity2 };
fakeEntity1.Id.Returns(id1);
fakeEntity2.Id.Returns(id2);
var mockObservableGroup = Substitute.For<IObservableGroup>();
mockObservableGroup.OnEntityAdded.Returns(new Subject<IEntity>());
mockObservableGroup.OnEntityRemoved.Returns(new Subject<IEntity>());
mockObservableGroup.GetEnumerator().Returns(fakeEntities.GetEnumerator());
var mockCollectionManager = Substitute.For<IEntityCollectionManager>();
var fakeGroup = new Group(x => x.Id == fakeEntity1.Id);
mockCollectionManager.GetObservableGroup(Arg.Is(fakeGroup), Arg.Any<int[]>()).Returns(mockObservableGroup);
var mockSystem = Substitute.For<ISetupSystem>();
mockSystem.Group.Returns(fakeGroup);
var systemHandler = new SetupSystemHandler(mockCollectionManager);
systemHandler.SetupSystem(mockSystem);
mockSystem.Received(1).Setup(Arg.Is(fakeEntity1));
mockSystem.Received(0).Setup(Arg.Is(fakeEntity2));
Assert.Equal(1, systemHandler._systemSubscriptions.Count);
Assert.NotNull(systemHandler._systemSubscriptions[mockSystem]);
Assert.Equal(1, systemHandler._entitySubscriptions.Count);
Assert.Equal(1, systemHandler._entitySubscriptions[mockSystem].Count);
Assert.True(systemHandler._entitySubscriptions[mockSystem].ContainsKey(fakeEntity2.Id));
}
[Fact]
public void should_execute_systems_when_predicate_met_after_period()
{
var id1 = 1;
var id2 = 2;
var expectedDate = DateTime.Now + TimeSpan.FromMilliseconds(500);
var fakeEntity1 = Substitute.For<IEntity>();
var fakeEntity2 = Substitute.For<IEntity>();
var fakeEntities = new List<IEntity> { fakeEntity1, fakeEntity2 };
fakeEntity1.Id.Returns(id1);
fakeEntity2.Id.Returns(id2);
var mockObservableGroup = Substitute.For<IObservableGroup>();
mockObservableGroup.OnEntityAdded.Returns(new Subject<IEntity>());
mockObservableGroup.OnEntityRemoved.Returns(new Subject<IEntity>());
mockObservableGroup.GetEnumerator().Returns(fakeEntities.GetEnumerator());
var mockCollectionManager = Substitute.For<IEntityCollectionManager>();
var fakeGroup = new Group(x => x.Id == fakeEntity1.Id && DateTime.Now >= expectedDate);
mockCollectionManager.GetObservableGroup(Arg.Is(fakeGroup), Arg.Any<int[]>()).Returns(mockObservableGroup);
var mockSystem = Substitute.For<ISetupSystem>();
mockSystem.Group.Returns(fakeGroup);
var systemHandler = new SetupSystemHandler(mockCollectionManager);
systemHandler.SetupSystem(mockSystem);
Assert.Equal(1, systemHandler._systemSubscriptions.Count);
Assert.NotNull(systemHandler._systemSubscriptions[mockSystem]);
Assert.Equal(1, systemHandler._entitySubscriptions.Count);
Assert.Equal(2, systemHandler._entitySubscriptions[mockSystem].Count);
Assert.True(systemHandler._entitySubscriptions[mockSystem].ContainsKey(fakeEntity1.Id));
Assert.True(systemHandler._entitySubscriptions[mockSystem].ContainsKey(fakeEntity2.Id));
Thread.Sleep(2000);
mockSystem.Received(1).Setup(Arg.Is(fakeEntity1));
mockSystem.Received(0).Setup(Arg.Is(fakeEntity2));
Assert.Equal(1, systemHandler._systemSubscriptions.Count);
Assert.NotNull(systemHandler._systemSubscriptions[mockSystem]);
Assert.Equal(1, systemHandler._entitySubscriptions.Count);
Assert.Equal(1, systemHandler._entitySubscriptions[mockSystem].Count);
Assert.True(systemHandler._entitySubscriptions[mockSystem].ContainsKey(fakeEntity2.Id));
}
}
}
| |
// Copyright (c) 1995-2009 held by the author(s). All rights reserved.
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the names of the Naval Postgraduate School (NPS)
// Modeling Virtual Environments and Simulation (MOVES) Institute
// (http://www.nps.edu and http://www.MovesInstitute.org)
// nor the names of its contributors may be used to endorse or
// promote products derived from this software without specific
// prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// AS IS AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
// COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
// BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
// LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
// ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008, MOVES Institute, Naval Postgraduate School. All
// rights reserved. This work is licensed under the BSD open source license,
// available at https://www.movesinstitute.org/licenses/bsd.html
//
// Author: DMcG
// Modified for use with C#:
// - Peter Smith (Naval Air Warfare Center - Training Systems Division)
// - Zvonko Bostjancic (Blubit d.o.o. - [email protected])
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Text;
using System.Xml.Serialization;
using OpenDis.Core;
namespace OpenDis.Dis1995
{
/// <summary>
/// Section 5.3.34. Three double precision floating point values, x, y, and z
/// </summary>
[Serializable]
[XmlRoot]
public partial class Vector3Double
{
/// <summary>
/// X value
/// </summary>
private double _x;
/// <summary>
/// Y value
/// </summary>
private double _y;
/// <summary>
/// Z value
/// </summary>
private double _z;
/// <summary>
/// Initializes a new instance of the <see cref="Vector3Double"/> class.
/// </summary>
public Vector3Double()
{
}
/// <summary>
/// Implements the operator !=.
/// </summary>
/// <param name="left">The left operand.</param>
/// <param name="right">The right operand.</param>
/// <returns>
/// <c>true</c> if operands are not equal; otherwise, <c>false</c>.
/// </returns>
public static bool operator !=(Vector3Double left, Vector3Double right)
{
return !(left == right);
}
/// <summary>
/// Implements the operator ==.
/// </summary>
/// <param name="left">The left operand.</param>
/// <param name="right">The right operand.</param>
/// <returns>
/// <c>true</c> if both operands are equal; otherwise, <c>false</c>.
/// </returns>
public static bool operator ==(Vector3Double left, Vector3Double right)
{
if (object.ReferenceEquals(left, right))
{
return true;
}
if (((object)left == null) || ((object)right == null))
{
return false;
}
return left.Equals(right);
}
public virtual int GetMarshalledSize()
{
int marshalSize = 0;
marshalSize += 8; // this._x
marshalSize += 8; // this._y
marshalSize += 8; // this._z
return marshalSize;
}
/// <summary>
/// Gets or sets the X value
/// </summary>
[XmlElement(Type = typeof(double), ElementName = "x")]
public double X
{
get
{
return this._x;
}
set
{
this._x = value;
}
}
/// <summary>
/// Gets or sets the Y value
/// </summary>
[XmlElement(Type = typeof(double), ElementName = "y")]
public double Y
{
get
{
return this._y;
}
set
{
this._y = value;
}
}
/// <summary>
/// Gets or sets the Z value
/// </summary>
[XmlElement(Type = typeof(double), ElementName = "z")]
public double Z
{
get
{
return this._z;
}
set
{
this._z = value;
}
}
/// <summary>
/// Occurs when exception when processing PDU is caught.
/// </summary>
public event EventHandler<PduExceptionEventArgs> ExceptionOccured;
/// <summary>
/// Called when exception occurs (raises the <see cref="Exception"/> event).
/// </summary>
/// <param name="e">The exception.</param>
protected void RaiseExceptionOccured(Exception e)
{
if (Pdu.FireExceptionEvents && this.ExceptionOccured != null)
{
this.ExceptionOccured(this, new PduExceptionEventArgs(e));
}
}
/// <summary>
/// Marshal the data to the DataOutputStream. Note: Length needs to be set before calling this method
/// </summary>
/// <param name="dos">The DataOutputStream instance to which the PDU is marshaled.</param>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Due to ignoring errors.")]
public virtual void Marshal(DataOutputStream dos)
{
if (dos != null)
{
try
{
dos.WriteDouble((double)this._x);
dos.WriteDouble((double)this._y);
dos.WriteDouble((double)this._z);
}
catch (Exception e)
{
if (PduBase.TraceExceptions)
{
Trace.WriteLine(e);
Trace.Flush();
}
this.RaiseExceptionOccured(e);
if (PduBase.ThrowExceptions)
{
throw e;
}
}
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Due to ignoring errors.")]
public virtual void Unmarshal(DataInputStream dis)
{
if (dis != null)
{
try
{
this._x = dis.ReadDouble();
this._y = dis.ReadDouble();
this._z = dis.ReadDouble();
}
catch (Exception e)
{
if (PduBase.TraceExceptions)
{
Trace.WriteLine(e);
Trace.Flush();
}
this.RaiseExceptionOccured(e);
if (PduBase.ThrowExceptions)
{
throw e;
}
}
}
}
/// <summary>
/// This allows for a quick display of PDU data. The current format is unacceptable and only used for debugging.
/// This will be modified in the future to provide a better display. Usage:
/// pdu.GetType().InvokeMember("Reflection", System.Reflection.BindingFlags.InvokeMethod, null, pdu, new object[] { sb });
/// where pdu is an object representing a single pdu and sb is a StringBuilder.
/// Note: The supplied Utilities folder contains a method called 'DecodePDU' in the PDUProcessor Class that provides this functionality
/// </summary>
/// <param name="sb">The StringBuilder instance to which the PDU is written to.</param>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Due to ignoring errors.")]
public virtual void Reflection(StringBuilder sb)
{
sb.AppendLine("<Vector3Double>");
try
{
sb.AppendLine("<x type=\"double\">" + this._x.ToString(CultureInfo.InvariantCulture) + "</x>");
sb.AppendLine("<y type=\"double\">" + this._y.ToString(CultureInfo.InvariantCulture) + "</y>");
sb.AppendLine("<z type=\"double\">" + this._z.ToString(CultureInfo.InvariantCulture) + "</z>");
sb.AppendLine("</Vector3Double>");
}
catch (Exception e)
{
if (PduBase.TraceExceptions)
{
Trace.WriteLine(e);
Trace.Flush();
}
this.RaiseExceptionOccured(e);
if (PduBase.ThrowExceptions)
{
throw e;
}
}
}
/// <summary>
/// Determines whether the specified <see cref="System.Object"/> is equal to this instance.
/// </summary>
/// <param name="obj">The <see cref="System.Object"/> to compare with this instance.</param>
/// <returns>
/// <c>true</c> if the specified <see cref="System.Object"/> is equal to this instance; otherwise, <c>false</c>.
/// </returns>
public override bool Equals(object obj)
{
return this == obj as Vector3Double;
}
/// <summary>
/// Compares for reference AND value equality.
/// </summary>
/// <param name="obj">The object to compare with this instance.</param>
/// <returns>
/// <c>true</c> if both operands are equal; otherwise, <c>false</c>.
/// </returns>
public bool Equals(Vector3Double obj)
{
bool ivarsEqual = true;
if (obj.GetType() != this.GetType())
{
return false;
}
if (this._x != obj._x)
{
ivarsEqual = false;
}
if (this._y != obj._y)
{
ivarsEqual = false;
}
if (this._z != obj._z)
{
ivarsEqual = false;
}
return ivarsEqual;
}
/// <summary>
/// HashCode Helper
/// </summary>
/// <param name="hash">The hash value.</param>
/// <returns>The new hash value.</returns>
private static int GenerateHash(int hash)
{
hash = hash << (5 + hash);
return hash;
}
/// <summary>
/// Gets the hash code.
/// </summary>
/// <returns>The hash code.</returns>
public override int GetHashCode()
{
int result = 0;
result = GenerateHash(result) ^ this._x.GetHashCode();
result = GenerateHash(result) ^ this._y.GetHashCode();
result = GenerateHash(result) ^ this._z.GetHashCode();
return result;
}
}
}
| |
using System;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using FluentNHibernate.Conventions;
using FluentNHibernate.Conventions.Inspections;
using FluentNHibernate.MappingModel;
using FluentNHibernate.Utils;
using NUnit.Framework;
namespace FluentNHibernate.Testing.ConventionsTests.Inspection
{
[TestFixture, Category("Inspection DSL")]
public class AnyInspectorMapsToAnyMapping
{
private AnyMapping mapping;
private IAnyInspector inspector;
[SetUp]
public void CreateDsl()
{
mapping = new AnyMapping();
inspector = new AnyInspector(mapping);
}
[Test]
public void AccessMapped()
{
mapping.Access = "field";
inspector.Access.ShouldEqual(Access.Field);
}
[Test]
public void AccessIsSet()
{
mapping.Access = "field";
inspector.IsSet(Prop(x => x.Access))
.ShouldBeTrue();
}
[Test]
public void AccessIsNotSet()
{
inspector.IsSet(Prop(x => x.Access))
.ShouldBeFalse();
}
[Test]
public void CascadeMapped()
{
mapping.Cascade = "all";
inspector.Cascade.ShouldEqual(Cascade.All);
}
[Test]
public void CascadeIsSet()
{
mapping.Cascade = "all";
inspector.IsSet(Prop(x => x.Cascade))
.ShouldBeTrue();
}
[Test]
public void CascadeIsNotSet()
{
inspector.IsSet(Prop(x => x.Cascade))
.ShouldBeFalse();
}
[Test]
public void IdentifierColumnsCollectionHasSameCountAsMapping()
{
mapping.AddIdentifierColumn(new ColumnMapping());
inspector.IdentifierColumns.Count().ShouldEqual(1);
}
[Test]
public void IdentifierColumnsCollectionOfInspectors()
{
mapping.AddIdentifierColumn(new ColumnMapping());
inspector.IdentifierColumns.First().ShouldBeOfType<IColumnInspector>();
}
[Test]
public void IdentifierColumnsCollectionIsEmpty()
{
inspector.IdentifierColumns.IsEmpty().ShouldBeTrue();
}
[Test]
public void IdTypeMapped()
{
mapping.IdType = "type";
inspector.IdType.ShouldEqual("type");
}
[Test]
public void IdTypeIsSet()
{
mapping.IdType = "type";
inspector.IsSet(Prop(x => x.IdType))
.ShouldBeTrue();
}
[Test]
public void IdTypeIsNotSet()
{
inspector.IsSet(Prop(x => x.IdType))
.ShouldBeFalse();
}
[Test]
public void InsertMapped()
{
mapping.Insert = true;
inspector.Insert.ShouldEqual(true);
}
[Test]
public void InsertIsSet()
{
mapping.Insert = true;
inspector.IsSet(Prop(x => x.Insert))
.ShouldBeTrue();
}
[Test]
public void InsertIsNotSet()
{
inspector.IsSet(Prop(x => x.Insert))
.ShouldBeFalse();
}
[Test]
public void LazyMapped()
{
mapping.Lazy = true;
inspector.LazyLoad.ShouldEqual(true);
}
[Test]
public void LazyIsSet()
{
mapping.Lazy = true;
inspector.IsSet(Prop(x => x.LazyLoad))
.ShouldBeTrue();
}
[Test]
public void LazyIsNotSet()
{
inspector.IsSet(Prop(x => x.LazyLoad))
.ShouldBeFalse();
}
[Test]
public void MetaTypeMapped()
{
mapping.MetaType = new TypeReference(typeof(string));
inspector.MetaType.ShouldEqual(new TypeReference(typeof(string)));
}
[Test]
public void MetaTypeIsSet()
{
mapping.MetaType = new TypeReference(typeof(string));
inspector.IsSet(Prop(x => x.MetaType))
.ShouldBeTrue();
}
[Test]
public void MetaTypeIsNotSet()
{
inspector.IsSet(Prop(x => x.MetaType))
.ShouldBeFalse();
}
[Test]
public void MetaValuesCollectionHasSameCountAsMapping()
{
mapping.AddMetaValue(new MetaValueMapping());
inspector.MetaValues.Count().ShouldEqual(1);
}
[Test]
public void MetaValuesCollectionOfInspectors()
{
mapping.AddMetaValue(new MetaValueMapping());
inspector.MetaValues.First().ShouldBeOfType<IMetaValueInspector>();
}
[Test]
public void MetaValuesCollectionIsEmpty()
{
inspector.MetaValues.IsEmpty().ShouldBeTrue();
}
[Test]
public void NameMapped()
{
mapping.Name = "name";
inspector.Name.ShouldEqual("name");
}
[Test]
public void NameIsSet()
{
mapping.Name = "name";
inspector.IsSet(Prop(x => x.Name))
.ShouldBeTrue();
}
[Test]
public void NameIsNotSet()
{
inspector.IsSet(Prop(x => x.Name))
.ShouldBeFalse();
}
[Test]
public void OptimisticLockMapped()
{
mapping.OptimisticLock = true;
inspector.OptimisticLock.ShouldEqual(true);
}
[Test]
public void OptimisticLockIsSet()
{
mapping.OptimisticLock = true;
inspector.IsSet(Prop(x => x.OptimisticLock))
.ShouldBeTrue();
}
[Test]
public void OptimisticLockIsNotSet()
{
inspector.IsSet(Prop(x => x.OptimisticLock))
.ShouldBeFalse();
}
[Test]
public void TypeColumnsCollectionHasSameCountAsMapping()
{
mapping.AddTypeColumn(new ColumnMapping());
inspector.TypeColumns.Count().ShouldEqual(1);
}
[Test]
public void TypeColumnsCollectionOfInspectors()
{
mapping.AddTypeColumn(new ColumnMapping());
inspector.TypeColumns.First().ShouldBeOfType<IColumnInspector>();
}
[Test]
public void TypeColumnsCollectionIsEmpty()
{
inspector.TypeColumns.IsEmpty().ShouldBeTrue();
}
[Test]
public void UpdateMapped()
{
mapping.Update = true;
inspector.Update.ShouldEqual(true);
}
[Test]
public void UpdateIsSet()
{
mapping.Update = true;
inspector.IsSet(Prop(x => x.Update))
.ShouldBeTrue();
}
[Test]
public void UpdateIsNotSet()
{
inspector.IsSet(Prop(x => x.Update))
.ShouldBeFalse();
}
#region Helpers
private PropertyInfo Prop(Expression<Func<IAnyInspector, object>> propertyExpression)
{
return ReflectionHelper.GetProperty(propertyExpression);
}
#endregion
}
}
| |
// Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
using gax = Google.Api.Gax;
using gcsv = Google.Cloud.SecurityCenter.V1P1Beta1;
using sys = System;
namespace Google.Cloud.SecurityCenter.V1P1Beta1
{
/// <summary>Resource name for the <c>OrganizationSettings</c> resource.</summary>
public sealed partial class OrganizationSettingsName : gax::IResourceName, sys::IEquatable<OrganizationSettingsName>
{
/// <summary>The possible contents of <see cref="OrganizationSettingsName"/>.</summary>
public enum ResourceNameType
{
/// <summary>An unparsed resource name.</summary>
Unparsed = 0,
/// <summary>
/// A resource name with pattern <c>organizations/{organization}/organizationSettings</c>.
/// </summary>
Organization = 1,
}
private static gax::PathTemplate s_organization = new gax::PathTemplate("organizations/{organization}/organizationSettings");
/// <summary>Creates a <see cref="OrganizationSettingsName"/> containing an unparsed resource name.</summary>
/// <param name="unparsedResourceName">The unparsed resource name. Must not be <c>null</c>.</param>
/// <returns>
/// A new instance of <see cref="OrganizationSettingsName"/> containing the provided
/// <paramref name="unparsedResourceName"/>.
/// </returns>
public static OrganizationSettingsName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) =>
new OrganizationSettingsName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName)));
/// <summary>
/// Creates a <see cref="OrganizationSettingsName"/> with the pattern
/// <c>organizations/{organization}/organizationSettings</c>.
/// </summary>
/// <param name="organizationId">The <c>Organization</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// A new instance of <see cref="OrganizationSettingsName"/> constructed from the provided ids.
/// </returns>
public static OrganizationSettingsName FromOrganization(string organizationId) =>
new OrganizationSettingsName(ResourceNameType.Organization, organizationId: gax::GaxPreconditions.CheckNotNullOrEmpty(organizationId, nameof(organizationId)));
/// <summary>
/// Formats the IDs into the string representation of this <see cref="OrganizationSettingsName"/> with pattern
/// <c>organizations/{organization}/organizationSettings</c>.
/// </summary>
/// <param name="organizationId">The <c>Organization</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="OrganizationSettingsName"/> with pattern
/// <c>organizations/{organization}/organizationSettings</c>.
/// </returns>
public static string Format(string organizationId) => FormatOrganization(organizationId);
/// <summary>
/// Formats the IDs into the string representation of this <see cref="OrganizationSettingsName"/> with pattern
/// <c>organizations/{organization}/organizationSettings</c>.
/// </summary>
/// <param name="organizationId">The <c>Organization</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="OrganizationSettingsName"/> with pattern
/// <c>organizations/{organization}/organizationSettings</c>.
/// </returns>
public static string FormatOrganization(string organizationId) =>
s_organization.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(organizationId, nameof(organizationId)));
/// <summary>
/// Parses the given resource name string into a new <see cref="OrganizationSettingsName"/> instance.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item><description><c>organizations/{organization}/organizationSettings</c></description></item>
/// </list>
/// </remarks>
/// <param name="organizationSettingsName">The resource name in string form. Must not be <c>null</c>.</param>
/// <returns>The parsed <see cref="OrganizationSettingsName"/> if successful.</returns>
public static OrganizationSettingsName Parse(string organizationSettingsName) =>
Parse(organizationSettingsName, false);
/// <summary>
/// Parses the given resource name string into a new <see cref="OrganizationSettingsName"/> instance; optionally
/// allowing an unparseable resource name.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item><description><c>organizations/{organization}/organizationSettings</c></description></item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="organizationSettingsName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="allowUnparsed">
/// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/>
/// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is
/// specified.
/// </param>
/// <returns>The parsed <see cref="OrganizationSettingsName"/> if successful.</returns>
public static OrganizationSettingsName Parse(string organizationSettingsName, bool allowUnparsed) =>
TryParse(organizationSettingsName, allowUnparsed, out OrganizationSettingsName result) ? result : throw new sys::ArgumentException("The given resource-name matches no pattern.");
/// <summary>
/// Tries to parse the given resource name string into a new <see cref="OrganizationSettingsName"/> instance.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item><description><c>organizations/{organization}/organizationSettings</c></description></item>
/// </list>
/// </remarks>
/// <param name="organizationSettingsName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="result">
/// When this method returns, the parsed <see cref="OrganizationSettingsName"/>, or <c>null</c> if parsing
/// failed.
/// </param>
/// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns>
public static bool TryParse(string organizationSettingsName, out OrganizationSettingsName result) =>
TryParse(organizationSettingsName, false, out result);
/// <summary>
/// Tries to parse the given resource name string into a new <see cref="OrganizationSettingsName"/> instance;
/// optionally allowing an unparseable resource name.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item><description><c>organizations/{organization}/organizationSettings</c></description></item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="organizationSettingsName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="allowUnparsed">
/// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/>
/// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is
/// specified.
/// </param>
/// <param name="result">
/// When this method returns, the parsed <see cref="OrganizationSettingsName"/>, or <c>null</c> if parsing
/// failed.
/// </param>
/// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns>
public static bool TryParse(string organizationSettingsName, bool allowUnparsed, out OrganizationSettingsName result)
{
gax::GaxPreconditions.CheckNotNull(organizationSettingsName, nameof(organizationSettingsName));
gax::TemplatedResourceName resourceName;
if (s_organization.TryParseName(organizationSettingsName, out resourceName))
{
result = FromOrganization(resourceName[0]);
return true;
}
if (allowUnparsed)
{
if (gax::UnparsedResourceName.TryParse(organizationSettingsName, out gax::UnparsedResourceName unparsedResourceName))
{
result = FromUnparsed(unparsedResourceName);
return true;
}
}
result = null;
return false;
}
private OrganizationSettingsName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string organizationId = null)
{
Type = type;
UnparsedResource = unparsedResourceName;
OrganizationId = organizationId;
}
/// <summary>
/// Constructs a new instance of a <see cref="OrganizationSettingsName"/> class from the component parts of
/// pattern <c>organizations/{organization}/organizationSettings</c>
/// </summary>
/// <param name="organizationId">The <c>Organization</c> ID. Must not be <c>null</c> or empty.</param>
public OrganizationSettingsName(string organizationId) : this(ResourceNameType.Organization, organizationId: gax::GaxPreconditions.CheckNotNullOrEmpty(organizationId, nameof(organizationId)))
{
}
/// <summary>The <see cref="ResourceNameType"/> of the contained resource name.</summary>
public ResourceNameType Type { get; }
/// <summary>
/// The contained <see cref="gax::UnparsedResourceName"/>. Only non-<c>null</c> if this instance contains an
/// unparsed resource name.
/// </summary>
public gax::UnparsedResourceName UnparsedResource { get; }
/// <summary>
/// The <c>Organization</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource
/// name.
/// </summary>
public string OrganizationId { get; }
/// <summary>Whether this instance contains a resource name with a known pattern.</summary>
public bool IsKnownPattern => Type != ResourceNameType.Unparsed;
/// <summary>The string representation of the resource name.</summary>
/// <returns>The string representation of the resource name.</returns>
public override string ToString()
{
switch (Type)
{
case ResourceNameType.Unparsed: return UnparsedResource.ToString();
case ResourceNameType.Organization: return s_organization.Expand(OrganizationId);
default: throw new sys::InvalidOperationException("Unrecognized resource-type.");
}
}
/// <summary>Returns a hash code for this resource name.</summary>
public override int GetHashCode() => ToString().GetHashCode();
/// <inheritdoc/>
public override bool Equals(object obj) => Equals(obj as OrganizationSettingsName);
/// <inheritdoc/>
public bool Equals(OrganizationSettingsName other) => ToString() == other?.ToString();
/// <inheritdoc/>
public static bool operator ==(OrganizationSettingsName a, OrganizationSettingsName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false);
/// <inheritdoc/>
public static bool operator !=(OrganizationSettingsName a, OrganizationSettingsName b) => !(a == b);
}
public partial class OrganizationSettings
{
/// <summary>
/// <see cref="gcsv::OrganizationSettingsName"/>-typed view over the <see cref="Name"/> resource name property.
/// </summary>
public gcsv::OrganizationSettingsName OrganizationSettingsName
{
get => string.IsNullOrEmpty(Name) ? null : gcsv::OrganizationSettingsName.Parse(Name, allowUnparsed: true);
set => Name = value?.ToString() ?? "";
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Formatting;
using System.Net.Http.Headers;
using System.Web.Http.Description;
using System.Xml.Linq;
using Newtonsoft.Json;
namespace Chat.Areas.HelpPage
{
/// <summary>
/// This class will generate the samples for the help page.
/// </summary>
public class HelpPageSampleGenerator
{
/// <summary>
/// Initializes a new instance of the <see cref="HelpPageSampleGenerator"/> class.
/// </summary>
public HelpPageSampleGenerator()
{
ActualHttpMessageTypes = new Dictionary<HelpPageSampleKey, Type>();
ActionSamples = new Dictionary<HelpPageSampleKey, object>();
SampleObjects = new Dictionary<Type, object>();
SampleObjectFactories = new List<Func<HelpPageSampleGenerator, Type, object>>
{
DefaultSampleObjectFactory,
};
}
/// <summary>
/// Gets CLR types that are used as the content of <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/>.
/// </summary>
public IDictionary<HelpPageSampleKey, Type> ActualHttpMessageTypes { get; internal set; }
/// <summary>
/// Gets the objects that are used directly as samples for certain actions.
/// </summary>
public IDictionary<HelpPageSampleKey, object> ActionSamples { get; internal set; }
/// <summary>
/// Gets the objects that are serialized as samples by the supported formatters.
/// </summary>
public IDictionary<Type, object> SampleObjects { get; internal set; }
/// <summary>
/// Gets factories for the objects that the supported formatters will serialize as samples. Processed in order,
/// stopping when the factory successfully returns a non-<see langref="null"/> object.
/// </summary>
/// <remarks>
/// Collection includes just <see cref="ObjectGenerator.GenerateObject(Type)"/> initially. Use
/// <code>SampleObjectFactories.Insert(0, func)</code> to provide an override and
/// <code>SampleObjectFactories.Add(func)</code> to provide a fallback.</remarks>
[SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures",
Justification = "This is an appropriate nesting of generic types")]
public IList<Func<HelpPageSampleGenerator, Type, object>> SampleObjectFactories { get; private set; }
/// <summary>
/// Gets the request body samples for a given <see cref="ApiDescription"/>.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The samples keyed by media type.</returns>
public IDictionary<MediaTypeHeaderValue, object> GetSampleRequests(ApiDescription api)
{
return GetSample(api, SampleDirection.Request);
}
/// <summary>
/// Gets the response body samples for a given <see cref="ApiDescription"/>.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The samples keyed by media type.</returns>
public IDictionary<MediaTypeHeaderValue, object> GetSampleResponses(ApiDescription api)
{
return GetSample(api, SampleDirection.Response);
}
/// <summary>
/// Gets the request or response body samples.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param>
/// <returns>The samples keyed by media type.</returns>
public virtual IDictionary<MediaTypeHeaderValue, object> GetSample(ApiDescription api, SampleDirection sampleDirection)
{
if (api == null)
{
throw new ArgumentNullException("api");
}
string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName;
string actionName = api.ActionDescriptor.ActionName;
IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name);
Collection<MediaTypeFormatter> formatters;
Type type = ResolveType(api, controllerName, actionName, parameterNames, sampleDirection, out formatters);
var samples = new Dictionary<MediaTypeHeaderValue, object>();
// Use the samples provided directly for actions
var actionSamples = GetAllActionSamples(controllerName, actionName, parameterNames, sampleDirection);
foreach (var actionSample in actionSamples)
{
samples.Add(actionSample.Key.MediaType, WrapSampleIfString(actionSample.Value));
}
// Do the sample generation based on formatters only if an action doesn't return an HttpResponseMessage.
// Here we cannot rely on formatters because we don't know what's in the HttpResponseMessage, it might not even use formatters.
if (type != null && !typeof(HttpResponseMessage).IsAssignableFrom(type))
{
object sampleObject = GetSampleObject(type);
foreach (var formatter in formatters)
{
foreach (MediaTypeHeaderValue mediaType in formatter.SupportedMediaTypes)
{
if (!samples.ContainsKey(mediaType))
{
object sample = GetActionSample(controllerName, actionName, parameterNames, type, formatter, mediaType, sampleDirection);
// If no sample found, try generate sample using formatter and sample object
if (sample == null && sampleObject != null)
{
sample = WriteSampleObjectUsingFormatter(formatter, sampleObject, type, mediaType);
}
samples.Add(mediaType, WrapSampleIfString(sample));
}
}
}
}
return samples;
}
/// <summary>
/// Search for samples that are provided directly through <see cref="ActionSamples"/>.
/// </summary>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
/// <param name="type">The CLR type.</param>
/// <param name="formatter">The formatter.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param>
/// <returns>The sample that matches the parameters.</returns>
public virtual object GetActionSample(string controllerName, string actionName, IEnumerable<string> parameterNames, Type type, MediaTypeFormatter formatter, MediaTypeHeaderValue mediaType, SampleDirection sampleDirection)
{
object sample;
// First, try to get the sample provided for the specified mediaType, sampleDirection, controllerName, actionName and parameterNames.
// If not found, try to get the sample provided for the specified mediaType, sampleDirection, controllerName and actionName regardless of the parameterNames.
// If still not found, try to get the sample provided for the specified mediaType and type.
// Finally, try to get the sample provided for the specified mediaType.
if (ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, parameterNames), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, new[] { "*" }), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, type), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType), out sample))
{
return sample;
}
return null;
}
/// <summary>
/// Gets the sample object that will be serialized by the formatters.
/// First, it will look at the <see cref="SampleObjects"/>. If no sample object is found, it will try to create
/// one using <see cref="DefaultSampleObjectFactory"/> (which wraps an <see cref="ObjectGenerator"/>) and other
/// factories in <see cref="SampleObjectFactories"/>.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>The sample object.</returns>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes",
Justification = "Even if all items in SampleObjectFactories throw, problem will be visible as missing sample.")]
public virtual object GetSampleObject(Type type)
{
object sampleObject;
if (!SampleObjects.TryGetValue(type, out sampleObject))
{
// No specific object available, try our factories.
foreach (Func<HelpPageSampleGenerator, Type, object> factory in SampleObjectFactories)
{
if (factory == null)
{
continue;
}
try
{
sampleObject = factory(this, type);
if (sampleObject != null)
{
break;
}
}
catch
{
// Ignore any problems encountered in the factory; go on to the next one (if any).
}
}
}
return sampleObject;
}
/// <summary>
/// Resolves the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The type.</returns>
public virtual Type ResolveHttpRequestMessageType(ApiDescription api)
{
string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName;
string actionName = api.ActionDescriptor.ActionName;
IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name);
Collection<MediaTypeFormatter> formatters;
return ResolveType(api, controllerName, actionName, parameterNames, SampleDirection.Request, out formatters);
}
/// <summary>
/// Resolves the type of the action parameter or return value when <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/> is used.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or a response.</param>
/// <param name="formatters">The formatters.</param>
[SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", Justification = "This is only used in advanced scenarios.")]
public virtual Type ResolveType(ApiDescription api, string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection, out Collection<MediaTypeFormatter> formatters)
{
if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection))
{
throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection));
}
if (api == null)
{
throw new ArgumentNullException("api");
}
Type type;
if (ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, parameterNames), out type) ||
ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, new[] { "*" }), out type))
{
// Re-compute the supported formatters based on type
Collection<MediaTypeFormatter> newFormatters = new Collection<MediaTypeFormatter>();
foreach (var formatter in api.ActionDescriptor.Configuration.Formatters)
{
if (IsFormatSupported(sampleDirection, formatter, type))
{
newFormatters.Add(formatter);
}
}
formatters = newFormatters;
}
else
{
switch (sampleDirection)
{
case SampleDirection.Request:
ApiParameterDescription requestBodyParameter = api.ParameterDescriptions.FirstOrDefault(p => p.Source == ApiParameterSource.FromBody);
type = requestBodyParameter == null ? null : requestBodyParameter.ParameterDescriptor.ParameterType;
formatters = api.SupportedRequestBodyFormatters;
break;
case SampleDirection.Response:
default:
type = api.ResponseDescription.ResponseType ?? api.ResponseDescription.DeclaredType;
formatters = api.SupportedResponseFormatters;
break;
}
}
return type;
}
/// <summary>
/// Writes the sample object using formatter.
/// </summary>
/// <param name="formatter">The formatter.</param>
/// <param name="value">The value.</param>
/// <param name="type">The type.</param>
/// <param name="mediaType">Type of the media.</param>
/// <returns></returns>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as InvalidSample.")]
public virtual object WriteSampleObjectUsingFormatter(MediaTypeFormatter formatter, object value, Type type, MediaTypeHeaderValue mediaType)
{
if (formatter == null)
{
throw new ArgumentNullException("formatter");
}
if (mediaType == null)
{
throw new ArgumentNullException("mediaType");
}
object sample = String.Empty;
MemoryStream ms = null;
HttpContent content = null;
try
{
if (formatter.CanWriteType(type))
{
ms = new MemoryStream();
content = new ObjectContent(type, value, formatter, mediaType);
formatter.WriteToStreamAsync(type, value, ms, content, null).Wait();
ms.Position = 0;
StreamReader reader = new StreamReader(ms);
string serializedSampleString = reader.ReadToEnd();
if (mediaType.MediaType.ToUpperInvariant().Contains("XML"))
{
serializedSampleString = TryFormatXml(serializedSampleString);
}
else if (mediaType.MediaType.ToUpperInvariant().Contains("JSON"))
{
serializedSampleString = TryFormatJson(serializedSampleString);
}
sample = new TextSample(serializedSampleString);
}
else
{
sample = new InvalidSample(String.Format(
CultureInfo.CurrentCulture,
"Failed to generate the sample for media type '{0}'. Cannot use formatter '{1}' to write type '{2}'.",
mediaType,
formatter.GetType().Name,
type.Name));
}
}
catch (Exception e)
{
sample = new InvalidSample(String.Format(
CultureInfo.CurrentCulture,
"An exception has occurred while using the formatter '{0}' to generate sample for media type '{1}'. Exception message: {2}",
formatter.GetType().Name,
mediaType.MediaType,
UnwrapException(e).Message));
}
finally
{
if (ms != null)
{
ms.Dispose();
}
if (content != null)
{
content.Dispose();
}
}
return sample;
}
internal static Exception UnwrapException(Exception exception)
{
AggregateException aggregateException = exception as AggregateException;
if (aggregateException != null)
{
return aggregateException.Flatten().InnerException;
}
return exception;
}
// Default factory for sample objects
private static object DefaultSampleObjectFactory(HelpPageSampleGenerator sampleGenerator, Type type)
{
// Try to create a default sample object
ObjectGenerator objectGenerator = new ObjectGenerator();
return objectGenerator.GenerateObject(type);
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")]
private static string TryFormatJson(string str)
{
try
{
object parsedJson = JsonConvert.DeserializeObject(str);
return JsonConvert.SerializeObject(parsedJson, Formatting.Indented);
}
catch
{
// can't parse JSON, return the original string
return str;
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")]
private static string TryFormatXml(string str)
{
try
{
XDocument xml = XDocument.Parse(str);
return xml.ToString();
}
catch
{
// can't parse XML, return the original string
return str;
}
}
private static bool IsFormatSupported(SampleDirection sampleDirection, MediaTypeFormatter formatter, Type type)
{
switch (sampleDirection)
{
case SampleDirection.Request:
return formatter.CanReadType(type);
case SampleDirection.Response:
return formatter.CanWriteType(type);
}
return false;
}
private IEnumerable<KeyValuePair<HelpPageSampleKey, object>> GetAllActionSamples(string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection)
{
HashSet<string> parameterNamesSet = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase);
foreach (var sample in ActionSamples)
{
HelpPageSampleKey sampleKey = sample.Key;
if (String.Equals(controllerName, sampleKey.ControllerName, StringComparison.OrdinalIgnoreCase) &&
String.Equals(actionName, sampleKey.ActionName, StringComparison.OrdinalIgnoreCase) &&
(sampleKey.ParameterNames.SetEquals(new[] { "*" }) || parameterNamesSet.SetEquals(sampleKey.ParameterNames)) &&
sampleDirection == sampleKey.SampleDirection)
{
yield return sample;
}
}
}
private static object WrapSampleIfString(object sample)
{
string stringSample = sample as string;
if (stringSample != null)
{
return new TextSample(stringSample);
}
return sample;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the Apache 2.0 License.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Threading;
using Microsoft.Scripting;
using Microsoft.Scripting.Runtime;
using Microsoft.Scripting.Utils;
using IronPython.Compiler;
using IronPython.Runtime.Exceptions;
using IronPython.Runtime.Operations;
namespace IronPython.Runtime {
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix"), PythonType("generator")]
[DontMapIDisposableToContextManager, DontMapIEnumerableToContains]
public sealed class PythonGenerator : IEnumerator, IEnumerator<object>, ICodeFormattable, IEnumerable, IWeakReferenceable {
private readonly Func<MutableTuple, object>/*!*/ _next; // The delegate which contains the user code to perform the iteration.
private readonly PythonFunction _function; // the function which created the generator
private readonly MutableTuple _data; // the closure data we need to pass into each iteration. Item000 is the index, Item001 is the current value
private readonly MutableTuple<int, object> _dataTuple; // the tuple which has our current index and value
private GeneratorFlags _flags; // Flags capturing various state for the generator
/// <summary>
/// True iff the thread is currently inside the generator (ie, invoking the _next delegate).
/// This can be used to enforce that a generator does not call back into itself.
/// Pep255 says that a generator should throw a ValueError if called reentrantly.
/// </summary>
private bool _active;
private GeneratorFinalizer _finalizer; // finalizer object
/// <summary>
/// We cache the GeneratorFinalizer of generators that were closed on the user
/// thread, and did not get finalized on the finalizer thread. We can then reuse
/// the object. Reusing objects with a finalizer is good because it reduces
/// the load on the GC's finalizer queue.
/// </summary>
private static GeneratorFinalizer _LastFinalizer;
/// <summary>
/// Fields set by Throw() to communicate an exception to the yield point.
/// These are plumbed through the generator to become parameters to Raise(...) invoked
/// at the yield suspension point in the generator.
/// </summary>
private object[] _excInfo;
/// <summary>
/// Value sent by generator.send().
/// Since send() could send an exception, we need to keep this different from throwable's value.
/// </summary>
private object _sendValue;
private WeakRefTracker _tracker;
internal PythonGenerator(PythonFunction function, Func<MutableTuple, object>/*!*/ next, MutableTuple data) {
_function = function;
_next = next;
_data = data;
_dataTuple = GetDataTuple();
State = GeneratorRewriter.NotStarted;
if (_LastFinalizer == null || (_finalizer = Interlocked.Exchange(ref _LastFinalizer, null)) == null) {
_finalizer = new GeneratorFinalizer(this);
} else {
_finalizer.Generator = this;
}
}
#region Python Public APIs
[LightThrowing]
public object next() {
// Python's language policy on generators is that attempting to access after it's closed (returned)
// just continues to throw StopIteration exceptions.
if (Closed) {
return LightExceptions.Throw(PythonOps.StopIteration());
}
object res = NextWorker();
if (res == OperationFailed.Value) {
return LightExceptions.Throw(PythonOps.StopIteration());
}
return res;
}
/// <summary>
/// See PEP 342 (http://python.org/dev/peps/pep-0342/) for details of new methods on Generator.
/// Full signature including default params for throw is:
/// throw(type, value=None, traceback=None)
/// Use multiple overloads to resolve the default parameters.
/// </summary>
[LightThrowing]
public object @throw(object type) {
return @throw(type, null, null, false);
}
[LightThrowing]
public object @throw(object type, object value) {
return @throw(type, value, null, false);
}
[LightThrowing]
public object @throw(object type, object value, object traceback) {
return @throw(type, value, traceback, false);
}
/// <summary>
/// Throw(...) is like Raise(...) being called from the yield point within the generator.
/// Note it must come from inside the generator so that the traceback matches, and so that it can
/// properly cooperate with any try/catch/finallys inside the generator body.
///
/// If the generator catches the exception and yields another value, that is the return value of g.throw().
/// </summary>
[LightThrowing]
private object @throw(object type, object value, object traceback, bool finalizing) {
// The Pep342 explicitly says "The type argument must not be None".
// According to CPython 2.5's implementation, a null type argument should:
// - throw a TypeError exception (just as Raise(None) would) *outside* of the generator's body
// (so the generator can't catch it).
// - not update any other generator state (so future calls to Next() will still work)
if (type == null) {
// Create the appropriate exception and throw it.
throw PythonOps.MakeExceptionTypeError(null, true);
}
// Set fields which will then be used by CheckThrowable.
// We create the actual exception from inside the generator so that if the exception's __init__
// throws, the traceback matches that which we get from CPython2.5.
_excInfo = new object[] { type, value, traceback };
Debug.Assert(_sendValue == null);
// Pep explicitly says that Throw on a closed generator throws the exception,
// and not a StopIteration exception. (This is different than Next()).
if (Closed) {
// this will throw the exception that we just set the fields for.
var throwable = CheckThrowable();
if (throwable != null) {
return throwable;
}
}
if (finalizing) {
// we are running on the finalizer thread - things can be already collected
return LightExceptions.Throw(PythonOps.StopIteration());
}
if (!((IEnumerator)this).MoveNext()) {
return LightExceptions.Throw(PythonOps.StopIteration());
}
return CurrentValue;
}
/// <summary>
/// send() was added in Pep342. It sends a result back into the generator, and the expression becomes
/// the result of yield when used as an expression.
/// </summary>
[LightThrowing]
public object send(object value) {
Debug.Assert(_excInfo == null);
// CPython2.5's behavior is that Send(non-null) on unstarted generator should:
// - throw a TypeError exception
// - not change generator state. So leave as unstarted, and allow future calls to succeed.
if (value != null && State == GeneratorRewriter.NotStarted) {
throw PythonOps.TypeErrorForIllegalSend();
}
_sendValue = value;
return next();
}
[LightThrowing]
public object close() {
return close(false);
}
/// <summary>
/// Close introduced in Pep 342.
/// </summary>
[LightThrowing]
private object close(bool finalizing) {
// This is nop if the generator is already closed.
// Optimization to avoid throwing + catching an exception if we're already closed.
if (Closed) {
return null;
}
// This function body is the psuedo code straight from Pep 342.
try {
object res = @throw(new GeneratorExitException(), null, null, finalizing);
Exception lightEh = LightExceptions.GetLightException(res);
if (lightEh != null) {
if (lightEh is StopIterationException || lightEh is GeneratorExitException) {
return null;
}
return lightEh;
}
// Generator should not have exited normally.
return LightExceptions.Throw(new RuntimeException("generator ignored GeneratorExit"));
} catch (StopIterationException) {
// Ignore, clear any stack frames we built up
} catch (GeneratorExitException) {
// Ignore, clear any stack frames we built up
}
return null;
}
public FunctionCode gi_code {
get {
return _function.func_code;
}
}
public int gi_running {
get {
if (Active) {
return 1;
}
return 0;
}
}
public TraceBackFrame gi_frame {
get {
return new TraceBackFrame(_function.Context, _function.Context.GlobalDict, new PythonDictionary(), gi_code);
}
}
/// <summary>
/// Gets the name of the function that produced this generator object.
/// </summary>
public string __name__ {
get {
return _function.__name__;
}
}
#endregion
#region Internal implementation details
private int State {
get {
return _dataTuple.Item000;
}
set {
_dataTuple.Item000 = value;
}
}
private object CurrentValue {
get {
return _dataTuple.Item001;
}
set {
_dataTuple.Item001 = value;
}
}
private MutableTuple<int, object> GetDataTuple() {
if (!(_data is MutableTuple<int, object> res)) {
res = GetBigData(_data);
}
return res;
}
private static MutableTuple<int, object> GetBigData(MutableTuple data) {
MutableTuple<int, object> smallGen;
do {
data = (MutableTuple)data.GetValue(0);
} while ((smallGen = (data as MutableTuple<int, object>)) == null);
return smallGen;
}
internal CodeContext Context {
get {
return _function.Context;
}
}
internal PythonFunction Function {
get {
return _function;
}
}
// Pep 342 says generators now have finalizers (__del__) that call Close()
private void Finalizer() {
// if there are no except or finally blocks then closing the
// generator has no effect.
if (CanSetSysExcInfo || ContainsTryFinally) {
try {
// This may run the users generator.
object res = close(true);
Exception ex = LightExceptions.GetLightException(res);
if (ex != null) {
HandleFinalizerException(ex);
}
} catch (Exception e) {
HandleFinalizerException(e);
}
}
}
private void HandleFinalizerException(Exception e) {
// An unhandled exceptions on the finalizer could tear down the process, so catch it.
// PEP says:
// If close() raises an exception, a traceback for the exception is printed to sys.stderr
// and further ignored; it is not propagated back to the place that
// triggered the garbage collection.
// Sample error message from CPython 2.5 looks like:
// Exception __main__.MyError: MyError() in <generator object at 0x00D7F6E8> ignored
try {
string message = "Exception in generator " + __repr__(Context) + " ignored";
PythonOps.PrintWithDest(Context, Context.LanguageContext.SystemStandardError, message);
PythonOps.PrintWithDest(Context, Context.LanguageContext.SystemStandardError, Context.LanguageContext.FormatException(e));
} catch {
// if stderr is closed then ignore any exceptions.
}
}
bool IEnumerator.MoveNext() {
if (Closed) {
// avoid exception
return false;
}
CheckSetActive();
if (!CanSetSysExcInfo) {
return MoveNextWorker();
} else {
Exception save = SaveCurrentException();
try {
return MoveNextWorker();
} finally {
RestoreCurrentException(save);
}
}
}
private FunctionStack? fnStack = null;
private void SaveFunctionStack(bool done) {
if (!Context.LanguageContext.PythonOptions.Frames || Context.LanguageContext.EnableTracing) return;
if (!done) {
var stack = PythonOps.GetFunctionStack();
var functionStack = stack[stack.Count - 1];
Debug.Assert(functionStack.Context != null);
functionStack.Frame = null; // don't keep the frame since f_back may be invalid
stack.RemoveAt(stack.Count - 1);
fnStack = functionStack;
}
else {
fnStack = null;
}
}
private void RestoreFunctionStack() {
if (!Context.LanguageContext.PythonOptions.Frames) return;
if (fnStack != null) {
List<FunctionStack> stack = PythonOps.GetFunctionStack();
stack.Add(fnStack.Value);
}
}
/// <summary>
/// Core implementation of IEnumerator.MoveNext()
/// </summary>
private bool MoveNextWorker() {
bool ret = false;
try {
RestoreFunctionStack();
try {
ret = GetNext();
} finally {
Active = false;
SaveFunctionStack(!ret);
if (!ret) {
Close();
}
}
} catch (StopIterationException) {
return false;
}
return ret;
}
/// <summary>
/// Core implementation of Python's next() method.
/// </summary>
private object NextWorker() {
// Generators can not be called re-entrantly.
CheckSetActive();
// We need to save/restore the exception info if the generator
// includes exception handling blocks.
Exception save = SaveCurrentException();
RestoreFunctionStack();
bool ret = false;
try {
// This calls into the delegate that has the real body of the generator.
// The generator body here may:
// 1. return an item: _next() returns true and 'next' is set to the next item in the enumeration.
// 2. Exit normally: _next returns false.
// 3. Exit with a StopIteration exception: for-loops and other enumeration consumers will
// catch this and terminate the loop without propogating the exception.
// 4. Exit via some other unhandled exception: This will close the generator, but the exception still propagates.
// _next does not return, so ret is left assigned to false (closed), which we detect in the finally.
if (!(ret = GetNext())) {
CurrentValue = OperationFailed.Value;
}
} finally {
// A generator restores the sys.exc_info() status after each yield point.
RestoreCurrentException(save);
Active = false;
SaveFunctionStack(!ret);
// If _next() returned false, or did not return (thus leavintg ret assigned to its initial value of false), then
// the body of the generator has exited and the generator is now closed.
if (!ret) {
Close();
}
}
return CurrentValue;
}
private void RestoreCurrentException(Exception save) {
if (CanSetSysExcInfo) {
PythonOps.RestoreCurrentException(save);
}
}
private Exception SaveCurrentException() {
if (CanSetSysExcInfo) {
return PythonOps.SaveCurrentException();
}
return null;
}
private void CheckSetActive() {
if (Active) {
// A generator could catch this exception and continue executing, so this does
// not necessarily close the generator.
AlreadyExecuting();
}
Active = true;
}
private static void AlreadyExecuting() {
throw PythonOps.ValueError("generator already executing");
}
/// <summary>
/// Helper called from PythonOps after the yield statement
/// Keepin this in a helper method:
/// - reduces generated code size
/// - allows better coupling with PythonGenerator.Throw()
/// - avoids throws from emitted code (which can be harder to debug).
/// </summary>
/// <returns></returns>
[LightThrowing]
internal object CheckThrowableAndReturnSendValue() {
// Since this method is called from the generator body's execution, the generator must be running
// and not closed.
Debug.Assert(!Closed);
if (_sendValue != null) {
// Can't Send() and Throw() at the same time.
Debug.Assert(_excInfo == null);
return SwapValues();
}
return CheckThrowable();
}
private object SwapValues() {
object sendValueBackup = _sendValue;
_sendValue = null;
return sendValueBackup;
}
/// <summary>
/// Called to throw an exception set by Throw().
/// </summary>
[LightThrowing]
private object CheckThrowable() {
if (_excInfo != null) {
return ThrowThrowable();
}
return null;
}
[LightThrowing]
private object ThrowThrowable() {
object[] throwableBackup = _excInfo;
// Clear it so that any future Next()/MoveNext() call doesn't pick up the exception again.
_excInfo = null;
// This may invoke user code such as __init__, thus MakeException may throw.
// Since this is invoked from the generator's body, the generator can catch this exception.
return LightExceptions.Throw(PythonOps.MakeExceptionForGenerator(Context, throwableBackup[0], throwableBackup[1], throwableBackup[2]));
}
private void Close() {
Closed = true;
// if we're closed the finalizer won't do anything, so suppress it.
SuppressFinalize();
}
private void SuppressFinalize() {
if (_finalizer != null) {
_finalizer.Generator = null;
_LastFinalizer = _finalizer;
} else {
// We must be on the finalizer thread, and being called from _finalizer.Finalize()
Debug.Assert(Thread.CurrentThread.Name == null);
}
}
private bool Closed {
get {
return (_flags & GeneratorFlags.Closed) != 0;
}
set {
if (value) _flags |= GeneratorFlags.Closed;
else _flags &= ~GeneratorFlags.Closed;
}
}
private bool Active {
get {
return _active;
}
set {
_active = value;
}
}
private bool GetNext() {
_next(_data);
return State != GeneratorRewriter.Finished;
}
internal bool CanSetSysExcInfo {
get {
return (_function.Flags & FunctionAttributes.CanSetSysExcInfo) != 0;
}
}
internal bool ContainsTryFinally {
get {
return (_function.Flags & FunctionAttributes.ContainsTryFinally) != 0;
}
}
#endregion
#region ICodeFormattable Members
public string __repr__(CodeContext context) {
return string.Format("<generator object at {0}>", PythonOps.HexId(this));
}
#endregion
[Flags]
private enum GeneratorFlags {
None,
/// <summary>
/// True if the generator has finished (is "closed"), else false.
/// Python language spec mandates that calling Next on a closed generator gracefully throws a StopIterationException.
/// This can never be reset.
/// </summary>
Closed = 0x01,
/// <summary>
/// True if the generator can set sys exc info and therefore needs exception save/restore.
/// </summary>
CanSetSysExcInfo = 0x04
}
#region IEnumerator Members
object IEnumerator.Current {
get { return CurrentValue; }
}
void IEnumerator.Reset() {
throw new NotImplementedException();
}
#endregion
#region IEnumerator<object> Members
object IEnumerator<object>.Current {
get { return CurrentValue; }
}
#endregion
#region IDisposable Members
void IDisposable.Dispose() {
// nothing needed to dispose
SuppressFinalize();
}
#endregion
class GeneratorFinalizer {
public PythonGenerator Generator;
public GeneratorFinalizer(PythonGenerator generator) {
Generator = generator;
}
~GeneratorFinalizer() {
var gen = Generator;
if (gen != null) {
Debug.Assert(gen._finalizer == this);
// We set this to null to indicate that the GeneratorFinalizer has been finalized,
// and should not be reused (ie saved in PythonGenerator._LastFinalizer)
gen._finalizer = null;
gen.Finalizer();
}
}
}
#region IEnumerable Members
IEnumerator IEnumerable.GetEnumerator() {
// only present for better C# interop
return this;
}
#endregion
#region IWeakReferenceable Members
WeakRefTracker IWeakReferenceable.GetWeakRef() {
return _tracker;
}
bool IWeakReferenceable.SetWeakRef(WeakRefTracker value) {
_tracker = value;
return true;
}
void IWeakReferenceable.SetFinalizer(WeakRefTracker value) {
_tracker = value;
}
#endregion
}
}
| |
//
// System.Decimal.cs
//
// Represents a floating-point decimal data type with up to 29
// significant digits, suitable for financial and commercial calculations.
//
// Author:
// Martin Weindel ([email protected])
//
// (C) 2001 Martin Weindel
//
//
// Copyright (C) 2004 Novell, Inc (http://www.novell.com)
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.Globalization;
using System.Text;
using System.Runtime.CompilerServices;
using System.Runtime.ConstrainedExecution;
using System.Runtime.Serialization;
using Dot42;
#if MSTEST
using System.Runtime.InteropServices;
#endif
namespace System
{
/// <summary>
/// Represents a floating-point decimal data type with up to 29 significant
/// digits, suitable for financial and commercial calculations
/// </summary>
[Serializable]
[System.Runtime.InteropServices.ComVisible (true)]
public struct Decimal: IFormattable, IConvertible, IComparable, IComparable<Decimal>, IEquatable <Decimal>
#if NET_4_0
, IDeserializationCallback
#endif
{
public const decimal MinValue = -79228162514264337593543950335m;
public const decimal MaxValue = 79228162514264337593543950335m;
public const decimal MinusOne = -1;
public const decimal One = 1;
public const decimal Zero = 0;
private static readonly Decimal MaxValueDiv10 = MaxValue / 10;
// some constants
private const uint MAX_SCALE = 28;
private const uint SIGN_FLAG = 0x80000000;
private const int SCALE_SHIFT = 16;
private const uint RESERVED_SS32_BITS = 0x7F00FFFF;
// internal representation of decimal
private uint flags;
private uint hi;
private uint lo;
private uint mid;
public Decimal (int lo, int mid, int hi, bool isNegative, byte scale)
{
unchecked
{
this.lo = (uint) lo;
this.mid = (uint) mid;
this.hi = (uint) hi;
if (scale > MAX_SCALE)
throw new ArgumentOutOfRangeException (Locale.GetText ("scale must be between 0 and 28"));
flags = scale;
flags <<= SCALE_SHIFT;
if (isNegative) flags |= SIGN_FLAG;
}
}
public Decimal (int value)
{
unchecked
{
hi = mid = 0;
if (value < 0)
{
flags = SIGN_FLAG;
lo = ((uint)~value) + 1;
}
else
{
flags = 0;
lo = (uint) value;
}
}
}
[CLSCompliant(false)]
public Decimal (uint value)
{
lo = value;
flags = hi = mid = 0;
}
public Decimal (long value)
{
unchecked
{
hi = 0;
if (value < 0)
{
flags = SIGN_FLAG;
ulong u = ((ulong)~value) + 1;
lo = (uint)u;
mid = (uint)(u >> 32);
}
else
{
flags = 0;
ulong u = (ulong)value;
lo = (uint)u;
mid = (uint)(u >> 32);
}
}
}
[CLSCompliant(false)]
public Decimal (ulong value)
{
unchecked
{
flags = hi = 0;
lo = (uint)value;
mid = (uint)(value >> 32);
}
}
public Decimal (float value)
{
#if false
//
// We cant use the double2decimal method
// because it incorrectly turns the floating point
// value 1.23456789E-25F which should be:
// 0.0000000000000000000000001235
// into the incorrect:
// 0.0000000000000000000000001234
//
// The code currently parses the double value 0.6 as
// 0.600000000000000
//
// And we have a patch for that called (trim
if (double2decimal (out this, value, 7) != 0)
throw new OverflowException ();
#else
if (value > (float)Decimal.MaxValue || value < (float)Decimal.MinValue ||
float.IsNaN (value) || float.IsNegativeInfinity (value) || float.IsPositiveInfinity (value)) {
throw new OverflowException (Locale.GetText (
"Value {0} is greater than Decimal.MaxValue or less than Decimal.MinValue", value));
}
// we must respect the precision (double2decimal doesn't)
Decimal d = Decimal.Parse (value.ToString (CultureInfo.InvariantCulture),
NumberStyles.Float, CultureInfo.InvariantCulture);
flags = d.flags;
hi = d.hi;
lo = d.lo;
mid = d.mid;
#endif
}
public Decimal (double value)
{
#if true
//
// We cant use the double2decimal method
// because it incorrectly turns the floating point
// value 1.23456789E-25F which should be:
// 0.0000000000000000000000001235
// into the incorrect:
// 0.0000000000000000000000001234
//
// The code currently parses the double value 0.6 as
// 0.600000000000000
//
// And we have a patch for that called (trim
if (double2decimal (out this, value, 15) != 0)
throw new OverflowException ();
#else
if (value > (double)Decimal.MaxValue || value < (double)Decimal.MinValue ||
double.IsNaN (value) || double.IsNegativeInfinity (value) || double.IsPositiveInfinity (value)) {
throw new OverflowException (Locale.GetText (
"Value {0} is greater than Decimal.MaxValue or less than Decimal.MinValue", value));
}
// we must respect the precision (double2decimal doesn't)
Decimal d = Decimal.Parse (value.ToString (CultureInfo.InvariantCulture),
NumberStyles.Float, CultureInfo.InvariantCulture);
flags = d.flags;
hi = d.hi;
lo = d.lo;
mid = d.mid;
#endif
}
public Decimal (int[] bits)
{
if (bits == null)
{
throw new ArgumentNullException (Locale.GetText ("bits is a null reference"));
}
if (bits.Length != 4)
{
throw new ArgumentException (Locale.GetText ("bits does not contain four values"));
}
unchecked {
lo = (uint) bits[0];
mid = (uint) bits[1];
hi = (uint) bits[2];
flags = (uint) bits[3];
byte scale = (byte)(flags >> SCALE_SHIFT);
if (scale > MAX_SCALE || (flags & RESERVED_SS32_BITS) != 0)
{
throw new ArgumentException (Locale.GetText ("Invalid bits[3]"));
}
}
}
public static decimal FromOACurrency (long cy)
{
return (decimal)cy / (decimal)10000;
}
public static int[] GetBits (Decimal d)
{
unchecked
{
return new int[] { (int)d.lo, (int)d.mid, (int)d.hi, (int)d.flags };
}
}
public static Decimal Negate (Decimal d)
{
d.flags ^= SIGN_FLAG;
return d;
}
public static Decimal Add (Decimal d1, Decimal d2)
{
if (decimalIncr (ref d1, ref d2) == 0)
return d1;
else
throw new OverflowException (Locale.GetText ("Overflow on adding decimal number"));
}
public static Decimal Subtract (Decimal d1, Decimal d2)
{
d2.flags ^= SIGN_FLAG;
int result = decimalIncr (ref d1, ref d2);
if (result == 0)
return d1;
else
throw new OverflowException (Locale.GetText ("Overflow on subtracting decimal numbers ("+result+")"));
}
public override int GetHashCode ()
{
return (int) (flags ^ hi ^ lo ^ mid);
}
public static Decimal operator + (Decimal d1, Decimal d2)
{
return Add (d1, d2);
}
public static Decimal operator -- (Decimal d)
{
return Add(d, MinusOne);
}
public static Decimal operator ++ (Decimal d)
{
return Add (d, One);
}
public static Decimal operator - (Decimal d1, Decimal d2)
{
return Subtract (d1, d2);
}
public static Decimal operator - (Decimal d)
{
return Negate (d);
}
public static Decimal operator + (Decimal d)
{
return d;
}
public static Decimal operator * (Decimal d1, Decimal d2)
{
return Multiply (d1, d2);
}
public static Decimal operator / (Decimal d1, Decimal d2)
{
return Divide (d1, d2);
}
public static Decimal operator % (Decimal d1, Decimal d2)
{
return Remainder (d1, d2);
}
private static ulong u64 (Decimal value)
{
ulong result;
decimalFloorAndTrunc (ref value, 0);
if (decimal2UInt64 (ref value, out result) != 0) {
throw new System.OverflowException ();
}
return result;
}
private static long s64 (Decimal value)
{
long result;
decimalFloorAndTrunc (ref value, 0);
if (decimal2Int64 (ref value, out result) != 0) {
throw new System.OverflowException ();
}
return result;
}
public static explicit operator byte (Decimal value)
{
ulong result = u64 (value);
return checked ((byte) result);
}
[CLSCompliant (false)]
public static explicit operator sbyte (Decimal value)
{
long result = s64 (value);
return checked ((sbyte) result);
}
public static explicit operator char (Decimal value)
{
ulong result = u64 (value);
return checked ((char) result);
}
public static explicit operator short (Decimal value)
{
long result = s64 (value);
return checked ((short) result);
}
[CLSCompliant (false)]
public static explicit operator ushort (Decimal value)
{
ulong result = u64 (value);
return checked ((ushort) result);
}
public static explicit operator int (Decimal value)
{
long result = s64 (value);
return checked ((int) result);
}
[CLSCompliant(false)]
public static explicit operator uint (Decimal value)
{
ulong result = u64 (value);
return checked ((uint) result);
}
public static explicit operator long (Decimal value)
{
return s64 (value);
}
[CLSCompliant(false)]
public static explicit operator ulong (Decimal value)
{
return u64 (value);
}
public static implicit operator Decimal (byte value)
{
return new Decimal (value);
}
[CLSCompliant(false)]
public static implicit operator Decimal (sbyte value)
{
return new Decimal (value);
}
public static implicit operator Decimal (short value)
{
return new Decimal (value);
}
[CLSCompliant(false)]
public static implicit operator Decimal (ushort value)
{
return new Decimal (value);
}
public static implicit operator Decimal (char value)
{
return new Decimal (value);
}
public static implicit operator Decimal (int value)
{
return new Decimal (value);
}
[CLSCompliant(false)]
public static implicit operator Decimal (uint value)
{
return new Decimal (value);
}
public static implicit operator Decimal (long value)
{
return new Decimal (value);
}
[CLSCompliant(false)]
public static implicit operator Decimal (ulong value)
{
return new Decimal (value);
}
public static explicit operator Decimal (float value)
{
return new Decimal (value);
}
public static explicit operator Decimal (double value)
{
return new Decimal (value);
}
public static explicit operator float (Decimal value)
{
return (float) (double) value;
}
public static explicit operator double (Decimal value)
{
return decimal2double (ref value);
}
public static bool operator != (Decimal d1, Decimal d2)
{
return !Equals (d1, d2);
}
public static bool operator == (Decimal d1, Decimal d2)
{
return Equals (d1, d2);
}
public static bool operator > (Decimal d1, Decimal d2)
{
return Compare (d1, d2) > 0;
}
public static bool operator >= (Decimal d1, Decimal d2)
{
return Compare (d1, d2) >= 0;
}
public static bool operator < (Decimal d1, Decimal d2)
{
return Compare (d1, d2) < 0;
}
public static bool operator <= (Decimal d1, Decimal d2)
{
return Compare (d1, d2) <= 0;
}
public static bool Equals (Decimal d1, Decimal d2)
{
return Compare (d1, d2) == 0;
}
public override bool Equals (object value)
{
if (!(value is Decimal))
return false;
return Equals ((Decimal) value, this);
}
// avoid unmanaged call
private bool IsZero ()
{
return ((hi == 0) && (lo == 0) && (mid == 0));
}
// avoid unmanaged call
private bool IsNegative ()
{
return ((flags & 0x80000000) == 0x80000000);
}
public static Decimal Floor (Decimal d)
{
decimalFloorAndTrunc (ref d, 1);
return d;
}
public static Decimal Truncate (Decimal d)
{
decimalFloorAndTrunc (ref d, 0);
return d;
}
public static Decimal Round (Decimal d, int decimals)
{
return Round (d, decimals, MidpointRounding.ToEven);
}
public static Decimal Round (Decimal d, int decimals, MidpointRounding mode)
{
if ((mode != MidpointRounding.ToEven) && (mode != MidpointRounding.AwayFromZero))
throw new ArgumentException ("The value '" + mode + "' is not valid for this usage of the type MidpointRounding.", "mode");
if (decimals < 0 || decimals > 28) {
throw new ArgumentOutOfRangeException ("decimals", "[0,28]");
}
bool negative = d.IsNegative ();
if (negative)
d.flags ^= SIGN_FLAG;
// Moved from Math.cs because it's easier to fix the "sign"
// issue here :( as the logic is OK only for positive numbers
decimal p = (decimal) Math.Pow (10, decimals);
decimal int_part = Decimal.Floor (d);
decimal dec_part = d - int_part;
dec_part *= 10000000000000000000000000000M;
dec_part = Decimal.Floor(dec_part);
dec_part /= (10000000000000000000000000000M / p);
dec_part = Math.Round (dec_part, mode);
dec_part /= p;
decimal result = int_part + dec_part;
// that fixes the precision/scale (which we must keep for output)
// (moved and adapted from System.Data.SqlTypes.SqlMoney)
long scaleDiff = decimals - ((result.flags & 0x7FFF0000) >> 16);
// integrify
if (scaleDiff > 0) {
// note: here we always work with positive numbers
while (scaleDiff > 0) {
if (result > MaxValueDiv10)
break;
result *= 10;
scaleDiff--;
}
}
else if (scaleDiff < 0) {
while (scaleDiff < 0) {
result /= 10;
scaleDiff++;
}
}
result.flags = (uint)((decimals - scaleDiff) << SCALE_SHIFT);
if (negative)
result.flags ^= SIGN_FLAG;
return result;
}
public static Decimal Round (Decimal d)
{
return Math.Round (d);
}
public static Decimal Round (Decimal d, MidpointRounding mode)
{
return Math.Round (d, mode);
}
public static Decimal Multiply (Decimal d1, Decimal d2)
{
if (d1.IsZero () || d2.IsZero ())
return Decimal.Zero;
if (decimalMult (ref d1, ref d2) != 0)
throw new OverflowException ();
return d1;
}
public static Decimal Divide (Decimal d1, Decimal d2)
{
if (d2.IsZero ())
throw new DivideByZeroException ();
if (d1.IsZero ())
return Decimal.Zero;
d1.flags ^= SIGN_FLAG;
d1.flags ^= SIGN_FLAG;
Decimal result;
if (decimalDiv (out result, ref d1, ref d2) != 0)
throw new OverflowException ();
return result;
}
public static Decimal Remainder (Decimal d1, Decimal d2)
{
if (d2.IsZero ())
throw new DivideByZeroException ();
if (d1.IsZero ())
return Decimal.Zero;
bool negative = d1.IsNegative ();
if (negative)
d1.flags ^= SIGN_FLAG;
if (d2.IsNegative ())
d2.flags ^= SIGN_FLAG;
Decimal result;
if (d1 == d2) {
return Decimal.Zero;
}
else if (d2 > d1) {
result = d1;
}
else {
if (decimalDiv (out result, ref d1, ref d2) != 0)
throw new OverflowException ();
result = Decimal.Truncate (result);
// FIXME: not really performant here
result = d1 - result * d2;
}
if (negative)
result.flags ^= SIGN_FLAG;
return result;
}
[ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.Success)]
public static int Compare (Decimal d1, Decimal d2)
{
return decimalCompare (ref d1, ref d2);
}
public int CompareTo (object value)
{
if (value == null)
return 1;
if (!(value is Decimal))
throw new ArgumentException (Locale.GetText ("Value is not a System.Decimal"));
return Compare (this, (Decimal)value);
}
public int CompareTo (Decimal value)
{
return Compare (this, value);
}
public bool Equals (Decimal value)
{
return Equals (value, this);
}
public static Decimal Ceiling (Decimal d)
{
return Math.Ceiling (d);
}
public static Decimal Parse (string s)
{
return Parse (s, NumberStyles.Number, null);
}
public static Decimal Parse (string s, NumberStyles style)
{
return Parse (s, style, null);
}
public static Decimal Parse (string s, IFormatProvider provider)
{
return Parse (s, NumberStyles.Number, provider);
}
static void ThrowAtPos (int pos)
{
throw new FormatException (String.Format (Locale.GetText ("Invalid character at position {0}"), pos));
}
static void ThrowInvalidExp ()
{
throw new FormatException (Locale.GetText ("Invalid exponent"));
}
private static string stripStyles (string s, NumberStyles style, NumberFormatInfo nfi,
out int decPos, out bool isNegative, out bool expFlag, out int exp, bool throwex)
{
isNegative = false;
expFlag = false;
exp = 0;
decPos = -1;
bool hasSign = false;
bool hasOpeningParentheses = false;
bool hasDecimalPoint = false;
bool allowedLeadingWhiteSpace = ((style & NumberStyles.AllowLeadingWhite) != 0);
bool allowedTrailingWhiteSpace = ((style & NumberStyles.AllowTrailingWhite) != 0);
bool allowedLeadingSign = ((style & NumberStyles.AllowLeadingSign) != 0);
bool allowedTrailingSign = ((style & NumberStyles.AllowTrailingSign) != 0);
bool allowedParentheses = ((style & NumberStyles.AllowParentheses) != 0);
bool allowedThousands = ((style & NumberStyles.AllowThousands) != 0);
bool allowedDecimalPoint = ((style & NumberStyles.AllowDecimalPoint) != 0);
bool allowedExponent = ((style & NumberStyles.AllowExponent) != 0);
/* get rid of currency symbol */
bool hasCurrency = false;
if ((style & NumberStyles.AllowCurrencySymbol) != 0)
{
int index = s.IndexOf (nfi.CurrencySymbol);
if (index >= 0)
{
s = s.Remove (index, nfi.CurrencySymbol.Length);
hasCurrency = true;
}
}
string decimalSep = (hasCurrency) ? nfi.CurrencyDecimalSeparator : nfi.NumberDecimalSeparator;
string groupSep = (hasCurrency) ? nfi.CurrencyGroupSeparator : nfi.NumberGroupSeparator;
string negativeSign = nfi.NegativeSign;
string positiveSign = nfi.PositiveSign;
// If we don't have a group separator defined, it has the same effect as if it wasn't allowed.
if (string.IsNullOrEmpty(groupSep)) allowedThousands = false;
int pos = 0;
int len = s.Length;
StringBuilder sb = new StringBuilder (len);
// leading
while (pos < len)
{
char ch = s[pos];
if (Char.IsDigit (ch))
{
break; // end of leading
}
else if (allowedLeadingWhiteSpace && Char.IsWhiteSpace (ch))
{
pos++;
}
else if (allowedParentheses && ch == '(' && !hasSign && !hasOpeningParentheses)
{
hasOpeningParentheses = true;
hasSign = true;
isNegative = true;
pos++;
}
else if (allowedLeadingSign && !string.IsNullOrEmpty (negativeSign) && ch == negativeSign[0] && !hasSign)
{
int slen = negativeSign.Length;
if (slen == 1 || s.IndexOf (negativeSign, pos, slen) == pos)
{
hasSign = true;
isNegative = true;
pos += slen;
}
}
else if (allowedLeadingSign && !string.IsNullOrEmpty (positiveSign) && ch == positiveSign[0] && !hasSign)
{
int slen = positiveSign.Length;
if (slen == 1 || s.IndexOf (positiveSign, pos, slen) == pos)
{
hasSign = true;
pos += slen;
}
}
else if (allowedDecimalPoint && ch == decimalSep[0])
{
int slen = decimalSep.Length;
if (slen != 1 && s.IndexOf (decimalSep, pos, slen) != pos)
{
if (throwex)
ThrowAtPos (pos);
else
return null;
}
break;
}
else
{
if (throwex)
ThrowAtPos (pos);
else
return null;
}
}
if (pos == len) {
if (throwex)
throw new FormatException (Locale.GetText ("No digits found"));
else
return null;
}
// digits
while (pos < len)
{
char ch = s[pos];
if (Char.IsDigit (ch))
{
sb.Append(ch);
pos++;
}
else if (allowedThousands && ch == groupSep[0] && ch != decimalSep [0])
{
int slen = groupSep.Length;
if (slen != 1 && s.IndexOf(groupSep, pos, slen) != pos)
{
if (throwex)
ThrowAtPos (pos);
else
return null;
}
pos += slen;
}
else if (allowedDecimalPoint && ch == decimalSep[0] && !hasDecimalPoint)
{
int slen = decimalSep.Length;
if (slen == 1 || s.IndexOf(decimalSep, pos, slen) == pos)
{
decPos = sb.Length;
hasDecimalPoint = true;
pos += slen;
}
}
else
{
break;
}
}
// exponent
if (pos < len)
{
char ch = s[pos];
if (allowedExponent && Char.ToUpperInvariant (ch) == 'E')
{
expFlag = true;
pos++;
if (pos >= len){
if (throwex)
ThrowInvalidExp ();
else
return null;
}
ch = s[pos];
bool isNegativeExp = false;
if (!string.IsNullOrEmpty (positiveSign) && ch == positiveSign[0])
{
int slen = positiveSign.Length;
if (slen == 1 || s.IndexOf (positiveSign, pos, slen) == pos)
{
pos += slen;
if (pos >= len) {
if (throwex)
ThrowInvalidExp ();
else
return null;
}
}
}
else if (!string.IsNullOrEmpty (negativeSign) && ch == negativeSign[0])
{
int slen = negativeSign.Length;
if (slen == 1 || s.IndexOf (negativeSign, pos, slen) == pos)
{
pos += slen;
if (pos >= len) {
if (throwex)
ThrowInvalidExp ();
else
return null;
}
isNegativeExp = true;
}
}
ch = s[pos];
if (!Char.IsDigit(ch)) {
if (throwex)
ThrowInvalidExp ();
else
return null;
}
exp = ch - '0';
pos++;
while (pos < len && Char.IsDigit (s[pos]))
{
exp *= 10;
exp += s[pos] - '0';
pos++;
}
if (isNegativeExp) exp *= -1;
}
}
// trailing
while (pos < len)
{
char ch = s[pos];
if (allowedTrailingWhiteSpace && Char.IsWhiteSpace (ch))
{
pos++;
}
else if (allowedParentheses && ch == ')' && hasOpeningParentheses)
{
hasOpeningParentheses = false;
pos++;
}
else if (allowedTrailingSign && !string.IsNullOrWhiteSpace (negativeSign) && ch == negativeSign[0] && !hasSign)
{
int slen = negativeSign.Length;
if (slen == 1 || s.IndexOf(negativeSign, pos, slen) == pos)
{
hasSign = true;
isNegative = true;
pos += slen;
}
}
else if (allowedTrailingSign && !string.IsNullOrWhiteSpace (positiveSign) && ch == positiveSign[0] && !hasSign)
{
int slen = positiveSign.Length;
if (slen == 1 || s.IndexOf (positiveSign, pos, slen) == pos)
{
hasSign = true;
pos += slen;
}
}
else
{
// trailing zero characters are allowed
if (ch == 0){
while (++pos < len && s [pos] == 0)
;
if (pos == len)
break;
}
if (throwex)
ThrowAtPos (pos);
else
return null;
}
}
if (hasOpeningParentheses) {
if (throwex)
throw new FormatException (Locale.GetText ("Closing Parentheses not found"));
else
return null;
}
if (!hasDecimalPoint)
decPos = sb.Length;
return sb.ToString ();
}
public static Decimal Parse (string s, NumberStyles style, IFormatProvider provider)
{
if (s == null)
throw new ArgumentNullException ("s");
if ((style & NumberStyles.AllowHexSpecifier) != 0)
throw new ArgumentException ("Decimal.TryParse does not accept AllowHexSpecifier", "style");
Decimal result;
PerformParse (s, style, provider, out result, true);
return result;
}
public static bool TryParse (string s, out Decimal result)
{
if (s == null){
result = 0;
return false;
}
return PerformParse (s, NumberStyles.Number, null, out result, false);
}
public static bool TryParse (string s, NumberStyles style, IFormatProvider provider, out decimal result)
{
if (s == null || (style & NumberStyles.AllowHexSpecifier) != 0){
result = 0;
return false;
}
return PerformParse (s, style, provider, out result, false);
}
static bool PerformParse (string s, NumberStyles style, IFormatProvider provider, out Decimal res, bool throwex)
{
NumberFormatInfo nfi = NumberFormatInfo.GetInstance (provider);
int iDecPos, exp;
bool isNegative, expFlag;
s = stripStyles(s, style, nfi, out iDecPos, out isNegative, out expFlag, out exp, throwex);
if (s == null){
res = 0;
return false;
}
if (iDecPos < 0){
if (throwex)
throw new Exception (Locale.GetText ("Error in System.Decimal.Parse"));
res = 0;
return false;
}
// first we remove leading 0
int len = s.Length;
int i = 0;
while ((i < iDecPos) && (s [i] == '0'))
i++;
if ((i > 1) && (len > 1)) {
s = s.Substring (i, len - i);
iDecPos -= i;
}
// first 0. may not be here but is part of the maximum length
int max = ((iDecPos == 0) ? 27 : 28);
len = s.Length;
if (len >= max + 1) {
// number lower than MaxValue (base-less) can have better precision
if (String.Compare (s, 0, "79228162514264337593543950335", 0, max + 1,
false, CultureInfo.InvariantCulture) <= 0) {
max++;
}
}
// then we trunc the string
if ((len > max) && (iDecPos < len)) {
int round = (s [max] - '0');
s = s.Substring (0, max);
bool addone = false;
if (round > 5) {
addone = true;
}
else if (round == 5) {
if (isNegative) {
addone = true;
}
else {
// banker rounding applies :(
int previous = (s [max - 1] - '0');
addone = ((previous & 0x01) == 0x01);
}
}
if (addone) {
char[] array = s.ToCharArray ();
int p = max - 1;
while (p >= 0) {
int b = (array [p] - '0');
if (array [p] != '9') {
array [p] = (char)(b + '1');
break;
}
else {
array [p--] = '0';
}
}
if ((p == -1) && (array [0] == '0')) {
iDecPos++;
s = "1".PadRight (iDecPos, '0');
}
else
s = new String (array);
}
}
Decimal result;
// always work in positive (rounding issues)
if (string2decimal (out result, s, (uint)iDecPos, 0) != 0){
if (throwex)
throw new OverflowException ();
res = 0;
return false;
}
if (expFlag) {
if (decimalSetExponent (ref result, exp) != 0){
if (throwex)
throw new OverflowException ();
res = 0;
return false;
}
}
if (isNegative)
result.flags ^= SIGN_FLAG;
res = result;
return true;
}
public TypeCode GetTypeCode ()
{
return TypeCode.Decimal;
}
public static byte ToByte (decimal value)
{
if (value > Byte.MaxValue || value < Byte.MinValue)
throw new OverflowException (Locale.GetText (
"Value is greater than Byte.MaxValue or less than Byte.MinValue"));
// return truncated value
return (byte)(Decimal.Truncate (value));
}
public static double ToDouble (decimal d)
{
return Convert.ToDouble (d);
}
public static short ToInt16 (decimal value)
{
if (value > Int16.MaxValue || value < Int16.MinValue)
throw new OverflowException (Locale.GetText (
"Value is greater than Int16.MaxValue or less than Int16.MinValue"));
// return truncated value
return (Int16)(Decimal.Truncate (value));
}
public static int ToInt32 (decimal d)
{
if (d > Int32.MaxValue || d < Int32.MinValue)
throw new OverflowException (Locale.GetText (
"Value is greater than Int32.MaxValue or less than Int32.MinValue"));
// return truncated value
return (Int32)(Decimal.Truncate (d));
}
public static long ToInt64 (decimal d)
{
if (d > Int64.MaxValue || d < Int64.MinValue)
throw new OverflowException (Locale.GetText (
"Value is greater than Int64.MaxValue or less than Int64.MinValue"));
// return truncated value
return (Int64)(Decimal.Truncate (d));
}
public static long ToOACurrency (decimal value)
{
return (long) (value * 10000);
}
[CLSCompliant(false)]
public static sbyte ToSByte (decimal value)
{
if (value > SByte.MaxValue || value < SByte.MinValue)
throw new OverflowException (Locale.GetText (
"Value is greater than SByte.MaxValue or less than SByte.MinValue"));
// return truncated value
return (SByte)(Decimal.Truncate (value));
}
public static float ToSingle (decimal d)
{
return Convert.ToSingle (d);
}
[CLSCompliant(false)]
public static ushort ToUInt16 (decimal value)
{
if (value > UInt16.MaxValue || value < UInt16.MinValue)
throw new OverflowException (Locale.GetText (
"Value is greater than UInt16.MaxValue or less than UInt16.MinValue"));
// return truncated value
return (UInt16)(Decimal.Truncate (value));
}
[CLSCompliant(false)]
public static uint ToUInt32 (decimal d)
{
if (d > UInt32.MaxValue || d < UInt32.MinValue)
throw new OverflowException (Locale.GetText (
"Value is greater than UInt32.MaxValue or less than UInt32.MinValue"));
// return truncated value
return (UInt32)(Decimal.Truncate (d));
}
[CLSCompliant(false)]
public static ulong ToUInt64 (decimal d)
{
if (d > UInt64.MaxValue || d < UInt64.MinValue)
throw new OverflowException (Locale.GetText (
"Value is greater than UInt64.MaxValue or less than UInt64.MinValue"));
// return truncated value
return (UInt64)(Decimal.Truncate (d));
}
object IConvertible.ToType (Type targetType, IFormatProvider provider)
{
if (targetType == null)
throw new ArgumentNullException ("targetType");
return Convert.ToType (this, targetType, provider, false);
}
bool IConvertible.ToBoolean (IFormatProvider provider)
{
return Convert.ToBoolean (this);
}
byte IConvertible.ToByte (IFormatProvider provider)
{
return Convert.ToByte (this);
}
char IConvertible.ToChar (IFormatProvider provider)
{
throw new InvalidCastException ();
}
DateTime IConvertible.ToDateTime (IFormatProvider provider)
{
throw new InvalidCastException ();
}
decimal IConvertible.ToDecimal (IFormatProvider provider)
{
return this;
}
double IConvertible.ToDouble (IFormatProvider provider)
{
return Convert.ToDouble (this);
}
short IConvertible.ToInt16 (IFormatProvider provider)
{
return Convert.ToInt16 (this);
}
int IConvertible.ToInt32 (IFormatProvider provider)
{
return Convert.ToInt32 (this);
}
long IConvertible.ToInt64 (IFormatProvider provider)
{
return Convert.ToInt64 (this);
}
sbyte IConvertible.ToSByte (IFormatProvider provider)
{
return Convert.ToSByte (this);
}
float IConvertible.ToSingle (IFormatProvider provider)
{
return Convert.ToSingle (this);
}
ushort IConvertible.ToUInt16 (IFormatProvider provider)
{
return Convert.ToUInt16 (this);
}
uint IConvertible.ToUInt32 (IFormatProvider provider)
{
return Convert.ToUInt32 (this);
}
ulong IConvertible.ToUInt64 (IFormatProvider provider)
{
return Convert.ToUInt64 (this);
}
public string ToString (string format, IFormatProvider provider)
{
throw new NotImplementedException("System.Decimal.ToString");
//return NumberFormatter.NumberToString (format, this, provider);
}
public override string ToString ()
{
return ToString ("G", null);
}
public string ToString (string format)
{
return ToString (format, null);
}
public string ToString (IFormatProvider provider)
{
return ToString ("G", provider);
}
#if NET_4_0
void IDeserializationCallback.OnDeserialization(object sender)
{
}
#endif
#if !MSTEST
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static extern int decimal2UInt64 (ref Decimal val, out ulong result);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static extern int decimal2Int64 (ref Decimal val, out long result);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static extern int double2decimal (out Decimal erg, double val, int digits);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static extern int decimalIncr (ref Decimal d1, ref Decimal d2);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern int string2decimal (out Decimal val, String sDigits, uint decPos, int sign);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern int decimalSetExponent (ref Decimal val, int exp);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static extern double decimal2double (ref Decimal val);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static extern void decimalFloorAndTrunc (ref Decimal val, int floorFlag);
// [MethodImplAttribute(MethodImplOptions.InternalCall)]
// private static extern void decimalRound (ref Decimal val, int decimals);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static extern int decimalMult (ref Decimal pd1, ref Decimal pd2);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static extern int decimalDiv (out Decimal pc, ref Decimal pa, ref Decimal pb);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static extern int decimalIntDiv (out Decimal pc, ref Decimal pa, ref Decimal pb);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static extern int decimalCompare (ref Decimal d1, ref Decimal d2);
#else
//![MethodImplAttribute(MethodImplOptions.InternalCall)]
[DllImport("libdec", EntryPoint="decimal2UInt64")]
private static extern int decimal2UInt64 (ref Decimal val, out ulong result);
//![MethodImplAttribute(MethodImplOptions.InternalCall)]
[DllImport("libdec", EntryPoint="decimal2Int64")]
private static extern int decimal2Int64 (ref Decimal val, out long result);
//![MethodImplAttribute(MethodImplOptions.InternalCall)]
[DllImport("libdec", EntryPoint="double2decimal")]
private static extern int double2decimal (out Decimal erg, double val, int digits);
//![MethodImplAttribute(MethodImplOptions.InternalCall)]
[DllImport("libdec", EntryPoint="decimalIncr")]
private static extern int decimalIncr (ref Decimal d1, ref Decimal d2);
//![MethodImplAttribute(MethodImplOptions.InternalCall)]
[DllImport("libdec", EntryPoint="string2decimal")]
internal static extern int string2decimal (out Decimal val,
[MarshalAs(UnmanagedType.LPWStr)]String sDigits,
uint decPos, int sign);
//![MethodImplAttribute(MethodImplOptions.InternalCall)]
[DllImport("libdec", EntryPoint="decimalSetExponent")]
internal static extern int decimalSetExponent (ref Decimal val, int exp);
//![MethodImplAttribute(MethodImplOptions.InternalCall)]
[DllImport("libdec", EntryPoint="decimal2double")]
private static extern double decimal2double (ref Decimal val);
//![MethodImplAttribute(MethodImplOptions.InternalCall)]
[DllImport("libdec", EntryPoint="decimalFloorAndTrunc")]
private static extern void decimalFloorAndTrunc (ref Decimal val, int floorFlag);
//![MethodImplAttribute(MethodImplOptions.InternalCall)]
[DllImport("libdec", EntryPoint="decimalRound")]
private static extern void decimalRound (ref Decimal val, int decimals);
//![MethodImplAttribute(MethodImplOptions.InternalCall)]
[DllImport("libdec", EntryPoint="decimalMult")]
private static extern int decimalMult (ref Decimal pd1, ref Decimal pd2);
//![MethodImplAttribute(MethodImplOptions.InternalCall)]
[DllImport("libdec", EntryPoint="decimalDiv")]
private static extern int decimalDiv (out Decimal pc, ref Decimal pa, ref Decimal pb);
//![MethodImplAttribute(MethodImplOptions.InternalCall)]
[DllImport("libdec", EntryPoint="decimalIntDiv")]
private static extern int decimalIntDiv (out Decimal pc, ref Decimal pa, ref Decimal pb);
//![MethodImplAttribute(MethodImplOptions.InternalCall)]
[DllImport("libdec", EntryPoint="decimalCompare")]
private static extern int decimalCompare (ref Decimal d1, ref Decimal d2);
#endif
}
}
| |
/*
Copyright 2019 Esri
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Input;
using ArcGIS.Core.Data;
using ArcGIS.Core.Events;
using ArcGIS.Core.Geometry;
using ArcGIS.Desktop.Editing;
using ArcGIS.Desktop.Editing.Events;
using ArcGIS.Desktop.Framework;
using ArcGIS.Desktop.Framework.Contracts;
using ArcGIS.Desktop.Framework.Dialogs;
using ArcGIS.Desktop.Framework.Threading.Tasks;
using ArcGIS.Desktop.Mapping;
namespace EditEventsSample.Dockpane
{
internal class EditorEventsSpyViewModel : DockPane
{
private const string _dockPaneID = "EditEventsSample_Dockpane_EditorEventsSpy";
private double _delta = 200.0;
private static double _offset = 0.0;
private int _numCreatesAtOneTime = 2;//change this to trigger more or less creates
//when the create button is clicked
private ICommand _createCmd;
private ICommand _changeCmd;
private ICommand _deleteCmd;
private ICommand _showCmd;
//For the events
private Dictionary<string, List<SubscriptionToken>> _rowevents = new Dictionary<string, List<SubscriptionToken>>();
private List<SubscriptionToken> _editevents = new List<SubscriptionToken>();
private ICommand _startStopCmd;
private ICommand _clearCmd = null;
private bool _listening = false;
private static readonly object _lock = new object();
private List<string> _entries = new List<string>();
private bool _firstStart = true;
//Flags for the row event handling
private bool _cancelEdit = false;
private bool _validate = false;
private bool _failvalidate = false;
private string _validateMsg = "";
protected EditorEventsSpyViewModel() {
AddEntry("Click 'Start Events' to start listening to edit events");
}
/// <summary>
/// Show the DockPane.
/// </summary>
internal static void Show()
{
DockPane pane = FrameworkApplication.DockPaneManager.Find(_dockPaneID);
if (pane == null)
return;
pane.Activate();
}
public string EventLog
{
get
{
string contents = "";
lock (_lock)
{
contents = string.Join("\r\n", _entries.ToArray());
}
return contents;
}
}
public override OperationManager OperationManager
{
get
{
return MapView.Active?.Map.OperationManager;
}
}
#region Flags
public bool CancelEdits
{
get
{
return _cancelEdit;
}
set
{
SetProperty(ref _cancelEdit, value, () => CancelEdits);
}
}
public bool ValidateEdits
{
get
{
return _validate;
}
set
{
SetProperty(ref _validate, value, () => ValidateEdits);
}
}
public bool FailValidateEdits
{
get
{
return _failvalidate;
}
set
{
SetProperty(ref _failvalidate, value, () => FailValidateEdits);
}
}
#endregion Flags
#region Editing Commands
public ICommand CreateCmd
{
get
{
if (_createCmd == null)
_createCmd = new RelayCommand(() => DoCreate());
return _createCmd;
}
}
public ICommand ChangeCmd
{
get
{
if (_changeCmd == null)
_changeCmd = new RelayCommand(() => DoChange());
return _changeCmd;
}
}
public ICommand DeleteCmd
{
get
{
if (_deleteCmd == null)
_deleteCmd = new RelayCommand(() => DoDelete());
return _deleteCmd;
}
}
private void DoCreate()
{
var x1 = 7683671.0;
var y1 = 687075.0;
var crimes = Module1.Current.Crimes;
if (NoCrimes(crimes))
return;
var editOp = new EditOperation();
editOp.Name = $"Create {Module1.Current.CrimesLayerName}";
editOp.SelectNewFeatures = true;
QueuedTask.Run(() =>
{
//do multiple creates if specified
for(int i = 0; i < _numCreatesAtOneTime; i++)
{
x1 += _offset;
y1 += _offset;
_offset += _delta;
var pt = MapPointBuilder.CreateMapPoint(x1, y1, crimes.GetSpatialReference());
Dictionary<string, object> attributes = new Dictionary<string, object>();
attributes["SHAPE"] = pt;
attributes["OFFENSE_TYPE"] = 4;
attributes["MAJOR_OFFENSE_TYPE"] = "DUI";
//do the create
editOp.Create(crimes, attributes);
}
editOp.Execute();
});
}
private async void DoChange()
{
var crimes = Module1.Current.Crimes;
if (NoCrimes(crimes))
return;
bool noSelect = true;
var editOp = new EditOperation();
editOp.Name = $"Change {Module1.Current.CrimesLayerName}";
editOp.SelectModifiedFeatures = true;
await QueuedTask.Run(() =>
{
using (var select = crimes.GetSelection())
{
if (select.GetCount() > 0)
{
noSelect = false;
foreach (var oid in select.GetObjectIDs())
{
//change an attribute
Dictionary<string, object> attributes = new Dictionary<string, object>();
attributes["POLICE_DISTRICT"] = "999";
editOp.Modify(crimes, oid, attributes);
}
editOp.Execute();
}
}
});
if (noSelect) NothingSelected();
}
private async void DoDelete()
{
var crimes = Module1.Current.Crimes;
if (NoCrimes(crimes))
return;
bool noSelect = true;
var editOp = new EditOperation();
editOp.Name = $"Delete {Module1.Current.CrimesLayerName}";
await QueuedTask.Run(() =>
{
using (var select = crimes.GetSelection())
{
if (select.GetCount() > 0)
{
noSelect = false;
editOp.Delete(crimes, select.GetObjectIDs());
editOp.Execute();
}
}
if (!_cancelEdit && !_failvalidate)
crimes.ClearSelection();
});
if (noSelect) NothingSelected();
}
private bool NoCrimes(FeatureLayer crimes)
{
if (crimes == null)
{
MessageBox.Show($"Please add the {Module1.Current.CrimesLayerName} feature layer from the sample data to your map",
$"{Module1.Current.CrimesLayerName} missing");
return true;
}
return false;
}
private void NothingSelected()
{
MessageBox.Show($"Please select some {Module1.Current.CrimesLayerName} then re-execute",
$"No {Module1.Current.CrimesLayerName} selected");
}
#endregion Editing Commands
public ICommand ShowSelectedCmd
{
get
{
if (_showCmd == null)
{
_showCmd = new RelayCommand(async () =>
{
bool noSelect = true;
await QueuedTask.Run(() =>
{
var select = Module1.Current.Crimes?.GetSelection();
if (select != null)
{
if (select.GetCount() > 0)
{
noSelect = false;
var camera = MapView.Active.Camera;
MapView.Active.ZoomTo(Module1.Current.Crimes, true,
new TimeSpan(0, 0, 2));
MapView.Active.ZoomTo(camera, new TimeSpan(0, 0, 0,0,500));
select.Dispose();
}
}
});
if (noSelect) NothingSelected();
});
}
return _showCmd;
}
}
#region Events
public string ButtonText => _listening ? "Stop Events" : "Start Events";
#region RegisterUnregister
public ICommand StartStopCmd
{
get
{
if (_startStopCmd == null)
{
_startStopCmd = new RelayCommand(() => {
if (_firstStart)
{
ClearEntries();
_firstStart = false;
}
if (_rowevents.Count > 0)
{
_listening = Unregister();
AddEntry("Not listening");
}
else
{
_listening = Register();
AddEntry("Listening");
}
NotifyPropertyChanged("ButtonText");
});
}
return _startStopCmd;
}
}
private bool Register()
{
var layers = MapView.Active.Map.GetLayersAsFlattenedList().OfType<FeatureLayer>();
QueuedTask.Run(() => {
foreach (var fl in layers)
{
var fc = fl.GetFeatureClass();
var tokens = new List<SubscriptionToken>();
//These events are fired once ~per feature~,
//per table
tokens.Add(RowCreatedEvent.Subscribe((rc) => RowEventHandler(rc), fc));
tokens.Add(RowChangedEvent.Subscribe((rc) => RowEventHandler(rc), fc));
tokens.Add(RowDeletedEvent.Subscribe((rc) => RowEventHandler(rc), fc));
_rowevents[fl.Name] = tokens;
}
//This event is fired once per edit execute
//Note: This event won't fire if the edits were cancelled
_editevents.Add(EditCompletingEvent.Subscribe((ec) =>
{
RecordEvent("EditCompletingEvent", "");
//can also cancel edit in the completing event...
//cancels everything (that is cancealable)
//
//you'll need to modify the RowEventHandler() to prevent if
//from doing the cancel or this will never get called
if (_cancelEdit)
{
ec.CancelEdit($"EditCompletingEvent, edit cancelled");
AddEntry("*** edits cancelled");
AddEntry("---------------------------------");
}
}));
//This event is fired after all the edits are completed (and on
//save, discard, undo, redo) and is fired once
_editevents.Add(EditCompletedEvent.Subscribe((ec) => {
HandleEditCompletedEvent(ec);
return Task.FromResult(0);
}));
});
return true;
}
private bool Unregister()
{
//Careful here - events have to be unregistered on the same
//thread they were registered on...hence the use of the
//Queued Task
QueuedTask.Run(() =>
{
//One kvp per layer....of which there is only one in the sample
//out of the box but you can add others and register for events
foreach (var kvp in _rowevents)
{
RowCreatedEvent.Unsubscribe(kvp.Value[0]);
RowChangedEvent.Unsubscribe(kvp.Value[1]);
RowDeletedEvent.Unsubscribe(kvp.Value[2]);
kvp.Value.Clear();
}
_rowevents.Clear();
//Editing and Edit Completed.
RowDeletedEvent.Unsubscribe(_editevents[0]);
RowDeletedEvent.Unsubscribe(_editevents[1]);
_editevents.Clear();
});
return false;
}
#endregion RegisterUnregister
public ICommand ClearTextCmd
{
get
{
if (_clearCmd == null)
_clearCmd = new RelayCommand(() => ClearEntries());
return _clearCmd;
}
}
#region Event Handlers
private void HandleEditCompletedEvent(EditCompletedEventArgs args)
{
RecordEvent("EditCompletedEvent", args.CompletedType.ToString());
StringBuilder adds = new StringBuilder();
StringBuilder mods = new StringBuilder();
StringBuilder dels = new StringBuilder();
adds.AppendLine("Adds");
mods.AppendLine("Modifies");
dels.AppendLine("Deletes");
if (args.Creates != null)
{
foreach (var kvp in args.Creates)
{
var oids = string.Join(",", kvp.Value.Select(n => n.ToString()).ToArray());
adds.AppendLine($" {kvp.Key.Name} {oids}");
}
}
else
{
adds.AppendLine(" No Adds");
}
if (args.Modifies != null)
{
foreach (var kvp in args.Modifies)
{
var oids = string.Join(",", kvp.Value.Select(n => n.ToString()).ToArray());
mods.AppendLine($" {kvp.Key.Name} {oids}");
}
}
else
{
mods.AppendLine(" No Modifies");
}
if (args.Deletes != null)
{
foreach (var kvp in args.Deletes)
{
var oids = string.Join(",", kvp.Value.Select(n => n.ToString()).ToArray());
dels.AppendLine($" {kvp.Key.Name} {oids}");
}
}
else
{
dels.AppendLine(" No Deletes");
}
AddEntry(adds.ToString());
AddEntry(mods.ToString());
AddEntry(dels.ToString());
AddEntry("---------------------------------");
}
private void RowEventHandler(RowChangedEventArgs rc)
{
using (var table = rc.Row.GetTable())
{
RecordEvent(rc, table);
//validate flag is set
//Note, we are validating deletes as well...if that makes sense ;-)
//if not, change the sample to check the rc.EditType for
//EditType.Delete and skip...
if (_validate)
{
//You can use 'rc.Row.HasValueChanged(fieldIndex)` to determine if
//a value you need to validate has changed
//
//call your validation method as needed...
//our validate method is a placeholder
if (!ValidateTheRow(rc.Row))
{
//if your validation fails take the appropriate action..
//we cancel the edit in this example
AddEntry($"*** {_validateMsg}");
rc.CancelEdit(_validateMsg);
AddEntry("*** edit cancelled");
AddEntry("---------------------------------");
return;
}
AddEntry("*** row validated");
}
//Cancel flag is set. If you have _failvalidate checked you won't
//get here - validation will have failed and canceled the edit
if (_cancelEdit)
{
//cancel the edit
rc.CancelEdit($"{rc.EditType} for {table.GetName()} cancelled");
AddEntry("*** edit cancelled");
AddEntry("---------------------------------");
}
}
}
internal bool ValidateTheRow(Row row)
{
//in the sample we are either returning true or deliberately
//failing the row validation.
if (_failvalidate)
{
var idx = row.FindField("POLICE_DISTRICT");
if (idx < 0) _validateMsg = $@"Force a failed validation: 'POLICE_DISTRICT' not found";
else
{
var district = (string)row[idx];
_validateMsg = $"Invalid district: {district}, row {row.GetObjectID()}";
}
}
return !_failvalidate;
}
private void AddEntry(string entry)
{
lock (_lock)
{
_entries.Add($"{entry}");
}
NotifyPropertyChanged(nameof(EventLog));
}
private void ClearEntries()
{
lock (_lock)
{
_entries.Clear();
}
NotifyPropertyChanged(nameof(EventLog));
}
private void RecordEvent(string eventName, string entry)
{
var dateTime = DateTime.Now.ToString("G");
lock (_lock)
{
_entries.Add($"{dateTime}: {eventName} {entry}");
}
NotifyPropertyChanged(nameof(EventLog));
}
private void RecordEvent(RowChangedEventArgs rc, Table table)
{
var eventName = $"Row{rc.EditType.ToString()}dEvent";
var entry = $"{table.GetName()}, oid:{rc.Row.GetObjectID()}";
RecordEvent(eventName, entry);
}
#endregion Event Handlers
#endregion Events
}
/// <summary>
/// Button implementation to show the DockPane.
/// </summary>
internal class EditorEventsSpy_ShowButton : Button
{
protected override void OnClick()
{
EditorEventsSpyViewModel.Show();
}
}
}
| |
using System;
using System.Collections;
using System.Globalization;
using System.IO;
using Org.BouncyCastle.Utilities;
using Org.BouncyCastle.Utilities.Collections;
namespace Org.BouncyCastle.Bcpg.OpenPgp
{
/// <remarks>
/// Often a PGP key ring file is made up of a succession of master/sub-key key rings.
/// If you want to read an entire public key file in one hit this is the class for you.
/// </remarks>
public class PgpPublicKeyRingBundle
{
private readonly IDictionary pubRings;
private readonly IList order;
private PgpPublicKeyRingBundle(
IDictionary pubRings,
IList order)
{
this.pubRings = pubRings;
this.order = order;
}
public PgpPublicKeyRingBundle(
byte[] encoding)
: this(new MemoryStream(encoding, false))
{
}
/// <summary>Build a PgpPublicKeyRingBundle from the passed in input stream.</summary>
/// <param name="inputStream">Input stream containing data.</param>
/// <exception cref="IOException">If a problem parsing the stream occurs.</exception>
/// <exception cref="PgpException">If an object is encountered which isn't a PgpPublicKeyRing.</exception>
public PgpPublicKeyRingBundle(
Stream inputStream)
: this(new PgpObjectFactory(inputStream).AllPgpObjects())
{
}
public PgpPublicKeyRingBundle(
IEnumerable e)
{
this.pubRings = Platform.CreateHashtable();
this.order = Platform.CreateArrayList();
foreach (object obj in e)
{
PgpPublicKeyRing pgpPub = obj as PgpPublicKeyRing;
if (pgpPub == null)
{
throw new PgpException(obj.GetType().FullName + " found where PgpPublicKeyRing expected");
}
long key = pgpPub.GetPublicKey().KeyId;
pubRings.Add(key, pgpPub);
order.Add(key);
}
}
[Obsolete("Use 'Count' property instead")]
public int Size
{
get { return order.Count; }
}
/// <summary>Return the number of key rings in this collection.</summary>
public int Count
{
get { return order.Count; }
}
/// <summary>Allow enumeration of the public key rings making up this collection.</summary>
public IEnumerable GetKeyRings()
{
return new EnumerableProxy(pubRings.Values);
}
/// <summary>Allow enumeration of the key rings associated with the passed in userId.</summary>
/// <param name="userId">The user ID to be matched.</param>
/// <returns>An <c>IEnumerable</c> of key rings which matched (possibly none).</returns>
public IEnumerable GetKeyRings(
string userId)
{
return GetKeyRings(userId, false, false);
}
/// <summary>Allow enumeration of the key rings associated with the passed in userId.</summary>
/// <param name="userId">The user ID to be matched.</param>
/// <param name="matchPartial">If true, userId need only be a substring of an actual ID string to match.</param>
/// <returns>An <c>IEnumerable</c> of key rings which matched (possibly none).</returns>
public IEnumerable GetKeyRings(
string userId,
bool matchPartial)
{
return GetKeyRings(userId, matchPartial, false);
}
/// <summary>Allow enumeration of the key rings associated with the passed in userId.</summary>
/// <param name="userId">The user ID to be matched.</param>
/// <param name="matchPartial">If true, userId need only be a substring of an actual ID string to match.</param>
/// <param name="ignoreCase">If true, case is ignored in user ID comparisons.</param>
/// <returns>An <c>IEnumerable</c> of key rings which matched (possibly none).</returns>
public IEnumerable GetKeyRings(
string userId,
bool matchPartial,
bool ignoreCase)
{
IList rings = Platform.CreateArrayList();
if (ignoreCase)
{
userId = userId.ToLower(CultureInfo.InvariantCulture);
}
foreach (PgpPublicKeyRing pubRing in GetKeyRings())
{
foreach (string nextUserID in pubRing.GetPublicKey().GetUserIds())
{
string next = nextUserID;
if (ignoreCase)
{
next = next.ToLower(CultureInfo.InvariantCulture);
}
if (matchPartial)
{
if (next.IndexOf(userId) > -1)
{
rings.Add(pubRing);
}
}
else
{
if (next.Equals(userId))
{
rings.Add(pubRing);
}
}
}
}
return new EnumerableProxy(rings);
}
/// <summary>Return the PGP public key associated with the given key id.</summary>
/// <param name="keyId">The ID of the public key to return.</param>
public PgpPublicKey GetPublicKey(
long keyId)
{
foreach (PgpPublicKeyRing pubRing in GetKeyRings())
{
PgpPublicKey pub = pubRing.GetPublicKey(keyId);
if (pub != null)
{
return pub;
}
}
return null;
}
/// <summary>Return the public key ring which contains the key referred to by keyId</summary>
/// <param name="keyId">key ID to match against</param>
public PgpPublicKeyRing GetPublicKeyRing(
long keyId)
{
if (pubRings.Contains(keyId))
{
return (PgpPublicKeyRing)pubRings[keyId];
}
foreach (PgpPublicKeyRing pubRing in GetKeyRings())
{
PgpPublicKey pub = pubRing.GetPublicKey(keyId);
if (pub != null)
{
return pubRing;
}
}
return null;
}
/// <summary>
/// Return true if a key matching the passed in key ID is present, false otherwise.
/// </summary>
/// <param name="keyID">key ID to look for.</param>
public bool Contains(
long keyID)
{
return GetPublicKey(keyID) != null;
}
public byte[] GetEncoded()
{
MemoryStream bOut = new MemoryStream();
Encode(bOut);
return bOut.ToArray();
}
public void Encode(
Stream outStr)
{
BcpgOutputStream bcpgOut = BcpgOutputStream.Wrap(outStr);
foreach (long key in order)
{
PgpPublicKeyRing sec = (PgpPublicKeyRing) pubRings[key];
sec.Encode(bcpgOut);
}
}
/// <summary>
/// Return a new bundle containing the contents of the passed in bundle and
/// the passed in public key ring.
/// </summary>
/// <param name="bundle">The <c>PgpPublicKeyRingBundle</c> the key ring is to be added to.</param>
/// <param name="publicKeyRing">The key ring to be added.</param>
/// <returns>A new <c>PgpPublicKeyRingBundle</c> merging the current one with the passed in key ring.</returns>
/// <exception cref="ArgumentException">If the keyId for the passed in key ring is already present.</exception>
public static PgpPublicKeyRingBundle AddPublicKeyRing(
PgpPublicKeyRingBundle bundle,
PgpPublicKeyRing publicKeyRing)
{
long key = publicKeyRing.GetPublicKey().KeyId;
if (bundle.pubRings.Contains(key))
{
throw new ArgumentException("Bundle already contains a key with a keyId for the passed in ring.");
}
IDictionary newPubRings = Platform.CreateHashtable(bundle.pubRings);
IList newOrder = Platform.CreateArrayList(bundle.order);
newPubRings[key] = publicKeyRing;
newOrder.Add(key);
return new PgpPublicKeyRingBundle(newPubRings, newOrder);
}
/// <summary>
/// Return a new bundle containing the contents of the passed in bundle with
/// the passed in public key ring removed.
/// </summary>
/// <param name="bundle">The <c>PgpPublicKeyRingBundle</c> the key ring is to be removed from.</param>
/// <param name="publicKeyRing">The key ring to be removed.</param>
/// <returns>A new <c>PgpPublicKeyRingBundle</c> not containing the passed in key ring.</returns>
/// <exception cref="ArgumentException">If the keyId for the passed in key ring is not present.</exception>
public static PgpPublicKeyRingBundle RemovePublicKeyRing(
PgpPublicKeyRingBundle bundle,
PgpPublicKeyRing publicKeyRing)
{
long key = publicKeyRing.GetPublicKey().KeyId;
if (!bundle.pubRings.Contains(key))
{
throw new ArgumentException("Bundle does not contain a key with a keyId for the passed in ring.");
}
IDictionary newPubRings = Platform.CreateHashtable(bundle.pubRings);
IList newOrder = Platform.CreateArrayList(bundle.order);
newPubRings.Remove(key);
newOrder.Remove(key);
return new PgpPublicKeyRingBundle(newPubRings, newOrder);
}
}
}
| |
/*
* Copyright (c) 2010-2012, Achim 'ahzf' Friedland <[email protected]>
* This file is part of Styx <http://www.github.com/Vanaheimr/Styx>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#region Usings
using System;
using System.Linq;
using System.Collections;
using System.Collections.Generic;
#endregion
namespace de.ahzf.Styx
{
#region AbstractMetaPipe<S, E>
/// <summary>
/// An AbstractPipe provides most of the functionality that is repeated
/// in every instance of a Pipe. Any subclass of AbstractPipe should simply
/// implement MoveNext().
/// </summary>
/// <typeparam name="S">The type of the consuming objects.</typeparam>
/// <typeparam name="E">The type of the emitting objects.</typeparam>
public abstract class AbstractMetaPipe<S, E> : IMetaPipe<S, E>
{
#region Data
private readonly IPipe[] InternalPipes;
private readonly IStartPipe<S> StartPipe;
private readonly IEndPipe<E> EndPipe;
#endregion
#region Constructor(s)
#region AbstractMetaPipe()
/// <summary>
/// Creates a AbstractPipe pipe.
/// </summary>
public AbstractMetaPipe()
{ }
#endregion
#region AbstractMetaPipe(InternalPipes, IEnumerator, IEnumerable)
/// <summary>
/// Creates a new AbstractPipe using the elements emitted
/// by the given IEnumerator as input.
/// </summary>
/// <param name="InternalPipes">The array of all wrapped pipes.</param>
/// <param name="IEnumerable">An IEnumerable<S> as element source.</param>
/// <param name="IEnumerator">An IEnumerator<S> as element source.</param>
public AbstractMetaPipe(IPipe[] InternalPipes, IEnumerable<S> IEnumerable, IEnumerator<S> IEnumerator)
{
#region Initial checks
if (InternalPipes == null)
throw new ArgumentNullException("The array of wrapped pipes must not be null!");
if (InternalPipes.Length < 2)
throw new ArgumentException("The array of wrapped pipes must at least wrap two pipes!");
if (!(InternalPipes[0] is IStartPipe<S>))
throw new ArgumentException("The first wrapped pipe must implement IStartPipe<S>!");
if (!(InternalPipes[InternalPipes.Length-1] is IEndPipe<E>))
throw new ArgumentException("The last wrapped pipe must implement IEndPipe<E>!");
if (IEnumerator != null && IEnumerable != null)
throw new ArgumentException("Please decide between IEnumerator and IEnumerable!");
#endregion
this.InternalPipes = InternalPipes;
this.StartPipe = InternalPipes[0] as IStartPipe<S>;
this.EndPipe = InternalPipes[InternalPipes.Length-1] as IEndPipe<E>;
if (IEnumerable != null)
this.StartPipe.SetSourceCollection(IEnumerable);
if (IEnumerator != null)
this.StartPipe.SetSource(IEnumerator);
for (var i = 1; i < InternalPipes.Length; i++)
{
InternalPipes[i].SetSource(InternalPipes[i - 1]);
}
}
#endregion
#endregion
#region SetSource(SourceElement)
/// <summary>
/// Set the given element as source.
/// </summary>
/// <param name="SourceElement">A single source element.</param>
void IStartPipe.SetSource(Object SourceElement)
{
StartPipe.SetSource(SourceElement);
}
/// <summary>
/// Set the given element as source.
/// </summary>
/// <param name="SourceElement">A single source element.</param>
public virtual void SetSource(S SourceElement)
{
StartPipe.SetSource(SourceElement);
}
#endregion
#region SetSource(IEnumerator)
/// <summary>
/// Set the elements emitted by the given IEnumerator<S> as input.
/// </summary>
/// <param name="IEnumerator">An IEnumerator<S> as element source.</param>
void IStartPipe.SetSource(IEnumerator IEnumerator)
{
StartPipe.SetSource(IEnumerator);
}
/// <summary>
/// Set the elements emitted by the given IEnumerator<S> as input.
/// </summary>
/// <param name="IEnumerator">An IEnumerator<S> as element source.</param>
public virtual void SetSource(IEnumerator<S> IEnumerator)
{
StartPipe.SetSource(IEnumerator);
}
#endregion
#region SetSourceCollection(IEnumerable)
/// <summary>
/// Set the elements emitted from the given IEnumerable as input.
/// </summary>
/// <param name="IEnumerable">An IEnumerable as element source.</param>
void IStartPipe.SetSourceCollection(IEnumerable IEnumerable)
{
StartPipe.SetSourceCollection(IEnumerable);
}
/// <summary>
/// Set the elements emitted from the given IEnumerable<S> as input.
/// </summary>
/// <param name="IEnumerable">An IEnumerable<S> as element source.</param>
public virtual void SetSourceCollection(IEnumerable<S> IEnumerable)
{
StartPipe.SetSourceCollection(IEnumerable);
}
#endregion
#region GetEnumerator()
/// <summary>
/// Returns an enumerator that iterates through the collection.
/// </summary>
/// <returns>
/// A IEnumerator<E> that can be used to iterate through the collection.
/// </returns>
public IEnumerator<E> GetEnumerator()
{
return this;
}
/// <summary>
/// Returns an enumerator that iterates through the collection.
/// </summary>
/// <returns>
/// A IEnumerator that can be used to iterate through the collection.
/// </returns>
IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
return this;
}
#endregion
#region Current
/// <summary>
/// Gets the current element in the collection.
/// </summary>
public virtual E Current
{
get
{
return EndPipe.Current;
}
}
/// <summary>
/// Gets the current element in the collection.
/// </summary>
Object System.Collections.IEnumerator.Current
{
get
{
return EndPipe.Current;
}
}
#endregion
#region MoveNext()
/// <summary>
/// Advances the enumerator to the next element of the collection.
/// </summary>
/// <returns>
/// True if the enumerator was successfully advanced to the next
/// element; false if the enumerator has passed the end of the
/// collection.
/// </returns>
public virtual Boolean MoveNext()
{
return EndPipe.MoveNext();
}
#endregion
#region Reset()
/// <summary>
/// Sets the enumerator to its initial position, which is
/// before the first element in the collection.
/// </summary>
public virtual void Reset()
{
foreach (var pipe in InternalPipes)
pipe.Reset();
}
#endregion
#region Dispose()
/// <summary>
/// Disposes this pipe.
/// </summary>
public virtual void Dispose()
{
foreach (var pipe in InternalPipes)
pipe.Dispose();
}
#endregion
#region Path
/// <summary>
/// Returns the transformation path to arrive at the current object
/// of the pipe. This is a list of all of the objects traversed for
/// the current iterator position of the pipe.
/// </summary>
public virtual List<Object> Path
{
get
{
throw new NotImplementedException();
}
}
#endregion
#region PathToHere
private List<Object> PathToHere
{
get
{
throw new NotImplementedException();
}
}
#endregion
#region Pipes
/// <summary>
/// A list of all wrapped pipes
/// </summary>
public virtual IEnumerable<IPipe> Pipes
{
get
{
return InternalPipes;
}
}
#endregion
#region ToString()
/// <summary>
/// A string representation of this pipe.
/// </summary>
public override String ToString()
{
return this.GetType().Name + " (" + String.Join(", ", InternalPipes.Select(p => p.GetType().Name)) + ")";
}
#endregion
}
#endregion
}
| |
/*
* Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
using System.IO;
namespace Amazon.RDS.Model
{
/// <summary>
/// <para> A list of all available options </para>
/// </summary>
public class OptionConfiguration
{
private string optionName;
private int? port;
private List<string> dBSecurityGroupMemberships = new List<string>();
private List<string> vpcSecurityGroupMemberships = new List<string>();
private List<OptionSetting> optionSettings = new List<OptionSetting>();
/// <summary>
/// The configuration of options to include in a group.
///
/// </summary>
public string OptionName
{
get { return this.optionName; }
set { this.optionName = value; }
}
/// <summary>
/// Sets the OptionName property
/// </summary>
/// <param name="optionName">The value to set for the OptionName property </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public OptionConfiguration WithOptionName(string optionName)
{
this.optionName = optionName;
return this;
}
// Check to see if OptionName property is set
internal bool IsSetOptionName()
{
return this.optionName != null;
}
/// <summary>
/// The optional port for the option.
///
/// </summary>
public int Port
{
get { return this.port ?? default(int); }
set { this.port = value; }
}
/// <summary>
/// Sets the Port property
/// </summary>
/// <param name="port">The value to set for the Port property </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public OptionConfiguration WithPort(int port)
{
this.port = port;
return this;
}
// Check to see if Port property is set
internal bool IsSetPort()
{
return this.port.HasValue;
}
/// <summary>
/// A list of DBSecurityGroupMemebrship name strings used for this option.
///
/// </summary>
public List<string> DBSecurityGroupMemberships
{
get { return this.dBSecurityGroupMemberships; }
set { this.dBSecurityGroupMemberships = value; }
}
/// <summary>
/// Adds elements to the DBSecurityGroupMemberships collection
/// </summary>
/// <param name="dBSecurityGroupMemberships">The values to add to the DBSecurityGroupMemberships collection </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public OptionConfiguration WithDBSecurityGroupMemberships(params string[] dBSecurityGroupMemberships)
{
foreach (string element in dBSecurityGroupMemberships)
{
this.dBSecurityGroupMemberships.Add(element);
}
return this;
}
/// <summary>
/// Adds elements to the DBSecurityGroupMemberships collection
/// </summary>
/// <param name="dBSecurityGroupMemberships">The values to add to the DBSecurityGroupMemberships collection </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public OptionConfiguration WithDBSecurityGroupMemberships(IEnumerable<string> dBSecurityGroupMemberships)
{
foreach (string element in dBSecurityGroupMemberships)
{
this.dBSecurityGroupMemberships.Add(element);
}
return this;
}
// Check to see if DBSecurityGroupMemberships property is set
internal bool IsSetDBSecurityGroupMemberships()
{
return this.dBSecurityGroupMemberships.Count > 0;
}
/// <summary>
/// A list of VpcSecurityGroupMemebrship name strings used for this option.
///
/// </summary>
public List<string> VpcSecurityGroupMemberships
{
get { return this.vpcSecurityGroupMemberships; }
set { this.vpcSecurityGroupMemberships = value; }
}
/// <summary>
/// Adds elements to the VpcSecurityGroupMemberships collection
/// </summary>
/// <param name="vpcSecurityGroupMemberships">The values to add to the VpcSecurityGroupMemberships collection </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public OptionConfiguration WithVpcSecurityGroupMemberships(params string[] vpcSecurityGroupMemberships)
{
foreach (string element in vpcSecurityGroupMemberships)
{
this.vpcSecurityGroupMemberships.Add(element);
}
return this;
}
/// <summary>
/// Adds elements to the VpcSecurityGroupMemberships collection
/// </summary>
/// <param name="vpcSecurityGroupMemberships">The values to add to the VpcSecurityGroupMemberships collection </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public OptionConfiguration WithVpcSecurityGroupMemberships(IEnumerable<string> vpcSecurityGroupMemberships)
{
foreach (string element in vpcSecurityGroupMemberships)
{
this.vpcSecurityGroupMemberships.Add(element);
}
return this;
}
// Check to see if VpcSecurityGroupMemberships property is set
internal bool IsSetVpcSecurityGroupMemberships()
{
return this.vpcSecurityGroupMemberships.Count > 0;
}
/// <summary>
/// The option settings to include in an option group.
///
/// </summary>
public List<OptionSetting> OptionSettings
{
get { return this.optionSettings; }
set { this.optionSettings = value; }
}
/// <summary>
/// Adds elements to the OptionSettings collection
/// </summary>
/// <param name="optionSettings">The values to add to the OptionSettings collection </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public OptionConfiguration WithOptionSettings(params OptionSetting[] optionSettings)
{
foreach (OptionSetting element in optionSettings)
{
this.optionSettings.Add(element);
}
return this;
}
/// <summary>
/// Adds elements to the OptionSettings collection
/// </summary>
/// <param name="optionSettings">The values to add to the OptionSettings collection </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public OptionConfiguration WithOptionSettings(IEnumerable<OptionSetting> optionSettings)
{
foreach (OptionSetting element in optionSettings)
{
this.optionSettings.Add(element);
}
return this;
}
// Check to see if OptionSettings property is set
internal bool IsSetOptionSettings()
{
return this.optionSettings.Count > 0;
}
}
}
| |
/// This code was generated by
/// \ / _ _ _| _ _
/// | (_)\/(_)(_|\/| |(/_ v1.0.0
/// / /
/// <summary>
/// PLEASE NOTE that this class contains preview products that are subject to change. Use them with caution. If you
/// currently do not have developer preview access, please contact [email protected].
///
/// DefaultsResource
/// </summary>
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using Twilio.Base;
using Twilio.Clients;
using Twilio.Converters;
using Twilio.Exceptions;
using Twilio.Http;
namespace Twilio.Rest.Autopilot.V1.Assistant
{
public class DefaultsResource : Resource
{
private static Request BuildFetchRequest(FetchDefaultsOptions options, ITwilioRestClient client)
{
return new Request(
HttpMethod.Get,
Rest.Domain.Autopilot,
"/v1/Assistants/" + options.PathAssistantSid + "/Defaults",
queryParams: options.GetParams(),
headerParams: null
);
}
/// <summary>
/// fetch
/// </summary>
/// <param name="options"> Fetch Defaults parameters </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> A single instance of Defaults </returns>
public static DefaultsResource Fetch(FetchDefaultsOptions options, ITwilioRestClient client = null)
{
client = client ?? TwilioClient.GetRestClient();
var response = client.Request(BuildFetchRequest(options, client));
return FromJson(response.Content);
}
#if !NET35
/// <summary>
/// fetch
/// </summary>
/// <param name="options"> Fetch Defaults parameters </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> Task that resolves to A single instance of Defaults </returns>
public static async System.Threading.Tasks.Task<DefaultsResource> FetchAsync(FetchDefaultsOptions options,
ITwilioRestClient client = null)
{
client = client ?? TwilioClient.GetRestClient();
var response = await client.RequestAsync(BuildFetchRequest(options, client));
return FromJson(response.Content);
}
#endif
/// <summary>
/// fetch
/// </summary>
/// <param name="pathAssistantSid"> The SID of the Assistant that is the parent of the resource to fetch </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> A single instance of Defaults </returns>
public static DefaultsResource Fetch(string pathAssistantSid, ITwilioRestClient client = null)
{
var options = new FetchDefaultsOptions(pathAssistantSid);
return Fetch(options, client);
}
#if !NET35
/// <summary>
/// fetch
/// </summary>
/// <param name="pathAssistantSid"> The SID of the Assistant that is the parent of the resource to fetch </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> Task that resolves to A single instance of Defaults </returns>
public static async System.Threading.Tasks.Task<DefaultsResource> FetchAsync(string pathAssistantSid,
ITwilioRestClient client = null)
{
var options = new FetchDefaultsOptions(pathAssistantSid);
return await FetchAsync(options, client);
}
#endif
private static Request BuildUpdateRequest(UpdateDefaultsOptions options, ITwilioRestClient client)
{
return new Request(
HttpMethod.Post,
Rest.Domain.Autopilot,
"/v1/Assistants/" + options.PathAssistantSid + "/Defaults",
postParams: options.GetParams(),
headerParams: null
);
}
/// <summary>
/// update
/// </summary>
/// <param name="options"> Update Defaults parameters </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> A single instance of Defaults </returns>
public static DefaultsResource Update(UpdateDefaultsOptions options, ITwilioRestClient client = null)
{
client = client ?? TwilioClient.GetRestClient();
var response = client.Request(BuildUpdateRequest(options, client));
return FromJson(response.Content);
}
#if !NET35
/// <summary>
/// update
/// </summary>
/// <param name="options"> Update Defaults parameters </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> Task that resolves to A single instance of Defaults </returns>
public static async System.Threading.Tasks.Task<DefaultsResource> UpdateAsync(UpdateDefaultsOptions options,
ITwilioRestClient client = null)
{
client = client ?? TwilioClient.GetRestClient();
var response = await client.RequestAsync(BuildUpdateRequest(options, client));
return FromJson(response.Content);
}
#endif
/// <summary>
/// update
/// </summary>
/// <param name="pathAssistantSid"> The SID of the Assistant that is the parent of the resource to update </param>
/// <param name="defaults"> A JSON string that describes the default task links. </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> A single instance of Defaults </returns>
public static DefaultsResource Update(string pathAssistantSid,
object defaults = null,
ITwilioRestClient client = null)
{
var options = new UpdateDefaultsOptions(pathAssistantSid){Defaults = defaults};
return Update(options, client);
}
#if !NET35
/// <summary>
/// update
/// </summary>
/// <param name="pathAssistantSid"> The SID of the Assistant that is the parent of the resource to update </param>
/// <param name="defaults"> A JSON string that describes the default task links. </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> Task that resolves to A single instance of Defaults </returns>
public static async System.Threading.Tasks.Task<DefaultsResource> UpdateAsync(string pathAssistantSid,
object defaults = null,
ITwilioRestClient client = null)
{
var options = new UpdateDefaultsOptions(pathAssistantSid){Defaults = defaults};
return await UpdateAsync(options, client);
}
#endif
/// <summary>
/// Converts a JSON string into a DefaultsResource object
/// </summary>
/// <param name="json"> Raw JSON string </param>
/// <returns> DefaultsResource object represented by the provided JSON </returns>
public static DefaultsResource FromJson(string json)
{
// Convert all checked exceptions to Runtime
try
{
return JsonConvert.DeserializeObject<DefaultsResource>(json);
}
catch (JsonException e)
{
throw new ApiException(e.Message, e);
}
}
/// <summary>
/// The SID of the Account that created the resource
/// </summary>
[JsonProperty("account_sid")]
public string AccountSid { get; private set; }
/// <summary>
/// The SID of the Assistant that is the parent of the resource
/// </summary>
[JsonProperty("assistant_sid")]
public string AssistantSid { get; private set; }
/// <summary>
/// The absolute URL of the Defaults resource
/// </summary>
[JsonProperty("url")]
public Uri Url { get; private set; }
/// <summary>
/// The JSON string that describes the default task links
/// </summary>
[JsonProperty("data")]
public object Data { get; private set; }
private DefaultsResource()
{
}
}
}
| |
/*********************************************************************
*
* MPFS Generator Library
*
*********************************************************************
* FileName: MPFSlib.cs
* Dependencies: Microsoft .NET Framework 2.0
* Processor: x86
* Complier: Microsoft Visual C# 2008 Express Edition
* Company: Microchip Technology, Inc.
*
* Software License Agreement
*
* This software is owned by Microchip Technology Inc. ("Microchip")
* and is supplied to you for use exclusively as described in the
* associated software agreement. This software is protected by
* software and other intellectual property laws. Any use in
* violation of the software license may subject the user to criminal
* sanctions as well as civil liability. Copyright 2008 Microchip
* Technology Inc. All rights reserved.
*
*
* THE SOFTWARE AND DOCUMENTATION ARE PROVIDED "AS IS" WITHOUT
* WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT
* LIMITATION, ANY WARRANTY OF MERCHANTABILITY, FITNESS FOR A
* PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT SHALL
* MICROCHIP BE LIABLE FOR ANY INCIDENTAL, SPECIAL, INDIRECT OR
* CONSEQUENTIAL DAMAGES, LOST PROFITS OR LOST DATA, COST OF
* PROCUREMENT OF SUBSTITUTE GOODS, TECHNOLOGY OR SERVICES, ANY CLAIMS
* BY THIRD PARTIES (INCLUDING BUT NOT LIMITED TO ANY DEFENSE
* THEREOF), ANY CLAIMS FOR INDEMNITY OR CONTRIBUTION, OR OTHER
* SIMILAR COSTS, WHETHER ASSERTED ON THE BASIS OF CONTRACT, TORT
* (INCLUDING NEGLIGENCE), BREACH OF WARRANTY, OR OTHERWISE.
*
*
* Author Date Comment
*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
* Elliott Wood 4/17/2008 Original
********************************************************************/
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Text;
using System.IO;
using System.IO.Compression;
using System.Text.RegularExpressions;
namespace Microchip
{
public enum MPFSOutputFormat
{
BIN,
C18,
ASM30,
C32,
MDD,
}
public class FileRecord
{
#region Fields
public UInt16 nameHash;
public UInt32 fileRecordOffset;
public UInt32 dynVarCntr=0;
#endregion
public FileRecord(UInt16 nameHash, UInt32 fileRecordOffset,UInt32 dynVarCntr)
{
this.nameHash = nameHash;
this.fileRecordOffset = fileRecordOffset;
this.dynVarCntr = dynVarCntr;
}
}
public abstract class MPFSBuilder
{
#region Fields
protected String Mddpath ;
protected String localPath;
protected String localFile;
protected List<string> log;
protected List<MPFSFileRecord> files;
protected String generatedImageName;
protected bool indexUpdated;
#endregion
#region Properties
/// <summary>
/// Specifies the path for the image file, along with any associated index files
/// </summary>
protected String LocalPath
{
get { return this.localPath; }
set { this.localPath = value; }
}
/// <summary>
/// Specifies the name of the image file to save to the file system
/// </summary>
protected String LocalFile
{
get { return this.localFile; }
set { this.localFile = value; }
}
/// <summary>
/// Retrieves the file name of the most recently generated image
/// </summary>
public String GeneratedImageFileName
{
get { return this.generatedImageName; }
}
/// <summary>
/// Retrieves the log from the last procedure
/// </summary>
public List<string> Log
{
get { return this.log; }
}
/// <summary>
/// Indicates whether or not the index file was updated
/// </summary>
public bool IndexUpdated
{
get { return this.indexUpdated; }
}
#endregion
#region Constructor
/// <summary>
/// Creates a new MPFSBuilder
/// </summary>
public MPFSBuilder()
{
// do nothing
}
#endregion
#region Methods
/// <summary>
/// Adds a file to the MPFS image
/// </summary>
/// <param name="localName">Local file name to read</param>
/// <param name="imageName">Name to use in image file</param>
public abstract bool AddFile(String localName, String imageName);
/// <summary>
/// Recursively adds a directory of files to the image
/// </summary>
/// <param name="dataPath">Local directory name to add</param>
/// <param name="imagePath">Path in MPFS image to add files to</param>
public abstract bool AddDirectory(String dataPath, String imagePath);
/// <summary>
/// Generates the MPFS image and any necessary support files
/// </summary>
public abstract bool Generate(MPFSOutputFormat format);
#endregion
}
public class MPFSClassicBuilder : MPFSBuilder
{
#region Fields
public UInt32 ReserveBlock;
#endregion
#region Constructor
/// <summary>
/// Creates a new MPFS Classic image builder
/// </summary>
/// <param name="localPath">The directory to save the image in</param>
/// <param name="localFile">The output file name for the image</param>
public MPFSClassicBuilder(String localPath, String localFile)
{
if (!localPath.EndsWith("\\"))
localPath += "\\";
this.LocalPath = localPath;
this.LocalFile = localFile;
this.ReserveBlock = 0;
this.log = new List<string>();
this.files = new List<MPFSFileRecord>();
this.indexUpdated = false;
}
#endregion
#region Constants
const byte MPFS_DATA = 0x00;
const byte MPFS_DELETED = 0x01;
const byte MPFS_DLE = 0x03;
const byte MPFS_ETX = 0x04;
String MPFS_C_HEADER =
"/***************************************************************\r\n" +
" * MPFSImg.c\r\n" +
" * Defines an MPFS2 image to be stored in program memory.\r\n" +
" *\r\n" +
" * NOT FOR HAND MODIFICATION\r\n" +
" * This file is automatically generated by the MPFS2 Utility\r\n" +
" * ALL MODIFICATIONS WILL BE OVERWRITTEN BY THE MPFS2 GENERATOR\r\n" +
" * Generated " + DateTime.Now.ToLongDateString() + " " + DateTime.Now.ToLongTimeString() + "\r\n" +
" ***************************************************************/\r\n" +
"\r\n" +
"#define __MPFSIMG_C\r\n" +
"\r\n" +
"#include \"TCPIP Stack/TCPIP.h\"\r\n" +
"\r\n" +
"#if defined(STACK_USE_MPFS) && !defined(MPFS_USE_EEPROM) && !defined(MPFS_USE_SPI_FLASH)\r\n" +
"\r\n";
String MPFS_C_FOOTER =
"/**************************************************************\r\n" +
" * End of MPFS\r\n" +
" **************************************************************/\r\n" +
"#endif // #if defined(STACK_USE_MPFS) && !defined(MPFS_USE_EEPROM) && !defined(MPFS_USE_SPI_FLASH)" +
"\r\n\r\n";
String MPFS_ASM_HEADER =
";**************************************************************\r\n" +
"; MPFSImg.s\r\n" +
"; Defines an MPFS2 image to be stored in program memory.\r\n" +
"; Defined in ASM30 assembly for optimal storage size.\r\n" +
";\r\n" +
"; NOT FOR HAND MODIFICATION\r\n" +
"; This file is automatically generated by the MPFS2 Utility\r\n" +
"; ALL MODIFICATIONS WILL BE OVERWRITTEN BY THE MPFS2 GENERATOR\r\n" +
"; Generated " + DateTime.Now.ToLongDateString() + " " + DateTime.Now.ToLongTimeString() + "\r\n" +
";**************************************************************\r\n\r\n" +
".equ VALID_ID,0\r\n" +
".ifdecl __dsPIC30F\r\n" +
" .include \"p30fxxxx.inc\"\r\n" +
".endif\r\n" +
".ifdecl __dsPIC33F\r\n" +
" .include \"p33fxxxx.inc\"\r\n" +
".endif\r\n" +
".ifdecl __PIC24H\r\n" +
" .include \"p24hxxxx.inc\"\r\n" +
".endif\r\n" +
".ifdecl __PIC24F\r\n" +
" .include \"p24fxxxx.inc\"\r\n" +
".endif\r\n" +
".if VALID_ID <> 1\r\n" +
" .error \"Processor ID not specified in generic include files. New ASM30 assembler needs to be downloaded?\"\r\n" +
".endif\r\n" +
" .text\r\n" +
" .section MPFSData,code\r\n\r\n" +
" goto END_OF_MPFS ; Prevent accidental execution of constant data.\r\n" +
" .global BEGIN_MPFS\r\n" +
"BEGIN_MPFS:\r\n";
String MPFS_ASM_FOOTER = "\r\n\r\n; End of Generated Image\r\n";
#endregion
#region Public Methods
/// <summary>
/// Adds a file to the MPFS image
/// </summary>
/// <param name="localName">Local file name to read</param>
/// <param name="imageName">Name to use in image file</param>
public override bool AddFile(String localName, String imageName)
{
// Skip if can't be opened
if (!File.Exists(localName))
{
log.Add("\r\nERROR: Could not read " + localName);
return false;
}
// Set up the new file record
MPFSFileRecord newFile = new MPFSFileRecord();
newFile.FileName = imageName;
// Read the data in, escaping as it is read
byte b;
List<byte> data = new List<byte>(1024);
FileStream fs = new FileStream(localName, FileMode.Open, FileAccess.Read);
BinaryReader fin = new BinaryReader(fs);
for (int i = 0; i < fs.Length; i++)
{
if(data.Count == data.Capacity)
data.Capacity *= 2;
b = fin.ReadByte();
if (b == MPFS_DLE || b == MPFS_ETX)
data.Add(MPFS_DLE);
data.Add(b);
}
fin.Close();
newFile.data = data.ToArray();
// Add the file and return
log.Add(" " + imageName + ": " + newFile.data.Length + " bytes");
files.Add(newFile);
return true;
}
/// <summary>
/// Adds a directory to the MPFS image. All non-hidden files will be included.
/// </summary>
/// <param name="dataPath">The local directory to search</param>
/// <param name="imagePath">Ignored for MPFS Classic</param>
/// <returns></returns>
public override bool AddDirectory(String dataPath, String imagePath)
{
// Make sure directory exists
if (!Directory.Exists(dataPath))
{
log.Add("\r\nERROR: Directory " + dataPath + " does not exist.");
return false;
}
// Make sure directory is not the project directory
if (this.localPath.Contains(dataPath))
{
log.Add("\r\nERROR: The project directory is located in the source " +
"directory. The generator cannot run if the image is to be placed " +
"in the source directory. Please select the base MPLAB project " +
"directory before continuing.");
return false;
}
// Load directory members
DirectoryInfo dir = new DirectoryInfo(dataPath);
FileInfo[] filelist = dir.GetFiles();
log.Add(dataPath + " :");
// Add all sub files
for (int i = 0; i < filelist.Length; i++)
if ((filelist[i].Attributes & FileAttributes.Hidden) != FileAttributes.Hidden)
this.AddFile(filelist[i].FullName, imagePath + filelist[i].Name);
return true;
}
public override bool Generate(MPFSOutputFormat format)
{
// Start with nothing
generatedImageName = null;
// Make sure all paths exist
if (!Directory.Exists(localPath))
{
log.Add("\r\nERROR: Output directory \"" + localPath + "\" does not exist!");
return false;
}
// Make sure we have some files
if(files.Count == 0)
return false;
// Generate based on format
try
{
switch (format)
{
case MPFSOutputFormat.BIN:
return GenerateBIN(localPath + localFile);
case MPFSOutputFormat.C18:
case MPFSOutputFormat.C32:
return GenerateC(localPath + localFile);
case MPFSOutputFormat.ASM30:
return GenerateASM(localPath + localFile);
default:
log.Add("\r\nERROR: Invalid output format was specified.");
return false;
}
}
catch (Exception e)
{
log.Add("\r\nERROR: " + e.Message);
return false;
}
}
private bool GenerateBIN(String filename)
{
// Open the file
if (!filename.EndsWith(".bin", StringComparison.OrdinalIgnoreCase))
filename += ".bin";
BinaryWriter fout = new BinaryWriter(new FileStream(filename, FileMode.Create), Encoding.ASCII);
// Write the FAT data
UInt32 baseAddr = ReserveBlock + 17 * ((UInt32)files.Count + 1);
foreach (MPFSFileRecord file in files)
{
fout.Write(MPFS_DATA);
fout.Write((byte)(baseAddr));
fout.Write((byte)(baseAddr >> 8));
fout.Write((byte)(baseAddr >> 16));
fout.Write((byte)(baseAddr >> 24));
fout.Write(NormalizeFileName(file.FileName).ToCharArray());
baseAddr += (UInt32)file.data.Length + 5;
}
fout.Write(MPFS_ETX);
fout.Write((uint)0xffffffff);
fout.Write("END OF FAT ".ToCharArray());
// Write the files
foreach (MPFSFileRecord file in files)
{
fout.Write(file.data);
fout.Write(MPFS_ETX);
fout.Write((uint)0xffffffff);
}
// Flush the output and store the file name
fout.Flush();
fout.Close();
generatedImageName = filename;
return true;
}
private bool GenerateC(String filename)
{
// Open the file
if (!filename.EndsWith(".c", StringComparison.OrdinalIgnoreCase))
filename += ".c";
StreamWriter fout = new StreamWriter(filename, false, Encoding.ASCII);
fout.Write(MPFS_C_HEADER);
// Write the files
int fileIndex = 0;
foreach (MPFSFileRecord file in files)
{
fout.Write("\r\n/*******************************\r\n * Begin ");
fout.Write(NormalizeFileName(file.FileName));
fout.Write("\r\n ******************************/\r\nstatic ROM unsigned char MPFS_");
fout.Write(Convert.ToString(fileIndex++, 16).PadLeft(4, '0') + "[] = \r\n{");
for (int i = 0; i < file.data.Length; i++)
{
if (i % 12 == 0)
fout.Write("\r\n\t");
fout.Write("0x" + Convert.ToString(file.data[i], 16).PadLeft(2, '0') + ",");
}
fout.Write("\r\n\t0x04,0xff,0xff,0xff\r\n};\r\n");
}
// Write the FAT
fileIndex = 0;
fout.Write(
"/**************************************************\r\n" +
" * Start of MPFS FAT\r\n" +
" **************************************************/\r\n" +
"typedef struct\r\n" +
"{\r\n" +
" unsigned char Flags;\r\n" +
" ROM unsigned char* Address;\r\n" +
" unsigned char Name[12];\r\n" +
"} FAT_TABLE_ENTRY;\r\n" +
"\r\n" +
"ROM FAT_TABLE_ENTRY MPFS_Start[] = \r\n" +
"{"
);
foreach (MPFSFileRecord file in files)
{
fout.Write("\r\n\t{ 0x00, MPFS_" + Convert.ToString(fileIndex++, 16).PadLeft(4, '0'));
foreach (byte b in NormalizeFileName(file.FileName))
{
fout.Write(", '" + (char)b + "'");
}
fout.Write(" },");
}
fout.Write(
"\r\n\t{ 0x04, (ROM unsigned char*)0xffffff, 'E', 'N', 'D', ' ', 'O', 'F', ' ', 'F', 'A', 'T', ' ', ' ' },\r\n" +
"};\r\n" +
"/**************************************************\r\n" +
" * End of MPFS FAT\r\n" +
" **************************************************/\r\n\r\n"
);
fout.Write(MPFS_C_FOOTER);
// Flush the output and store the file name
fout.Flush();
fout.Close();
generatedImageName = filename;
return true;
}
private bool GenerateASM(String filename)
{
// Open the file
if (!filename.EndsWith(".s", StringComparison.OrdinalIgnoreCase))
filename += ".s";
StreamWriter fout = new StreamWriter(filename, false, Encoding.ASCII);
fout.Write(MPFS_ASM_HEADER);
// Write the files
int fileIndex = 0;
foreach (MPFSFileRecord file in files)
{
fout.Write("\r\n;*******************************\r\n; Begin ");
fout.Write(NormalizeFileName(file.FileName));
fout.Write("\r\n;*******************************\r\n" +
"\tgoto\tEND_OF_MPFS_");
fout.Write(Convert.ToString(fileIndex, 16).PadLeft(4, '0'));
fout.Write("\t\t; Prevent accidental execution of constant data\r\n\t.global _MPFS_");
fout.Write(Convert.ToString(fileIndex, 16).PadLeft(4, '0'));
fout.Write("\r\n_MPFS_");
fout.Write(Convert.ToString(fileIndex, 16).PadLeft(4, '0'));
fout.Write(":");
for (int i = 0; i < file.data.Length; i++)
{
if (i % 12 == 0)
fout.Write("\r\n\t.pbyte\t");
fout.Write("0x" + Convert.ToString(file.data[i], 16).PadLeft(2, '0'));
if (i % 12 != 11 && i != file.data.Length-1)
fout.Write(",");
}
fout.Write("\r\n\t.pbyte\t0x04,0xff,0xff,0xff,0xff\r\nEND_OF_MPFS_");
fout.Write(Convert.ToString(fileIndex++, 16).PadLeft(4, '0'));
fout.Write(":\r\n");
}
// Write the FAT
fileIndex = 0;
fout.Write(
";*************************************************\r\n" +
"; Start of MPFS FAT\r\n" +
";*************************************************\r\n" +
"\t.section\t.const,psv\r\n" +
"\t.global _MPFS_Start\r\n" +
"_MPFS_Start:"
);
foreach (MPFSFileRecord file in files)
{
fout.Write("\r\n\t.byte\t0x00,0x00\r\n\t.long\tpaddr(_MPFS_");
fout.Write(Convert.ToString(fileIndex++, 16).PadLeft(4, '0'));
fout.Write(")\r\n\t.byte\t");
int i = 0;
foreach (byte b in NormalizeFileName(file.FileName))
{
fout.Write("'" + (char)b + "'");
if (++i < 12)
fout.Write(",");
}
}
fout.Write(
"\r\n\t.byte\t0x04,0x00\r\n\t.long\t0xffffffff" +
"\r\n\t.byte\t'E','N','D',' ','O','F',' ','F','A','T',' ',' '\r\n\r\n" +
"\t.section MPFSEnd,code\r\n" +
"END_OF_MPFS:\r\n"
);
fout.Write(MPFS_ASM_FOOTER);
// Flush the output and store the file name
fout.Flush();
fout.Close();
generatedImageName = filename;
return true;
}
private String NormalizeFileName(String name)
{
if (name.Length > 12)
name = name.Substring(0, 12);
return name.PadRight(12).ToUpper();
}
#endregion
}
public class MPFS2Builder : MPFSBuilder
{
#region Fields
private Collection<String> dynamicTypes;
private Collection<String> nonGZipTypes;
private DynamicVariableParser dynVarParser;
#endregion
#region Constants
private const UInt16 MPFS2_FLAG_ISZIPPED = 0x0001;
private const UInt16 MPFS2_FLAG_HASINDEX = 0x0002;
#endregion
#region Constructor
/// <summary>
/// Creates a new MPFS2 image builder
/// </summary>
/// <param name="localPath">The directory to save the image in, and to read/write index files</param>
/// <param name="localFile">The output file name for the image</param>
public MPFS2Builder(String localPath, String localFile)
{
if (!localPath.EndsWith("\\"))
localPath += "\\";
this.LocalPath = localPath;
this.LocalFile = localFile;
this.dynamicTypes = new Collection<string>();
this.nonGZipTypes = new Collection<string>();
this.log = new List<string>();
this.files = new List<MPFSFileRecord>();
this.dynVarParser = new DynamicVariableParser(localPath);
this.indexUpdated = false;
}
#endregion
#region Properties
/// <summary>
/// Sets a comma-separated list of types to be considered dynamic
/// </summary>
public string DynamicTypes
{
set
{
Array strings = value.Split(',');
dynamicTypes.Clear();
foreach (String s in strings)
{
String s_trimmed = s.Replace('*', ' ').Trim();
if (s_trimmed.Length > 0)
this.dynamicTypes.Add(s_trimmed);
}
}
}
/// <summary>
/// Sets a comma-separated list of types not to be compressed
/// </summary>
public string NonGZipTypes
{
set
{
Array strings = value.Split(',');
nonGZipTypes.Clear();
foreach (String s in strings)
{
String s_trimmed = s.Replace('*',' ').Trim();
if (s_trimmed.Length > 0)
this.nonGZipTypes.Add(s_trimmed);
}
}
}
#endregion
#region Public Methods
/// <summary>
/// Adds a file to the MPFS image
/// </summary>
/// <param name="localName">Local file name to read</param>
/// <param name="imageName">Name to use in image file</param>
public override bool AddFile(String localName, String imageName)
{
// Skip if can't be opened
if (!File.Exists(localName))
{
log.Add("\r\nERROR: Could not read " + localName);
return false;
}
// Set up the new file record
MPFSFileRecord newFile = new MPFSFileRecord();
newFile.FileName = imageName;
newFile.fileDate = File.GetLastWriteTime(localName);
// Read the data in
FileStream fs = new FileStream(localName, FileMode.Open, FileAccess.Read);
BinaryReader fin = new BinaryReader(fs);
newFile.data = fin.ReadBytes((int)fs.Length);
fin.Close();
// Parse the file if necessary
MPFSFileRecord idxFile = null;
if (this.FileMatches(localName, this.dynamicTypes))
{
idxFile = dynVarParser.Parse(newFile);
}
// GZip the file if possible
int gzipRatio = 0;
if (idxFile == null && !this.FileMatches(localName, this.nonGZipTypes))
{
MemoryStream ms = new MemoryStream();
GZipStream gz = new GZipStream(ms, CompressionMode.Compress, true);
gz.Write(newFile.data, 0, newFile.data.Length);
gz.Flush();
gz.Close();
// Only use zipped copy if it's smaller
if (ms.Length < newFile.data.Length)
{
gzipRatio = (int)(100 - (100 * ms.Length / newFile.data.Length));
newFile.data = ms.ToArray();
newFile.isZipped = true;
}
}
// Add the file and return
if (idxFile == null)
{
log.Add(" " + imageName + ": " + newFile.data.Length + " bytes" +
((gzipRatio > 0) ? " (gzipped by " + gzipRatio + "%)" : ""));
files.Add(newFile);
}
else
{
log.Add(" " + imageName + ": " + newFile.data.Length + " bytes, " + (idxFile.data.Length / 8) + " vars");
newFile.hasIndex = true;
files.Add(newFile);
files.Add(idxFile);
}
return true;
}
/// <summary>
/// Recursively adds a directory to the MPFS image. All non-hidden files will be included.
/// </summary>
/// <param name="dataPath">The local directory to search</param>
/// <param name="imagePath">The base directory this folder is in the MPFS2 image</param>
/// <returns></returns>
public override bool AddDirectory(String dataPath, String imagePath)
{
// Make sure directory exists
if (!Directory.Exists(dataPath))
{
log.Add("\r\nERROR: Directory " + dataPath + " does not exist.");
return false;
}
// Make sure directory is not the project directory
if (this.localPath.Contains(dataPath))
{
log.Add("\r\nERROR: The project directory is located in the source " +
"directory. The generator cannot run if the image is to be placed " +
"in the source directory. Please select the base MPLAB project " +
"directory before continuing.");
return false;
}
// Load directory members
DirectoryInfo dir = new DirectoryInfo(dataPath);
FileInfo[] filelist = dir.GetFiles();
DirectoryInfo[] subdirs = dir.GetDirectories();
log.Add(dataPath + " :");
// Add all sub files
for (int i = 0; i < filelist.Length; i++)
if ((filelist[i].Attributes & FileAttributes.Hidden) != FileAttributes.Hidden)
this.AddFile(filelist[i].FullName, imagePath + filelist[i].Name);
// Add all subdirectories
for (int i = 0; i < subdirs.Length; i++)
if((subdirs[i].Attributes & FileAttributes.Hidden) != FileAttributes.Hidden)
this.AddDirectory(subdirs[i].FullName, imagePath + subdirs[i].Name + "/");
return true;
}
/// <summary>
/// Generates an image in the specified format
/// </summary>
/// <param name="format">One of the MPFSOutputFormat constants indicating the format</param>
/// <returns>true if generation was successful, false otherwise</returns>
public override bool Generate(MPFSOutputFormat format)
{
// Start with nothing as the output name
generatedImageName = null;
// Make sure all paths exist
if (!Directory.Exists(localPath))
{
log.Add("\r\nERROR: Output directory \"" + localPath + "\" does not exist!");
return false;
}
// Make sure we have some files
if (files.Count == 0)
return false;
try
{
// Write any index files that have changed
indexUpdated = dynVarParser.WriteIndices();
}
catch (Exception e)
{
log.Add("ERROR: " + e.Message);
return false;
}
// Determine address of each file and string
UInt32 numFiles = (UInt32)files.Count;
UInt32 lenHeader = 8;
UInt32 lenHashes = 2 * numFiles;
UInt32 lenFAT = 22 * numFiles;
UInt32 baseAddr = lenHeader + lenHashes + lenFAT;
UInt32 counter=0;
UInt32 loopCntr=0;
UInt32 numFileRecrds = 0;
foreach (MPFSFileRecord file in files)
{
file.locStr = baseAddr;
baseAddr += (UInt32)file.FileName.Length + 1;
}
foreach (MPFSFileRecord file in files)
{
file.locData = baseAddr;
baseAddr += (UInt32)file.data.Length;
}
// Set up the writer
try
{
MPFS2Writer w;
switch (format)
{
case MPFSOutputFormat.C18:
case MPFSOutputFormat.C32:
w = new MPFS2C18Writer(localPath + localFile);
WriteImage(w);
break;
case MPFSOutputFormat.ASM30:
w = new MPFS2ASM30Writer(localPath + localFile);
WriteImage(w);
break;
case MPFSOutputFormat.MDD:
MDDWriter(localPath);
break;
default:
w = new MPFS2BINWriter(localPath + localFile);
WriteImage(w);
break;
}
}
catch (Exception e)
{
log.Add("\r\nERROR: " + e.Message);
return false;
}
return true;
}
#endregion
private void WriteImage(MPFS2Writer x)
{
MPFS2Writer w;
w = x;
// Write the image
w.Write("MPFS");
w.Write((byte)0x02);
w.Write((byte)0x01);
w.Write((UInt16)files.Count);
foreach (MPFSFileRecord file in files)
w.Write((UInt16)file.nameHash);
UInt16 flags;
foreach (MPFSFileRecord file in files)
{
w.Write(file.locStr);
w.Write(file.locData);
w.Write((UInt32)file.data.Length);
w.Write((UInt32)((file.fileDate.ToUniversalTime().Ticks - 621355968000000000) / 10000000));
w.Write((UInt32)0);
flags = 0;
if (file.hasIndex)
flags |= MPFS2_FLAG_HASINDEX;
if (file.isZipped)
flags |= MPFS2_FLAG_ISZIPPED;
w.Write(flags);
}
foreach (MPFSFileRecord file in files)
{
w.Write(file.FileName);
w.Write((byte)0x00);
}
foreach (MPFSFileRecord file in files)
w.Write(file.data);
w.Close();
generatedImageName = w.imageName;
log.Add("\r\nGENERATED MPFS2 IMAGE: " + w.ImageLength + " bytes");
}
private class FilesRecordWriter : BinaryWriter
{
#region Fields
protected BinaryWriter fout;
public int ImageLength = 0;
#endregion
public FilesRecordWriter(String DataPath)
{
String filename = "FileRcrd.bin";
string newPath = System.IO.Path.Combine(DataPath, filename);
if (!filename.EndsWith(".bin", StringComparison.OrdinalIgnoreCase))
filename += ".bin";
fout = new BinaryWriter(new FileStream(newPath, FileMode.Create), Encoding.ASCII);
}
public void Write(byte data)
{
fout.Write(data);
ImageLength++;
}
public void Close()
{
fout.Close();
}
}
private class DynamicVarRecordWriter : BinaryWriter
{
#region Fields
protected BinaryWriter fout;
#endregion
public DynamicVarRecordWriter(String DataPath)
{
String filename = "DynRcrd.bin";
//Create a new subfolder under the current active folder
string newPath = System.IO.Path.Combine(DataPath, filename);
if (!filename.EndsWith(".bin", StringComparison.OrdinalIgnoreCase))
filename += ".bin";
//BinaryWriter fout = new BinaryWriter(new FileStream(filename, FileMode.Create), Encoding.ASCII);
fout = new BinaryWriter(new FileStream(newPath, FileMode.Create), Encoding.ASCII);
}
//public override void Write(byte data)
public void Write(byte data)
{
fout.Write(data);
}
//public override void Close()
public void Close()
{
fout.Close();
}
}
//public bool MDDWriter(String localPath)
public void MDDWriter(String localPath)
{
FilesRecordWriter FileRecrd /*Files with dynamic variables Record*/;
//RecordWriter DynVarRecrd /*Dynamic Variables Record of each file*/;
DynamicVarRecordWriter DynVarRecrd /*Dynamic Variables Record of each file*/;
UInt32 counter = 0;
UInt32 loopCntr = 0;
UInt32 numFileRecrds = 0;
FileRecrd = new FilesRecordWriter(localPath);
DynVarRecrd = new DynamicVarRecordWriter(localPath);
UInt16 flags;
List<FileRecord> FileRcrdList = new List<FileRecord>();
foreach (MPFSFileRecord file in files)
{
counter=0;
loopCntr=0;
if(file.dynVarCntr >0)
{
FileRcrdList.Add(new FileRecord ((UInt16)file.nameHash,
(UInt32)file.fileRecordOffset,
(UInt32)file.dynVarCntr));
numFileRecrds++;
DynVarRecrd.Write((byte)(file.fileRecordLength));
DynVarRecrd.Write((byte)(file.fileRecordLength>>8));
DynVarRecrd.Write((byte)(file.fileRecordLength>>16));
DynVarRecrd.Write((byte)(file.fileRecordLength>>24));
flags = 0;
if (file.hasIndex)
flags |= MPFS2_FLAG_HASINDEX;
if (file.isZipped)
flags |= MPFS2_FLAG_ISZIPPED;
DynVarRecrd.Write((byte)(flags));
DynVarRecrd.Write((byte)(flags>>8));
/* loopCntr = (UInt16)file.FileName.Length;
flags = 0x00;
while (loopCntr != (UInt32)flags)
{
DynVarRecrd.Write((byte)file.FileName[flags]);
flags += 1;
}
*/
loopCntr=0;
while(loopCntr!=file.dynVarCntr)
{
DynVarRecrd.Write((byte)(file.dynVarOffsetAndIndexID[0+counter]));
DynVarRecrd.Write((byte)(file.dynVarOffsetAndIndexID[1+counter]));
DynVarRecrd.Write((byte)(file.dynVarOffsetAndIndexID[2+counter]));
DynVarRecrd.Write((byte)(file.dynVarOffsetAndIndexID[3+counter]));
DynVarRecrd.Write((byte)(file.dynVarOffsetAndIndexID[4 + counter]));
DynVarRecrd.Write((byte)(file.dynVarOffsetAndIndexID[5 + counter]));
DynVarRecrd.Write((byte)(file.dynVarOffsetAndIndexID[6 + counter]));
DynVarRecrd.Write((byte)(file.dynVarOffsetAndIndexID[7 + counter]));
counter+=8;
loopCntr+=1;
}
}
}
FileRcrdList.Sort(delegate(FileRecord FR1, FileRecord FR2)
{
return FR1.nameHash.CompareTo(FR2.nameHash);
}
);
FileRecrd.Write((byte)(numFileRecrds));
FileRecrd.Write((byte)(numFileRecrds>>8));
FileRecrd.Write((byte)(numFileRecrds>>16));
FileRecrd.Write((byte)(numFileRecrds>>24));
FileRcrdList.ForEach(delegate(FileRecord FR)
{
FileRecrd.Write((byte)(FR.nameHash));
FileRecrd.Write((byte)(FR.nameHash>>8));
FileRecrd.Write((byte)(FR.fileRecordOffset));
FileRecrd.Write((byte)(FR.fileRecordOffset>>8));
FileRecrd.Write((byte)(FR.fileRecordOffset>>16));
FileRecrd.Write((byte)(FR.fileRecordOffset>>24));
FileRecrd.Write((byte)(FR.dynVarCntr));
FileRecrd.Write((byte)(FR.dynVarCntr>>8));
FileRecrd.Write((byte)(FR.dynVarCntr>>16));
FileRecrd.Write((byte)(FR.dynVarCntr>>24));
}
);
log.Add("\r\nGENERATED MPFS2 IMAGE: " + FileRecrd.ImageLength + " bytes");
FileRecrd.Close();
DynVarRecrd.Close();
}
#region Private Methods
private bool FileMatches(String fileName, Collection<String> endings)
{
foreach(String end in endings)
if(fileName.EndsWith(end))
return true;
return false;
}
#endregion
#region Writer Classes
private abstract class MPFS2Writer
{
public int ImageLength = 0;
public string imageName;
public abstract void Write(byte data);
public abstract void Close();
public void Write(byte[] data)
{
foreach (byte b in data)
Write(b);
}
public void Write(String data)
{
foreach (byte b in data)
Write(b);
}
public void Write(UInt16 data)
{
Write((byte)(data));
Write((byte)(data >> 8));
}
public void Write(UInt32 data)
{
Write((byte)(data));
Write((byte)(data >> 8));
Write((byte)(data >> 16));
Write((byte)(data >> 24));
}
}
private class MPFS2BINWriter : MPFS2Writer
{
#region Fields
protected BinaryWriter fout;
#endregion
public MPFS2BINWriter(String filename)
{
if (!filename.EndsWith(".bin", StringComparison.OrdinalIgnoreCase))
filename += ".bin";
fout = new BinaryWriter(new FileStream(filename, FileMode.Create), Encoding.ASCII);
imageName = filename;
}
public override void Write(byte data)
{
ImageLength++;
fout.Write(data);
}
public override void Close()
{
fout.Flush();
fout.Close();
}
}
private class MPFS2C18Writer : MPFS2Writer
{
#region Fields
protected StreamWriter fout;
protected string ASCIILine;
#endregion
public MPFS2C18Writer(String filename)
{
if (!filename.EndsWith(".c", StringComparison.OrdinalIgnoreCase))
filename += ".c";
fout = new StreamWriter(filename, false, Encoding.ASCII);
imageName = filename;
fout.Write(
"/***************************************************************\r\n" +
" * MPFSImg2.c\r\n" +
" * Defines an MPFS2 image to be stored in program memory.\r\n" +
" *\r\n" +
" * NOT FOR HAND MODIFICATION\r\n" +
" * This file is automatically generated by the MPFS2 Utility\r\n" +
" * ALL MODIFICATIONS WILL BE OVERWRITTEN BY THE MPFS2 GENERATOR\r\n" +
" * Generated " + DateTime.Now.ToLongDateString() + " " + DateTime.Now.ToLongTimeString() + "\r\n" +
" ***************************************************************/\r\n" +
"\r\n#define __MPFSIMG2_C\r\n\r\n" +
"#include \"TCPIPConfig.h\"\r\n" +
"#if !defined(MPFS_USE_EEPROM) && !defined(MPFS_USE_SPI_FLASH)\r\n\r\n" +
"#include \"TCPIP Stack/TCPIP.h\"\r\n" +
"#if defined(STACK_USE_MPFS2)\r\n\r\n" +
"\r\n" +
"/**************************************\r\n" +
" * MPFS2 Image Data\r\n" +
" **************************************/"
);
}
public override void Write(byte data)
{
char ASCIIdata;
ASCIIdata = '.';
if (data >= 32 && data <= 126 && data != '*') // * cannot be displayed because it would open the possibility of */ occuring in the sequence, which would mess up our block comment
ASCIIdata = (char)data;
if (ImageLength % 1024 == 0)
ASCIILine = " " + ASCIILine;
else
fout.Write(",");
if (ImageLength % 16 == 0)
{
if (ImageLength != 0)
fout.Write(ASCIILine + " */");
ASCIILine = " /* ";
}
if (ImageLength % 1024 == 0)
fout.Write("\r\n#define DATACHUNK" + Convert.ToString((ImageLength / 1024), 16).PadLeft(6, '0'));
if (ImageLength % 16 == 0)
fout.Write(" \\\r\n\t");
ASCIILine += ASCIIdata.ToString();
fout.Write("0x" + Convert.ToString(data, 16).PadLeft(2, '0'));
ImageLength++;
}
public override void Close()
{
if (ImageLength % 16 != 0)
fout.Write("".PadLeft((16-(ImageLength % 16))*5+1, ' ') + ASCIILine.PadRight(20) + " */");
fout.Write("\r\n\r\n\r\n");
if (ImageLength != 0)
{
fout.Write("/**************************************\r\n" +
" * MPFS2 C linkable symbols\r\n" +
" **************************************/\r\n" +
"// For C18, these are split into seperate arrays because it speeds up compilation a lot. \r\n" +
"// For other compilers, the entire data array must be defined as a single variable to \r\n" +
"// ensure that the linker does not reorder the data chunks in Flash when compiler \r\n" +
"// optimizations are turned on.\r\n" +
"#if defined(__18CXX)\r\n" +
"\tROM BYTE MPFS_Start[] = {DATACHUNK000000};\r\n");
for (UInt32 i = 1024; i < ImageLength; i += 1024)
{
fout.Write("\tROM BYTE MPFS_" + Convert.ToString((i / 1024), 16).PadLeft(6, '0') + "[] = {DATACHUNK"+Convert.ToString((i / 1024), 16).PadLeft(6, '0')+ "};\r\n");
}
fout.Write("#else\r\n" +
"\tROM BYTE MPFS_Start[] = {");
for (UInt32 i = 0; i < ImageLength; i += 1024)
{
fout.Write("DATACHUNK" + Convert.ToString((i / 1024), 16).PadLeft(6, '0'));
if (i + 1024 < ImageLength)
fout.Write(", ");
}
fout.Write("};\r\n" +
"#endif\r\n\r\n\r\n");
}
fout.Write(
"/**************************************************************\r\n" +
" * End of MPFS\r\n" +
" **************************************************************/\r\n" +
"#endif // #if defined(STACK_USE_MPFS2)\r\n" +
"#endif // #if !defined(MPFS_USE_EEPROM) && !defined(MPFS_USE_SPI_FLASH)\r\n"
);
fout.Flush();
fout.Close();
}
}
private class MPFS2ASM30Writer : MPFS2Writer
{
#region Fields
protected StreamWriter fout;
#endregion
public MPFS2ASM30Writer(String filename)
{
if (!filename.EndsWith(".s",StringComparison.OrdinalIgnoreCase))
filename += ".s";
fout = new StreamWriter(filename, false, Encoding.ASCII);
imageName = filename;
fout.Write(
";**************************************************************\r\n" +
"; MPFSImg2.s\r\n" +
"; Defines an MPFS2 image to be stored in program memory.\r\n" +
"; Defined in ASM30 assembly for optimal storage size.\r\n" +
";\r\n" +
"; NOT FOR HAND MODIFICATION\r\n" +
"; This file is automatically generated by the MPFS2 Utility\r\n" +
"; ALL MODIFICATIONS WILL BE OVERWRITTEN BY THE MPFS2 GENERATOR\r\n" +
"; Generated " + DateTime.Now.ToLongDateString() + " " + DateTime.Now.ToLongTimeString() + "\r\n" +
";**************************************************************\r\n\r\n" +
".equ VALID_ID,0\r\n" +
".ifdecl __dsPIC30F\r\n" +
" .include \"p30fxxxx.inc\"\r\n" +
".endif\r\n" +
".ifdecl __dsPIC33F\r\n" +
" .include \"p33fxxxx.inc\"\r\n" +
".endif\r\n" +
".ifdecl __PIC24H\r\n" +
" .include \"p24hxxxx.inc\"\r\n" +
".endif\r\n" +
".ifdecl __PIC24F\r\n" +
" .include \"p24fxxxx.inc\"\r\n" +
".endif\r\n" +
".if VALID_ID <> 1\r\n" +
" .error \"Processor ID not specified in generic include files. New ASM30 assembler needs to be downloaded?\"\r\n" +
".endif\r\n" +
" .text\r\n" +
" .section MPFSData,code\r\n\r\n" +
" goto END_OF_MPFS ; Prevent accidental execution of constant data.\r\n" +
" .global BEGIN_MPFS\r\n" +
"BEGIN_MPFS:"
);
}
public override void Write(byte data)
{
if (ImageLength % 12 == 0)
fout.Write("\r\n\t.pbyte\t");
fout.Write("0x" + Convert.ToString(data, 16).PadLeft(2, '0'));
ImageLength++;
if(ImageLength % 12 != 0)
fout.Write(",");
}
public override void Close()
{
if (ImageLength % 12 == 0)
fout.Write(",");
fout.Write(
"0x00\r\n" +
"END_OF_MPFS:\r\n\r\n" +
" .section .const,psv\r\n" +
" .global _MPFS_Start\r\n" +
"_MPFS_Start:\r\n" +
" .long paddr(BEGIN_MPFS)\r\n\r\n" +
" .section MPFSHelpers,code\r\n\r\n" +
" .global _ReadProgramMemory\r\n" +
"_ReadProgramMemory:\r\n" +
" push _TBLPAG\r\n" +
" mov w1,_TBLPAG\r\n" +
" mov w0,w5\r\n" +
" tblrdl [w5],w0\r\n" +
" tblrdh [w5],w1\r\n" +
" pop _TBLPAG\r\n" +
" return\r\n"
);
fout.Flush();
fout.Close();
}
}
#endregion
}
public class MPFSFileRecord
{
#region Fields
private String fileName;
public UInt16 nameHash;
public DateTime fileDate;
public byte[] data;
public UInt32 locStr;
public UInt32 locData;
public bool hasIndex;
public bool isIndex;
public bool isZipped;
public UInt32 dynVarCntr=0;/*Number of Dynamic Variables in the file*/
public byte[] dynVarOffsetAndIndexID = new byte[0];/*Location of dynamic var and its ID*/
public UInt32 fileRecordOffset;/* Byte location in the Record file where this file record/information is written from*/
public UInt32 fileRecordLength;/* Total length/number of bytes in this file record*/
#endregion
#region Constructor
/// <summary>
/// Sets up a new MPFSFileRecord
/// </summary>
public MPFSFileRecord()
{
locStr = 0;
locData = 0;
hasIndex = false;
isIndex = false;
isZipped = false;
dynVarCntr=0;
}
#endregion
public String FileName
{
get { return this.fileName; }
set
{
this.fileName = value;
if(value == "")
this.nameHash = 0xffff;
else
{
this.nameHash = 0;
foreach (byte b in value)
{
nameHash += b;
nameHash <<= 1;
}
}
}
}
}
}
|