context stringlengths 2.52k 185k | gt stringclasses 1
value |
|---|---|
namespace System.IO.Compression {
using System;
using System.Diagnostics;
// This class decodes GZip header and footer information.
// See RFC 1952 for details about the format.
internal class GZipDecoder : IFileFormatReader {
private GzipHeaderState gzipHeaderSubstate;
private GzipHeaderState gzipFooterSubstate;
private int gzip_header_flag;
private int gzip_header_xlen;
private uint expectedCrc32;
private uint expectedOutputStreamSizeModulo;
private int loopCounter;
private uint actualCrc32;
private long actualStreamSizeModulo;
public GZipDecoder() {
Reset();
}
public void Reset() {
gzipHeaderSubstate = GzipHeaderState.ReadingID1;
gzipFooterSubstate = GzipHeaderState.ReadingCRC;
expectedCrc32 = 0;
expectedOutputStreamSizeModulo = 0;
}
public bool ReadHeader(InputBuffer input) {
while (true) {
int bits;
switch (gzipHeaderSubstate) {
case GzipHeaderState.ReadingID1:
bits = input.GetBits(8);
if (bits < 0) {
return false;
}
if (bits != GZipConstants.ID1) {
throw new InvalidDataException(SR.GetString(SR.CorruptedGZipHeader));
}
gzipHeaderSubstate = GzipHeaderState.ReadingID2;
goto case GzipHeaderState.ReadingID2;
case GzipHeaderState.ReadingID2:
bits = input.GetBits(8);
if (bits < 0) {
return false;
}
if (bits != GZipConstants.ID2) {
throw new InvalidDataException(SR.GetString(SR.CorruptedGZipHeader));
}
gzipHeaderSubstate = GzipHeaderState.ReadingCM;
goto case GzipHeaderState.ReadingCM;
case GzipHeaderState.ReadingCM:
bits = input.GetBits(8);
if (bits < 0) {
return false;
}
if (bits != GZipConstants.Deflate) { // compression mode must be 8 (deflate)
throw new InvalidDataException(SR.GetString(SR.UnknownCompressionMode));
}
gzipHeaderSubstate = GzipHeaderState.ReadingFLG; ;
goto case GzipHeaderState.ReadingFLG;
case GzipHeaderState.ReadingFLG:
bits = input.GetBits(8);
if (bits < 0) {
return false;
}
gzip_header_flag = bits;
gzipHeaderSubstate = GzipHeaderState.ReadingMMTime;
loopCounter = 0; // 4 MMTIME bytes
goto case GzipHeaderState.ReadingMMTime;
case GzipHeaderState.ReadingMMTime:
bits = 0;
while (loopCounter < 4) {
bits = input.GetBits(8);
if (bits < 0) {
return false;
}
loopCounter++;
}
gzipHeaderSubstate = GzipHeaderState.ReadingXFL;
loopCounter = 0;
goto case GzipHeaderState.ReadingXFL;
case GzipHeaderState.ReadingXFL: // ignore XFL
bits = input.GetBits(8);
if (bits < 0) {
return false;
}
gzipHeaderSubstate = GzipHeaderState.ReadingOS;
goto case GzipHeaderState.ReadingOS;
case GzipHeaderState.ReadingOS: // ignore OS
bits = input.GetBits(8);
if (bits < 0) {
return false;
}
gzipHeaderSubstate = GzipHeaderState.ReadingXLen1;
goto case GzipHeaderState.ReadingXLen1;
case GzipHeaderState.ReadingXLen1:
if ((gzip_header_flag & (int)GZipOptionalHeaderFlags.ExtraFieldsFlag) == 0) {
goto case GzipHeaderState.ReadingFileName;
}
bits = input.GetBits(8);
if (bits < 0) {
return false;
}
gzip_header_xlen = bits;
gzipHeaderSubstate = GzipHeaderState.ReadingXLen2;
goto case GzipHeaderState.ReadingXLen2;
case GzipHeaderState.ReadingXLen2:
bits = input.GetBits(8);
if (bits < 0) {
return false;
}
gzip_header_xlen |= (bits << 8);
gzipHeaderSubstate = GzipHeaderState.ReadingXLenData;
loopCounter = 0; // 0 bytes of XLEN data read so far
goto case GzipHeaderState.ReadingXLenData;
case GzipHeaderState.ReadingXLenData:
bits = 0;
while (loopCounter < gzip_header_xlen) {
bits = input.GetBits(8);
if (bits < 0) {
return false;
}
loopCounter++;
}
gzipHeaderSubstate = GzipHeaderState.ReadingFileName;
loopCounter = 0;
goto case GzipHeaderState.ReadingFileName;
case GzipHeaderState.ReadingFileName:
if ((gzip_header_flag & (int)GZipOptionalHeaderFlags.FileNameFlag) == 0) {
gzipHeaderSubstate = GzipHeaderState.ReadingComment;
goto case GzipHeaderState.ReadingComment;
}
do {
bits = input.GetBits(8);
if (bits < 0) {
return false;
}
if (bits == 0) { // see '\0' in the file name string
break;
}
} while (true);
gzipHeaderSubstate = GzipHeaderState.ReadingComment;
goto case GzipHeaderState.ReadingComment;
case GzipHeaderState.ReadingComment:
if ((gzip_header_flag & (int)GZipOptionalHeaderFlags.CommentFlag) == 0) {
gzipHeaderSubstate = GzipHeaderState.ReadingCRC16Part1;
goto case GzipHeaderState.ReadingCRC16Part1;
}
do {
bits = input.GetBits(8);
if (bits < 0) {
return false;
}
if (bits == 0) { // see '\0' in the file name string
break;
}
} while (true);
gzipHeaderSubstate = GzipHeaderState.ReadingCRC16Part1;
goto case GzipHeaderState.ReadingCRC16Part1;
case GzipHeaderState.ReadingCRC16Part1:
if ((gzip_header_flag & (int)GZipOptionalHeaderFlags.CRCFlag) == 0) {
gzipHeaderSubstate = GzipHeaderState.Done;
goto case GzipHeaderState.Done;
}
bits = input.GetBits(8); // ignore crc
if (bits < 0) {
return false;
}
gzipHeaderSubstate = GzipHeaderState.ReadingCRC16Part2;
goto case GzipHeaderState.ReadingCRC16Part2;
case GzipHeaderState.ReadingCRC16Part2:
bits = input.GetBits(8); // ignore crc
if (bits < 0) {
return false;
}
gzipHeaderSubstate = GzipHeaderState.Done;
goto case GzipHeaderState.Done;
case GzipHeaderState.Done:
return true;
default:
Debug.Assert(false, "We should not reach unknown state!");
throw new InvalidDataException(SR.GetString(SR.UnknownState));
}
}
}
public bool ReadFooter(InputBuffer input) {
input.SkipToByteBoundary();
if (gzipFooterSubstate == GzipHeaderState.ReadingCRC) {
while (loopCounter < 4) {
int bits = input.GetBits(8);
if (bits < 0) {
return false;
}
expectedCrc32 |= ((uint)bits << (8 * loopCounter));
loopCounter++;
}
gzipFooterSubstate = GzipHeaderState.ReadingFileSize;
loopCounter = 0;
}
if (gzipFooterSubstate == GzipHeaderState.ReadingFileSize) {
if (loopCounter == 0)
expectedOutputStreamSizeModulo = 0;
while (loopCounter < 4) {
int bits = input.GetBits(8);
if (bits < 0) {
return false;
}
expectedOutputStreamSizeModulo |= ((uint) bits << (8 * loopCounter));
loopCounter++;
}
}
return true;
}
public void UpdateWithBytesRead(byte[] buffer, int offset, int copied) {
actualCrc32 = Crc32Helper.UpdateCrc32(actualCrc32, buffer, offset, copied);
long n = actualStreamSizeModulo + (uint) copied;
if (n >= GZipConstants.FileLengthModulo) {
n %= GZipConstants.FileLengthModulo;
}
actualStreamSizeModulo = n;
}
public void Validate() {
if (expectedCrc32 != actualCrc32) {
throw new InvalidDataException(SR.GetString(SR.InvalidCRC));
}
if (actualStreamSizeModulo != expectedOutputStreamSizeModulo) {
throw new InvalidDataException(SR.GetString(SR.InvalidStreamSize));
}
}
internal enum GzipHeaderState {
// GZIP header
ReadingID1,
ReadingID2,
ReadingCM,
ReadingFLG,
ReadingMMTime, // iterates 4 times
ReadingXFL,
ReadingOS,
ReadingXLen1,
ReadingXLen2,
ReadingXLenData,
ReadingFileName,
ReadingComment,
ReadingCRC16Part1,
ReadingCRC16Part2,
Done, // done reading GZIP header
// GZIP footer
ReadingCRC, // iterates 4 times
ReadingFileSize // iterates 4 times
}
[Flags]
internal enum GZipOptionalHeaderFlags {
CRCFlag = 2,
ExtraFieldsFlag = 4,
FileNameFlag = 8,
CommentFlag = 16
}
}
}
| |
// 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.
// ------------------------------------------------------------------------------
// Changes to this file must follow the http://aka.ms/api-review process.
// ------------------------------------------------------------------------------
namespace System.Management
{
public enum AuthenticationLevel
{
Call = 3,
Connect = 2,
Default = 0,
None = 1,
Packet = 4,
PacketIntegrity = 5,
PacketPrivacy = 6,
Unchanged = -1,
}
public enum CimType
{
Boolean = 11,
Char16 = 103,
DateTime = 101,
None = 0,
Object = 13,
Real32 = 4,
Real64 = 5,
Reference = 102,
SInt16 = 2,
SInt32 = 3,
SInt64 = 20,
SInt8 = 16,
String = 8,
UInt16 = 18,
UInt32 = 19,
UInt64 = 21,
UInt8 = 17,
}
public enum CodeLanguage
{
CSharp = 0,
JScript = 1,
Mcpp = 4,
VB = 2,
VJSharp = 3,
}
[System.FlagsAttribute]
public enum ComparisonSettings
{
IgnoreCase = 16,
IgnoreClass = 8,
IgnoreDefaultValues = 4,
IgnoreFlavor = 32,
IgnoreObjectSource = 2,
IgnoreQualifiers = 1,
IncludeAll = 0,
}
public partial class CompletedEventArgs : System.Management.ManagementEventArgs
{
internal CompletedEventArgs() { }
public System.Management.ManagementStatus Status { get { throw null; } }
public System.Management.ManagementBaseObject StatusObject { get { throw null; } }
}
public delegate void CompletedEventHandler(object sender, System.Management.CompletedEventArgs e);
public partial class ConnectionOptions : System.Management.ManagementOptions
{
public ConnectionOptions() { }
public ConnectionOptions(string locale, string username, System.Security.SecureString password, string authority, System.Management.ImpersonationLevel impersonation, System.Management.AuthenticationLevel authentication, bool enablePrivileges, System.Management.ManagementNamedValueCollection context, System.TimeSpan timeout) { }
public ConnectionOptions(string locale, string username, string password, string authority, System.Management.ImpersonationLevel impersonation, System.Management.AuthenticationLevel authentication, bool enablePrivileges, System.Management.ManagementNamedValueCollection context, System.TimeSpan timeout) { }
public System.Management.AuthenticationLevel Authentication { get { throw null; } set { } }
public string Authority { get { throw null; } set { } }
public bool EnablePrivileges { get { throw null; } set { } }
public System.Management.ImpersonationLevel Impersonation { get { throw null; } set { } }
public string Locale { get { throw null; } set { } }
public string Password { set { } }
public System.Security.SecureString SecurePassword { set { } }
public string Username { get { throw null; } set { } }
public override object Clone() { throw null; }
}
public partial class DeleteOptions : System.Management.ManagementOptions
{
public DeleteOptions() { }
public DeleteOptions(System.Management.ManagementNamedValueCollection context, System.TimeSpan timeout) { }
public override object Clone() { throw null; }
}
public partial class EnumerationOptions : System.Management.ManagementOptions
{
public EnumerationOptions() { }
public EnumerationOptions(System.Management.ManagementNamedValueCollection context, System.TimeSpan timeout, int blockSize, bool rewindable, bool returnImmediatley, bool useAmendedQualifiers, bool ensureLocatable, bool prototypeOnly, bool directRead, bool enumerateDeep) { }
public int BlockSize { get { throw null; } set { } }
public bool DirectRead { get { throw null; } set { } }
public bool EnsureLocatable { get { throw null; } set { } }
public bool EnumerateDeep { get { throw null; } set { } }
public bool PrototypeOnly { get { throw null; } set { } }
public bool ReturnImmediately { get { throw null; } set { } }
public bool Rewindable { get { throw null; } set { } }
public bool UseAmendedQualifiers { get { throw null; } set { } }
public override object Clone() { throw null; }
}
public partial class EventArrivedEventArgs : System.Management.ManagementEventArgs
{
internal EventArrivedEventArgs() { }
public System.Management.ManagementBaseObject NewEvent { get { throw null; } }
}
public delegate void EventArrivedEventHandler(object sender, System.Management.EventArrivedEventArgs e);
public partial class EventQuery : System.Management.ManagementQuery
{
public EventQuery() { }
public EventQuery(string query) { }
public EventQuery(string language, string query) { }
public override object Clone() { throw null; }
}
public partial class EventWatcherOptions : System.Management.ManagementOptions
{
public EventWatcherOptions() { }
public EventWatcherOptions(System.Management.ManagementNamedValueCollection context, System.TimeSpan timeout, int blockSize) { }
public int BlockSize { get { throw null; } set { } }
public override object Clone() { throw null; }
}
public enum ImpersonationLevel
{
Anonymous = 1,
Default = 0,
Delegate = 4,
Identify = 2,
Impersonate = 3,
}
public partial class InvokeMethodOptions : System.Management.ManagementOptions
{
public InvokeMethodOptions() { }
public InvokeMethodOptions(System.Management.ManagementNamedValueCollection context, System.TimeSpan timeout) { }
public override object Clone() { throw null; }
}
[System.ComponentModel.ToolboxItemAttribute(false)]
public partial class ManagementBaseObject : System.ComponentModel.Component, System.ICloneable, System.Runtime.Serialization.ISerializable
{
protected ManagementBaseObject(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { }
public virtual System.Management.ManagementPath ClassPath { get { throw null; } }
public object this[string propertyName] { get { throw null; } set { } }
public virtual System.Management.PropertyDataCollection Properties { get { throw null; } }
public virtual System.Management.QualifierDataCollection Qualifiers { get { throw null; } }
public virtual System.Management.PropertyDataCollection SystemProperties { get { throw null; } }
public virtual object Clone() { throw null; }
public bool CompareTo(System.Management.ManagementBaseObject otherObject, System.Management.ComparisonSettings settings) { throw null; }
public new void Dispose() { }
public override bool Equals(object obj) { throw null; }
public override int GetHashCode() { throw null; }
protected virtual void GetObjectData(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { }
public object GetPropertyQualifierValue(string propertyName, string qualifierName) { throw null; }
public object GetPropertyValue(string propertyName) { throw null; }
public object GetQualifierValue(string qualifierName) { throw null; }
public string GetText(System.Management.TextFormat format) { throw null; }
public static explicit operator System.IntPtr (System.Management.ManagementBaseObject managementObject) { throw null; }
public void SetPropertyQualifierValue(string propertyName, string qualifierName, object qualifierValue) { }
public void SetPropertyValue(string propertyName, object propertyValue) { }
public void SetQualifierValue(string qualifierName, object qualifierValue) { }
void System.Runtime.Serialization.ISerializable.GetObjectData(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { }
}
public partial class ManagementClass : System.Management.ManagementObject
{
public ManagementClass() { }
public ManagementClass(System.Management.ManagementPath path) { }
public ManagementClass(System.Management.ManagementPath path, System.Management.ObjectGetOptions options) { }
public ManagementClass(System.Management.ManagementScope scope, System.Management.ManagementPath path, System.Management.ObjectGetOptions options) { }
protected ManagementClass(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { }
public ManagementClass(string path) { }
public ManagementClass(string path, System.Management.ObjectGetOptions options) { }
public ManagementClass(string scope, string path, System.Management.ObjectGetOptions options) { }
public System.Collections.Specialized.StringCollection Derivation { get { throw null; } }
public System.Management.MethodDataCollection Methods { get { throw null; } }
public override System.Management.ManagementPath Path { get { throw null; } set { } }
public override object Clone() { throw null; }
public System.Management.ManagementObject CreateInstance() { throw null; }
public System.Management.ManagementClass Derive(string newClassName) { throw null; }
public System.Management.ManagementObjectCollection GetInstances() { throw null; }
public System.Management.ManagementObjectCollection GetInstances(System.Management.EnumerationOptions options) { throw null; }
public void GetInstances(System.Management.ManagementOperationObserver watcher) { }
public void GetInstances(System.Management.ManagementOperationObserver watcher, System.Management.EnumerationOptions options) { }
protected override void GetObjectData(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { }
public System.Management.ManagementObjectCollection GetRelatedClasses() { throw null; }
public void GetRelatedClasses(System.Management.ManagementOperationObserver watcher) { }
public void GetRelatedClasses(System.Management.ManagementOperationObserver watcher, string relatedClass) { }
public void GetRelatedClasses(System.Management.ManagementOperationObserver watcher, string relatedClass, string relationshipClass, string relationshipQualifier, string relatedQualifier, string relatedRole, string thisRole, System.Management.EnumerationOptions options) { }
public System.Management.ManagementObjectCollection GetRelatedClasses(string relatedClass) { throw null; }
public System.Management.ManagementObjectCollection GetRelatedClasses(string relatedClass, string relationshipClass, string relationshipQualifier, string relatedQualifier, string relatedRole, string thisRole, System.Management.EnumerationOptions options) { throw null; }
public System.Management.ManagementObjectCollection GetRelationshipClasses() { throw null; }
public void GetRelationshipClasses(System.Management.ManagementOperationObserver watcher) { }
public void GetRelationshipClasses(System.Management.ManagementOperationObserver watcher, string relationshipClass) { }
public void GetRelationshipClasses(System.Management.ManagementOperationObserver watcher, string relationshipClass, string relationshipQualifier, string thisRole, System.Management.EnumerationOptions options) { }
public System.Management.ManagementObjectCollection GetRelationshipClasses(string relationshipClass) { throw null; }
public System.Management.ManagementObjectCollection GetRelationshipClasses(string relationshipClass, string relationshipQualifier, string thisRole, System.Management.EnumerationOptions options) { throw null; }
public System.CodeDom.CodeTypeDeclaration GetStronglyTypedClassCode(bool includeSystemClassInClassDef, bool systemPropertyClass) { throw null; }
public bool GetStronglyTypedClassCode(System.Management.CodeLanguage lang, string filePath, string classNamespace) { throw null; }
public System.Management.ManagementObjectCollection GetSubclasses() { throw null; }
public System.Management.ManagementObjectCollection GetSubclasses(System.Management.EnumerationOptions options) { throw null; }
public void GetSubclasses(System.Management.ManagementOperationObserver watcher) { }
public void GetSubclasses(System.Management.ManagementOperationObserver watcher, System.Management.EnumerationOptions options) { }
}
public sealed partial class ManagementDateTimeConverter
{
internal ManagementDateTimeConverter() { }
public static System.DateTime ToDateTime(string dmtfDate) { throw null; }
public static string ToDmtfDateTime(System.DateTime date) { throw null; }
public static string ToDmtfTimeInterval(System.TimeSpan timespan) { throw null; }
public static System.TimeSpan ToTimeSpan(string dmtfTimespan) { throw null; }
}
public abstract partial class ManagementEventArgs : System.EventArgs
{
internal ManagementEventArgs() { }
public object Context { get { throw null; } }
}
[System.ComponentModel.ToolboxItemAttribute(false)]
public partial class ManagementEventWatcher : System.ComponentModel.Component
{
public ManagementEventWatcher() { }
public ManagementEventWatcher(System.Management.EventQuery query) { }
public ManagementEventWatcher(System.Management.ManagementScope scope, System.Management.EventQuery query) { }
public ManagementEventWatcher(System.Management.ManagementScope scope, System.Management.EventQuery query, System.Management.EventWatcherOptions options) { }
public ManagementEventWatcher(string query) { }
public ManagementEventWatcher(string scope, string query) { }
public ManagementEventWatcher(string scope, string query, System.Management.EventWatcherOptions options) { }
public System.Management.EventWatcherOptions Options { get { throw null; } set { } }
public System.Management.EventQuery Query { get { throw null; } set { } }
public System.Management.ManagementScope Scope { get { throw null; } set { } }
public event System.Management.EventArrivedEventHandler EventArrived { add { } remove { } }
public event System.Management.StoppedEventHandler Stopped { add { } remove { } }
~ManagementEventWatcher() { }
public void Start() { }
public void Stop() { }
public System.Management.ManagementBaseObject WaitForNextEvent() { throw null; }
}
public partial class ManagementException : System.SystemException
{
public ManagementException() { }
protected ManagementException(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { }
public ManagementException(string message) { }
public ManagementException(string message, System.Exception innerException) { }
public System.Management.ManagementStatus ErrorCode { get { throw null; } }
public System.Management.ManagementBaseObject ErrorInformation { get { throw null; } }
public override void GetObjectData(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { }
}
public partial class ManagementNamedValueCollection : System.Collections.Specialized.NameObjectCollectionBase
{
public ManagementNamedValueCollection() { }
protected ManagementNamedValueCollection(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { }
public object this[string name] { get { throw null; } }
public void Add(string name, object value) { }
public System.Management.ManagementNamedValueCollection Clone() { throw null; }
public void Remove(string name) { }
public void RemoveAll() { }
}
public partial class ManagementObject : System.Management.ManagementBaseObject, System.ICloneable
{
public ManagementObject() : base (default(System.Runtime.Serialization.SerializationInfo), default(System.Runtime.Serialization.StreamingContext)) { }
public ManagementObject(System.Management.ManagementPath path) : base (default(System.Runtime.Serialization.SerializationInfo), default(System.Runtime.Serialization.StreamingContext)) { }
public ManagementObject(System.Management.ManagementPath path, System.Management.ObjectGetOptions options) : base (default(System.Runtime.Serialization.SerializationInfo), default(System.Runtime.Serialization.StreamingContext)) { }
public ManagementObject(System.Management.ManagementScope scope, System.Management.ManagementPath path, System.Management.ObjectGetOptions options) : base (default(System.Runtime.Serialization.SerializationInfo), default(System.Runtime.Serialization.StreamingContext)) { }
protected ManagementObject(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) : base (default(System.Runtime.Serialization.SerializationInfo), default(System.Runtime.Serialization.StreamingContext)) { }
public ManagementObject(string path) : base (default(System.Runtime.Serialization.SerializationInfo), default(System.Runtime.Serialization.StreamingContext)) { }
public ManagementObject(string path, System.Management.ObjectGetOptions options) : base (default(System.Runtime.Serialization.SerializationInfo), default(System.Runtime.Serialization.StreamingContext)) { }
public ManagementObject(string scopeString, string pathString, System.Management.ObjectGetOptions options) : base (default(System.Runtime.Serialization.SerializationInfo), default(System.Runtime.Serialization.StreamingContext)) { }
public override System.Management.ManagementPath ClassPath { get { throw null; } }
public System.Management.ObjectGetOptions Options { get { throw null; } set { } }
public virtual System.Management.ManagementPath Path { get { throw null; } set { } }
public System.Management.ManagementScope Scope { get { throw null; } set { } }
public override object Clone() { throw null; }
public void CopyTo(System.Management.ManagementOperationObserver watcher, System.Management.ManagementPath path) { }
public void CopyTo(System.Management.ManagementOperationObserver watcher, System.Management.ManagementPath path, System.Management.PutOptions options) { }
public void CopyTo(System.Management.ManagementOperationObserver watcher, string path) { }
public void CopyTo(System.Management.ManagementOperationObserver watcher, string path, System.Management.PutOptions options) { }
public System.Management.ManagementPath CopyTo(System.Management.ManagementPath path) { throw null; }
public System.Management.ManagementPath CopyTo(System.Management.ManagementPath path, System.Management.PutOptions options) { throw null; }
public System.Management.ManagementPath CopyTo(string path) { throw null; }
public System.Management.ManagementPath CopyTo(string path, System.Management.PutOptions options) { throw null; }
public void Delete() { }
public void Delete(System.Management.DeleteOptions options) { }
public void Delete(System.Management.ManagementOperationObserver watcher) { }
public void Delete(System.Management.ManagementOperationObserver watcher, System.Management.DeleteOptions options) { }
public new void Dispose() { }
public void Get() { }
public void Get(System.Management.ManagementOperationObserver watcher) { }
public System.Management.ManagementBaseObject GetMethodParameters(string methodName) { throw null; }
protected override void GetObjectData(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { }
public System.Management.ManagementObjectCollection GetRelated() { throw null; }
public void GetRelated(System.Management.ManagementOperationObserver watcher) { }
public void GetRelated(System.Management.ManagementOperationObserver watcher, string relatedClass) { }
public void GetRelated(System.Management.ManagementOperationObserver watcher, string relatedClass, string relationshipClass, string relationshipQualifier, string relatedQualifier, string relatedRole, string thisRole, bool classDefinitionsOnly, System.Management.EnumerationOptions options) { }
public System.Management.ManagementObjectCollection GetRelated(string relatedClass) { throw null; }
public System.Management.ManagementObjectCollection GetRelated(string relatedClass, string relationshipClass, string relationshipQualifier, string relatedQualifier, string relatedRole, string thisRole, bool classDefinitionsOnly, System.Management.EnumerationOptions options) { throw null; }
public System.Management.ManagementObjectCollection GetRelationships() { throw null; }
public void GetRelationships(System.Management.ManagementOperationObserver watcher) { }
public void GetRelationships(System.Management.ManagementOperationObserver watcher, string relationshipClass) { }
public void GetRelationships(System.Management.ManagementOperationObserver watcher, string relationshipClass, string relationshipQualifier, string thisRole, bool classDefinitionsOnly, System.Management.EnumerationOptions options) { }
public System.Management.ManagementObjectCollection GetRelationships(string relationshipClass) { throw null; }
public System.Management.ManagementObjectCollection GetRelationships(string relationshipClass, string relationshipQualifier, string thisRole, bool classDefinitionsOnly, System.Management.EnumerationOptions options) { throw null; }
public void InvokeMethod(System.Management.ManagementOperationObserver watcher, string methodName, System.Management.ManagementBaseObject inParameters, System.Management.InvokeMethodOptions options) { }
public void InvokeMethod(System.Management.ManagementOperationObserver watcher, string methodName, object[] args) { }
public System.Management.ManagementBaseObject InvokeMethod(string methodName, System.Management.ManagementBaseObject inParameters, System.Management.InvokeMethodOptions options) { throw null; }
public object InvokeMethod(string methodName, object[] args) { throw null; }
public System.Management.ManagementPath Put() { throw null; }
public void Put(System.Management.ManagementOperationObserver watcher) { }
public void Put(System.Management.ManagementOperationObserver watcher, System.Management.PutOptions options) { }
public System.Management.ManagementPath Put(System.Management.PutOptions options) { throw null; }
public override string ToString() { throw null; }
}
public partial class ManagementObjectCollection : System.Collections.ICollection, System.Collections.IEnumerable, System.IDisposable
{
internal ManagementObjectCollection() { }
public int Count { get { throw null; } }
public bool IsSynchronized { get { throw null; } }
public object SyncRoot { get { throw null; } }
public void CopyTo(System.Array array, int index) { }
public void CopyTo(System.Management.ManagementBaseObject[] objectCollection, int index) { }
public void Dispose() { }
~ManagementObjectCollection() { }
public System.Management.ManagementObjectCollection.ManagementObjectEnumerator GetEnumerator() { throw null; }
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { throw null; }
public partial class ManagementObjectEnumerator : System.Collections.IEnumerator, System.IDisposable
{
internal ManagementObjectEnumerator() { }
public System.Management.ManagementBaseObject Current { get { throw null; } }
object System.Collections.IEnumerator.Current { get { throw null; } }
public void Dispose() { }
~ManagementObjectEnumerator() { }
public bool MoveNext() { throw null; }
public void Reset() { }
}
}
[System.ComponentModel.ToolboxItemAttribute(false)]
public partial class ManagementObjectSearcher : System.ComponentModel.Component
{
public ManagementObjectSearcher() { }
public ManagementObjectSearcher(System.Management.ManagementScope scope, System.Management.ObjectQuery query) { }
public ManagementObjectSearcher(System.Management.ManagementScope scope, System.Management.ObjectQuery query, System.Management.EnumerationOptions options) { }
public ManagementObjectSearcher(System.Management.ObjectQuery query) { }
public ManagementObjectSearcher(string queryString) { }
public ManagementObjectSearcher(string scope, string queryString) { }
public ManagementObjectSearcher(string scope, string queryString, System.Management.EnumerationOptions options) { }
public System.Management.EnumerationOptions Options { get { throw null; } set { } }
public System.Management.ObjectQuery Query { get { throw null; } set { } }
public System.Management.ManagementScope Scope { get { throw null; } set { } }
public System.Management.ManagementObjectCollection Get() { throw null; }
public void Get(System.Management.ManagementOperationObserver watcher) { }
}
public partial class ManagementOperationObserver
{
public ManagementOperationObserver() { }
public event System.Management.CompletedEventHandler Completed { add { } remove { } }
public event System.Management.ObjectPutEventHandler ObjectPut { add { } remove { } }
public event System.Management.ObjectReadyEventHandler ObjectReady { add { } remove { } }
public event System.Management.ProgressEventHandler Progress { add { } remove { } }
public void Cancel() { }
}
[System.ComponentModel.TypeConverter(typeof(System.ComponentModel.ExpandableObjectConverter))]
public abstract partial class ManagementOptions : System.ICloneable
{
internal ManagementOptions() { }
public static readonly System.TimeSpan InfiniteTimeout;
public System.Management.ManagementNamedValueCollection Context { get { throw null; } set { } }
public System.TimeSpan Timeout { get { throw null; } set { } }
public abstract object Clone();
}
public partial class ManagementPath : System.ICloneable
{
public ManagementPath() { }
public ManagementPath(string path) { }
[System.ComponentModel.RefreshPropertiesAttribute((System.ComponentModel.RefreshProperties)(1))]
public string ClassName { get { throw null; } set { } }
public static System.Management.ManagementPath DefaultPath { get { throw null; } set { } }
public bool IsClass { get { throw null; } }
public bool IsInstance { get { throw null; } }
public bool IsSingleton { get { throw null; } }
[System.ComponentModel.RefreshPropertiesAttribute((System.ComponentModel.RefreshProperties)(1))]
public string NamespacePath { get { throw null; } set { } }
[System.ComponentModel.RefreshPropertiesAttribute((System.ComponentModel.RefreshProperties)(1))]
public string Path { get { throw null; } set { } }
[System.ComponentModel.RefreshPropertiesAttribute((System.ComponentModel.RefreshProperties)(1))]
public string RelativePath { get { throw null; } set { } }
[System.ComponentModel.RefreshPropertiesAttribute((System.ComponentModel.RefreshProperties)(1))]
public string Server { get { throw null; } set { } }
public System.Management.ManagementPath Clone() { throw null; }
public void SetAsClass() { }
public void SetAsSingleton() { }
object System.ICloneable.Clone() { throw null; }
public override string ToString() { throw null; }
}
public abstract partial class ManagementQuery : System.ICloneable
{
internal ManagementQuery() { }
public virtual string QueryLanguage { get { throw null; } set { } }
public virtual string QueryString { get { throw null; } set { } }
public abstract object Clone();
protected internal virtual void ParseQuery(string query) { }
}
public partial class ManagementScope : System.ICloneable
{
public ManagementScope() { }
public ManagementScope(System.Management.ManagementPath path) { }
public ManagementScope(System.Management.ManagementPath path, System.Management.ConnectionOptions options) { }
public ManagementScope(string path) { }
public ManagementScope(string path, System.Management.ConnectionOptions options) { }
public bool IsConnected { get { throw null; } }
public System.Management.ConnectionOptions Options { get { throw null; } set { } }
public System.Management.ManagementPath Path { get { throw null; } set { } }
public System.Management.ManagementScope Clone() { throw null; }
public void Connect() { }
object System.ICloneable.Clone() { throw null; }
}
public enum ManagementStatus
{
AccessDenied = -2147217405,
AggregatingByObject = -2147217315,
AlreadyExists = -2147217383,
AmendedObject = -2147217306,
BackupRestoreWinmgmtRunning = -2147217312,
BufferTooSmall = -2147217348,
CallCanceled = -2147217358,
CannotBeAbstract = -2147217307,
CannotBeKey = -2147217377,
CannotBeSingleton = -2147217364,
CannotChangeIndexInheritance = -2147217328,
CannotChangeKeyInheritance = -2147217335,
CircularReference = -2147217337,
ClassHasChildren = -2147217371,
ClassHasInstances = -2147217370,
ClientTooSlow = -2147217305,
CriticalError = -2147217398,
Different = 262147,
DuplicateObjects = 262152,
Failed = -2147217407,
False = 1,
IllegalNull = -2147217368,
IllegalOperation = -2147217378,
IncompleteClass = -2147217376,
InitializationFailure = -2147217388,
InvalidCimType = -2147217363,
InvalidClass = -2147217392,
InvalidContext = -2147217401,
InvalidDuplicateParameter = -2147217341,
InvalidFlavor = -2147217338,
InvalidMethod = -2147217362,
InvalidMethodParameters = -2147217361,
InvalidNamespace = -2147217394,
InvalidObject = -2147217393,
InvalidObjectPath = -2147217350,
InvalidOperation = -2147217386,
InvalidOperator = -2147217309,
InvalidParameter = -2147217400,
InvalidParameterID = -2147217353,
InvalidProperty = -2147217359,
InvalidPropertyType = -2147217366,
InvalidProviderRegistration = -2147217390,
InvalidQualifier = -2147217342,
InvalidQualifierType = -2147217367,
InvalidQuery = -2147217385,
InvalidQueryType = -2147217384,
InvalidStream = -2147217397,
InvalidSuperclass = -2147217395,
InvalidSyntax = -2147217375,
LocalCredentials = -2147217308,
MarshalInvalidSignature = -2147217343,
MarshalVersionMismatch = -2147217344,
MethodDisabled = -2147217322,
MethodNotImplemented = -2147217323,
MissingAggregationList = -2147217317,
MissingGroupWithin = -2147217318,
MissingParameterID = -2147217354,
NoError = 0,
NoMoreData = 262149,
NonconsecutiveParameterIDs = -2147217352,
NondecoratedObject = -2147217374,
NotAvailable = -2147217399,
NotEventClass = -2147217319,
NotFound = -2147217406,
NotSupported = -2147217396,
OperationCanceled = 262150,
OutOfDiskSpace = -2147217349,
OutOfMemory = -2147217402,
OverrideNotAllowed = -2147217382,
ParameterIDOnRetval = -2147217351,
PartialResults = 262160,
Pending = 262151,
PrivilegeNotHeld = -2147217310,
PropagatedMethod = -2147217356,
PropagatedProperty = -2147217380,
PropagatedQualifier = -2147217381,
PropertyNotAnObject = -2147217316,
ProviderFailure = -2147217404,
ProviderLoadFailure = -2147217389,
ProviderNotCapable = -2147217372,
ProviderNotFound = -2147217391,
QueryNotImplemented = -2147217369,
QueueOverflow = -2147217311,
ReadOnly = -2147217373,
RefresherBusy = -2147217321,
RegistrationTooBroad = -2147213311,
RegistrationTooPrecise = -2147213310,
ResetToDefault = 262146,
ServerTooBusy = -2147217339,
ShuttingDown = -2147217357,
SystemProperty = -2147217360,
Timedout = 262148,
TooManyProperties = -2147217327,
TooMuchData = -2147217340,
TransportFailure = -2147217387,
TypeMismatch = -2147217403,
Unexpected = -2147217379,
UninterpretableProviderQuery = -2147217313,
UnknownObjectType = -2147217346,
UnknownPacketType = -2147217345,
UnparsableQuery = -2147217320,
UnsupportedClassUpdate = -2147217336,
UnsupportedParameter = -2147217355,
UnsupportedPutExtension = -2147217347,
UpdateOverrideNotAllowed = -2147217325,
UpdatePropagatedMethod = -2147217324,
UpdateTypeMismatch = -2147217326,
ValueOutOfRange = -2147217365,
}
public partial class MethodData
{
internal MethodData() { }
public System.Management.ManagementBaseObject InParameters { get { throw null; } }
public string Name { get { throw null; } }
public string Origin { get { throw null; } }
public System.Management.ManagementBaseObject OutParameters { get { throw null; } }
public System.Management.QualifierDataCollection Qualifiers { get { throw null; } }
}
public partial class MethodDataCollection : System.Collections.ICollection, System.Collections.IEnumerable
{
internal MethodDataCollection() { }
public int Count { get { throw null; } }
public bool IsSynchronized { get { throw null; } }
public virtual System.Management.MethodData this[string methodName] { get { throw null; } }
public object SyncRoot { get { throw null; } }
public virtual void Add(string methodName) { }
public virtual void Add(string methodName, System.Management.ManagementBaseObject inParameters, System.Management.ManagementBaseObject outParameters) { }
public void CopyTo(System.Array array, int index) { }
public void CopyTo(System.Management.MethodData[] methodArray, int index) { }
public System.Management.MethodDataCollection.MethodDataEnumerator GetEnumerator() { throw null; }
public virtual void Remove(string methodName) { }
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { throw null; }
public partial class MethodDataEnumerator : System.Collections.IEnumerator
{
internal MethodDataEnumerator() { }
public System.Management.MethodData Current { get { throw null; } }
object System.Collections.IEnumerator.Current { get { throw null; } }
public bool MoveNext() { throw null; }
public void Reset() { }
}
}
public partial class ObjectGetOptions : System.Management.ManagementOptions
{
public ObjectGetOptions() { }
public ObjectGetOptions(System.Management.ManagementNamedValueCollection context) { }
public ObjectGetOptions(System.Management.ManagementNamedValueCollection context, System.TimeSpan timeout, bool useAmendedQualifiers) { }
public bool UseAmendedQualifiers { get { throw null; } set { } }
public override object Clone() { throw null; }
}
public partial class ObjectPutEventArgs : System.Management.ManagementEventArgs
{
internal ObjectPutEventArgs() { }
public System.Management.ManagementPath Path { get { throw null; } }
}
public delegate void ObjectPutEventHandler(object sender, System.Management.ObjectPutEventArgs e);
public partial class ObjectQuery : System.Management.ManagementQuery
{
public ObjectQuery() { }
public ObjectQuery(string query) { }
public ObjectQuery(string language, string query) { }
public override object Clone() { throw null; }
}
public partial class ObjectReadyEventArgs : System.Management.ManagementEventArgs
{
internal ObjectReadyEventArgs() { }
public System.Management.ManagementBaseObject NewObject { get { throw null; } }
}
public delegate void ObjectReadyEventHandler(object sender, System.Management.ObjectReadyEventArgs e);
public partial class ProgressEventArgs : System.Management.ManagementEventArgs
{
internal ProgressEventArgs() { }
public int Current { get { throw null; } }
public string Message { get { throw null; } }
public int UpperBound { get { throw null; } }
}
public delegate void ProgressEventHandler(object sender, System.Management.ProgressEventArgs e);
public partial class PropertyData
{
internal PropertyData() { }
public bool IsArray { get { throw null; } }
public bool IsLocal { get { throw null; } }
public string Name { get { throw null; } }
public string Origin { get { throw null; } }
public System.Management.QualifierDataCollection Qualifiers { get { throw null; } }
public System.Management.CimType Type { get { throw null; } }
public object Value { get { throw null; } set { } }
}
public partial class PropertyDataCollection : System.Collections.ICollection, System.Collections.IEnumerable
{
internal PropertyDataCollection() { }
public int Count { get { throw null; } }
public bool IsSynchronized { get { throw null; } }
public virtual System.Management.PropertyData this[string propertyName] { get { throw null; } }
public object SyncRoot { get { throw null; } }
public void Add(string propertyName, System.Management.CimType propertyType, bool isArray) { }
public virtual void Add(string propertyName, object propertyValue) { }
public void Add(string propertyName, object propertyValue, System.Management.CimType propertyType) { }
public void CopyTo(System.Array array, int index) { }
public void CopyTo(System.Management.PropertyData[] propertyArray, int index) { }
public System.Management.PropertyDataCollection.PropertyDataEnumerator GetEnumerator() { throw null; }
public virtual void Remove(string propertyName) { }
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { throw null; }
public partial class PropertyDataEnumerator : System.Collections.IEnumerator
{
internal PropertyDataEnumerator() { }
public System.Management.PropertyData Current { get { throw null; } }
object System.Collections.IEnumerator.Current { get { throw null; } }
public bool MoveNext() { throw null; }
public void Reset() { }
}
}
public partial class PutOptions : System.Management.ManagementOptions
{
public PutOptions() { }
public PutOptions(System.Management.ManagementNamedValueCollection context) { }
public PutOptions(System.Management.ManagementNamedValueCollection context, System.TimeSpan timeout, bool useAmendedQualifiers, System.Management.PutType putType) { }
public System.Management.PutType Type { get { throw null; } set { } }
public bool UseAmendedQualifiers { get { throw null; } set { } }
public override object Clone() { throw null; }
}
public enum PutType
{
CreateOnly = 2,
None = 0,
UpdateOnly = 1,
UpdateOrCreate = 3,
}
public partial class QualifierData
{
internal QualifierData() { }
public bool IsAmended { get { throw null; } set { } }
public bool IsLocal { get { throw null; } }
public bool IsOverridable { get { throw null; } set { } }
public string Name { get { throw null; } }
public bool PropagatesToInstance { get { throw null; } set { } }
public bool PropagatesToSubclass { get { throw null; } set { } }
public object Value { get { throw null; } set { } }
}
public partial class QualifierDataCollection : System.Collections.ICollection, System.Collections.IEnumerable
{
internal QualifierDataCollection() { }
public int Count { get { throw null; } }
public bool IsSynchronized { get { throw null; } }
public virtual System.Management.QualifierData this[string qualifierName] { get { throw null; } }
public object SyncRoot { get { throw null; } }
public virtual void Add(string qualifierName, object qualifierValue) { }
public virtual void Add(string qualifierName, object qualifierValue, bool isAmended, bool propagatesToInstance, bool propagatesToSubclass, bool isOverridable) { }
public void CopyTo(System.Array array, int index) { }
public void CopyTo(System.Management.QualifierData[] qualifierArray, int index) { }
public System.Management.QualifierDataCollection.QualifierDataEnumerator GetEnumerator() { throw null; }
public virtual void Remove(string qualifierName) { }
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { throw null; }
public partial class QualifierDataEnumerator : System.Collections.IEnumerator
{
internal QualifierDataEnumerator() { }
public System.Management.QualifierData Current { get { throw null; } }
object System.Collections.IEnumerator.Current { get { throw null; } }
public bool MoveNext() { throw null; }
public void Reset() { }
}
}
public partial class RelatedObjectQuery : System.Management.WqlObjectQuery
{
public RelatedObjectQuery() { }
public RelatedObjectQuery(bool isSchemaQuery, string sourceObject, string relatedClass, string relationshipClass, string relatedQualifier, string relationshipQualifier, string relatedRole, string thisRole) { }
public RelatedObjectQuery(string queryOrSourceObject) { }
public RelatedObjectQuery(string sourceObject, string relatedClass) { }
public RelatedObjectQuery(string sourceObject, string relatedClass, string relationshipClass, string relatedQualifier, string relationshipQualifier, string relatedRole, string thisRole, bool classDefinitionsOnly) { }
public bool ClassDefinitionsOnly { get { throw null; } set { } }
public bool IsSchemaQuery { get { throw null; } set { } }
public string RelatedClass { get { throw null; } set { } }
public string RelatedQualifier { get { throw null; } set { } }
public string RelatedRole { get { throw null; } set { } }
public string RelationshipClass { get { throw null; } set { } }
public string RelationshipQualifier { get { throw null; } set { } }
public string SourceObject { get { throw null; } set { } }
public string ThisRole { get { throw null; } set { } }
protected internal void BuildQuery() { }
public override object Clone() { throw null; }
protected internal override void ParseQuery(string query) { }
}
public partial class RelationshipQuery : System.Management.WqlObjectQuery
{
public RelationshipQuery() { }
public RelationshipQuery(bool isSchemaQuery, string sourceObject, string relationshipClass, string relationshipQualifier, string thisRole) { }
public RelationshipQuery(string queryOrSourceObject) { }
public RelationshipQuery(string sourceObject, string relationshipClass) { }
public RelationshipQuery(string sourceObject, string relationshipClass, string relationshipQualifier, string thisRole, bool classDefinitionsOnly) { }
public bool ClassDefinitionsOnly { get { throw null; } set { } }
public bool IsSchemaQuery { get { throw null; } set { } }
public string RelationshipClass { get { throw null; } set { } }
public string RelationshipQualifier { get { throw null; } set { } }
public string SourceObject { get { throw null; } set { } }
public string ThisRole { get { throw null; } set { } }
protected internal void BuildQuery() { }
public override object Clone() { throw null; }
protected internal override void ParseQuery(string query) { }
}
public partial class SelectQuery : System.Management.WqlObjectQuery
{
public SelectQuery() { }
public SelectQuery(bool isSchemaQuery, string condition) { }
public SelectQuery(string queryOrClassName) { }
public SelectQuery(string className, string condition) { }
public SelectQuery(string className, string condition, string[] selectedProperties) { }
public string ClassName { get { throw null; } set { } }
public string Condition { get { throw null; } set { } }
public bool IsSchemaQuery { get { throw null; } set { } }
public override string QueryString { get { throw null; } set { } }
public System.Collections.Specialized.StringCollection SelectedProperties { get { throw null; } set { } }
protected internal void BuildQuery() { }
public override object Clone() { throw null; }
protected internal override void ParseQuery(string query) { }
}
public partial class StoppedEventArgs : System.Management.ManagementEventArgs
{
internal StoppedEventArgs() { }
public System.Management.ManagementStatus Status { get { throw null; } }
}
public delegate void StoppedEventHandler(object sender, System.Management.StoppedEventArgs e);
public enum TextFormat
{
CimDtd20 = 1,
Mof = 0,
WmiDtd20 = 2,
}
public partial class WqlEventQuery : System.Management.EventQuery
{
public WqlEventQuery() { }
public WqlEventQuery(string queryOrEventClassName) { }
public WqlEventQuery(string eventClassName, string condition) { }
public WqlEventQuery(string eventClassName, string condition, System.TimeSpan groupWithinInterval) { }
public WqlEventQuery(string eventClassName, string condition, System.TimeSpan groupWithinInterval, string[] groupByPropertyList) { }
public WqlEventQuery(string eventClassName, System.TimeSpan withinInterval) { }
public WqlEventQuery(string eventClassName, System.TimeSpan withinInterval, string condition) { }
public WqlEventQuery(string eventClassName, System.TimeSpan withinInterval, string condition, System.TimeSpan groupWithinInterval, string[] groupByPropertyList, string havingCondition) { }
public string Condition { get { throw null; } set { } }
public string EventClassName { get { throw null; } set { } }
public System.Collections.Specialized.StringCollection GroupByPropertyList { get { throw null; } set { } }
public System.TimeSpan GroupWithinInterval { get { throw null; } set { } }
public string HavingCondition { get { throw null; } set { } }
public override string QueryLanguage { get { throw null; } }
public override string QueryString { get { throw null; } set { } }
public System.TimeSpan WithinInterval { get { throw null; } set { } }
protected internal void BuildQuery() { }
public override object Clone() { throw null; }
protected internal override void ParseQuery(string query) { }
}
public partial class WqlObjectQuery : System.Management.ObjectQuery
{
public WqlObjectQuery() { }
public WqlObjectQuery(string query) { }
public override string QueryLanguage { get { throw null; } }
public override object Clone() { throw null; }
}
}
| |
//
// DependencyProperty.cs
//
// Author:
// Iain McCoy (iain@mccoy.id.au)
// Moonlight Team (moonlight-list@lists.ximian.com)
//
//
// Copyright 2005 Iain McCoy
// Copyright 2007 Novell, Inc.
//
// 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 Mono;
using System.Collections.Generic;
namespace System.Windows {
internal delegate void ValueValidator (DependencyObject target, DependencyProperty property, object value);
internal class CoreDependencyProperty : DependencyProperty {
internal CoreDependencyProperty (IntPtr handle, string name, Type property_type, Type declaring_type) : base (handle, name, property_type, declaring_type) {}
}
public class DependencyProperty {
static ValueValidator DefaultValidator = delegate { };
string name;
IntPtr native;
Type property_type;
Type declaring_type;
bool? attached;
bool? hasHiddenDefaultValue;
ValueValidator validator;
internal PropertyChangedCallback property_changed_callback {
get; private set;
}
static Dictionary <IntPtr, DependencyProperty> properties = new Dictionary<IntPtr, DependencyProperty> ();
public static readonly object UnsetValue = new object ();
internal DependencyProperty (IntPtr handle, string name, Type property_type, Type declaring_type)
{
this.native = handle;
this.property_type = property_type;
this.declaring_type = declaring_type;
this.name = name;
properties.Add (handle, this);
//Console.WriteLine ("DependencyProperty.DependencyProperty ({0:X}, {1}, {2})", handle, property_type.FullName, declaring_type.FullName);
}
public PropertyMetadata GetMetadata (Type forType)
{
var kind = Deployment.Current.Types.TypeToNativeKind (forType);
var defaultValue = UnsetValue;
if (!HasHiddenDefaultValue)
defaultValue = GetDefaultValue (kind) ?? UnsetValue;
return new PropertyMetadata (defaultValue);
}
public static DependencyProperty Register (string name, Type propertyType, Type ownerType, PropertyMetadata typeMetadata)
{
return RegisterAny (name, propertyType, ownerType, typeMetadata, false, false, true, true);
}
internal static DependencyProperty RegisterCore (string name, Type propertyType, Type ownerType, PropertyMetadata typeMetadata)
{
return RegisterAny (name, propertyType, ownerType, typeMetadata, false, false, true, false);
}
public static DependencyProperty RegisterAttached (string name, Type propertyType, Type ownerType, PropertyMetadata defaultMetadata)
{
return RegisterAny (name, propertyType, ownerType, defaultMetadata, true, false, true, true);
}
internal static DependencyProperty RegisterAttachedCore (string name, Type propertyType, Type ownerType, PropertyMetadata defaultMetadata)
{
return RegisterAny (name, propertyType, ownerType, defaultMetadata, true, false, true, false);
}
// internally Silverlight use some read-only properties
internal static DependencyProperty RegisterReadOnlyAttached (string name, Type propertyType, Type ownerType, PropertyMetadata defaultMetadata)
{
return RegisterAny (name, propertyType, ownerType, defaultMetadata, true, true, true, true);
}
// internally Silverlight use some read-only properties
internal static DependencyProperty RegisterReadOnlyCore (string name, Type propertyType, Type ownerType, PropertyMetadata defaultMetadata)
{
return RegisterAny (name, propertyType, ownerType, defaultMetadata, true, true, true, false);
}
private static DependencyProperty RegisterAny (string name, Type propertyType, Type ownerType, PropertyMetadata metadata, bool attached, bool readOnly, bool setsParent, bool custom)
{
ManagedType property_type;
ManagedType owner_type;
UnmanagedPropertyChangeHandler handler = null;
CustomDependencyProperty result;
bool is_nullable = false;
object default_value = DependencyProperty.UnsetValue;
PropertyChangedCallback property_changed_callback = null;
if (name == null)
throw new ArgumentNullException ("name");
if (name.Length == 0)
throw new ArgumentException("The 'name' argument cannot be an empty string");
if (propertyType == null)
throw new ArgumentNullException ("propertyType");
if (ownerType == null)
throw new ArgumentNullException ("ownerType");
if (propertyType.IsGenericType && propertyType.GetGenericTypeDefinition () == typeof (Nullable<>)) {
is_nullable = true;
// Console.WriteLine ("DependencyProperty.RegisterAny (): found nullable {0}, got nullable {1}", propertyType.FullName, propertyType.GetGenericArguments () [0].FullName);
propertyType = propertyType.GetGenericArguments () [0];
}
Types types = Deployment.Current.Types;
property_type = types.Find (propertyType);
owner_type = types.Find (ownerType);
if (metadata != null) {
default_value = metadata.DefaultValue ?? UnsetValue;
property_changed_callback = metadata.property_changed_callback;
}
if ((default_value == DependencyProperty.UnsetValue) && propertyType.IsValueType && !is_nullable)
default_value = Activator.CreateInstance (propertyType);
if (default_value != null && default_value != UnsetValue && !propertyType.IsAssignableFrom (default_value.GetType ()))
throw new ArgumentException (string.Format ("DefaultValue is of type {0} which is not compatible with type {1}", default_value.GetType (), propertyType));
if (property_changed_callback != null)
handler = UnmanagedPropertyChangedCallbackSafe;
Value v;
if (default_value == DependencyProperty.UnsetValue) {
v = new Value { k = types.TypeToKind (propertyType), IsNull = true };
default_value = null;
} else {
v = Value.FromObject (default_value, true);
}
IntPtr handle;
using (v) {
var val = v;
if (custom)
handle = NativeMethods.dependency_property_register_custom_property (name, property_type.native_handle, owner_type.native_handle, ref val, attached, readOnly, handler);
else
handle = NativeMethods.dependency_property_register_core_property (name, property_type.native_handle, owner_type.native_handle, ref val, attached, readOnly, handler);
}
if (handle == IntPtr.Zero)
return null;
if (is_nullable)
NativeMethods.dependency_property_set_is_nullable (handle, true);
result = new CustomDependencyProperty (handle, name, property_type, owner_type, default_value);
result.attached = attached;
result.PropertyChangedHandler = handler;
result.property_changed_callback = property_changed_callback;
return result;
}
private static void UnmanagedPropertyChangedCallbackSafe (IntPtr dependency_object, IntPtr propertyChangeArgs, ref MoonError error, IntPtr unused)
{
try {
try {
UnmanagedPropertyChangedCallback (dependency_object,
NativeMethods.property_changed_event_args_get_property (propertyChangeArgs),
NativeMethods.property_changed_event_args_get_old_value (propertyChangeArgs),
NativeMethods.property_changed_event_args_get_new_value (propertyChangeArgs));
} catch (Exception ex) {
error = new MoonError (ex);
}
} catch (Exception ex) {
try {
Console.WriteLine ("Moonlight: Unhandled exception in DependencyProperty.UnmanagedPropertyChangedCallback: {0}",
ex.Message);
} catch {
}
}
}
private static void UnmanagedPropertyChangedCallback (IntPtr dependency_object, IntPtr dependency_property, IntPtr old_value, IntPtr new_value)
{
DependencyProperty property;
CustomDependencyProperty custom_property;
DependencyObject obj;
object old_obj, new_obj;
if (!properties.TryGetValue (dependency_property, out property)) {
Console.Error.WriteLine ("DependencyProperty.UnmanagedPropertyChangedCallback: Couldn't find the managed DependencyProperty corresponding with native {0}", dependency_property);
return;
}
custom_property = property as CustomDependencyProperty;
if (custom_property == null) {
Console.Error.WriteLine ("DependencyProperty.UnmanagedPropertyChangedCallback: Got the event for a builtin dependency property.");
return;
}
// Console.WriteLine ("UnmanagedPropertyChangedCallback {3} {2} {0} {1}", old_value, new_value, custom_property.name, custom_property.property_type.FullName);
if (custom_property.property_changed_callback == null)
return;
obj = NativeDependencyObjectHelper.Lookup (dependency_object) as DependencyObject;
if (obj == null)
return;
old_obj = Value.ToObject (property.property_type, old_value);
new_obj = Value.ToObject (property.property_type, new_value);
InvokeChangedCallback (obj, property, custom_property.property_changed_callback, old_obj, new_obj);
}
static void InvokeChangedCallback (DependencyObject obj, DependencyProperty property, PropertyChangedCallback callback,
object old_obj, object new_obj)
{
if (old_obj == null && property.property_type.IsValueType && !property.IsNullable) {
old_obj = property.GetDefaultValue (obj);
Console.WriteLine ("WARNING: Got a null value for {0}.{1} which is a value type", property.DeclaringType.Name, property.Name);
}
if (Helper.AreEqual (property.PropertyType, old_obj, new_obj))
return;
var args = new DependencyPropertyChangedEventArgs (old_obj, new_obj, property);
// note: since callbacks might throw exceptions but we cannot catch them
callback (obj, args);
}
internal static DependencyProperty Lookup (IntPtr native)
{
DependencyProperty prop;
return properties.TryGetValue (native, out prop) ? prop : null;
}
internal static DependencyProperty Lookup (Kind declaring_kind, string name)
{
return Lookup (declaring_kind, name, null, false);
}
internal static DependencyProperty Lookup (Kind declaring_kind, string name, Type property_type)
{
return Lookup (declaring_kind, name, property_type, true);
}
private static DependencyProperty Lookup (Kind declaring_kind, string name, Type property_type, bool create)
{
DependencyProperty prop;
if (!LookupInternal (declaring_kind, name, property_type, create, out prop)) {
throw new Exception (
String.Format ("DependencyProperty.Lookup: {0} lacks {1}.", Deployment.Current.Types.KindToType (declaring_kind), name));
}
return prop;
}
private static bool LookupInternal (Kind declaring_kind, string name, Type property_type, bool create, out DependencyProperty property)
{
IntPtr handle;
if (name == null)
throw new ArgumentNullException ("name");
if (create && property_type == null)
throw new ArgumentNullException ("property_type");
if (declaring_kind == Kind.INVALID)
throw new ArgumentOutOfRangeException ("declaring_kind");
if (property_type != null)
Deployment.Current.Types.Find (property_type);
handle = NativeMethods.dependency_property_get_dependency_property_full (declaring_kind, name, true);
if (handle == IntPtr.Zero) {
property = null;
return false;
}
if (properties.TryGetValue (handle, out property))
return true;
if (create) {
property = new CoreDependencyProperty (handle, name, property_type, Deployment.Current.Types.KindToType (declaring_kind));
}
return property != null;
}
internal static bool TryLookup (Kind declaring_kind, string name, out DependencyProperty property)
{
return LookupInternal (declaring_kind, name, null, false, out property);
}
internal PropertyChangedCallback change_cb;
internal void AddPropertyChangeCallback (PropertyChangedCallback callback)
{
if (this is CustomDependencyProperty) {
Console.WriteLine ("this should really just be done by registering the property with metadata");
CustomDependencyProperty cdp = (CustomDependencyProperty)this;
if (cdp.property_changed_callback != null)
throw new InvalidOperationException ("this DP was registered with a PropertyChangedCallback already");
}
if (change_cb != null)
throw new InvalidOperationException ("this DP already has a change callback registered");
change_cb = callback;
NativeMethods.dependency_property_set_property_changed_callback (native,
CustomUnmanagedPropertyChangedCallbackSafe);
}
private static void CustomUnmanagedPropertyChangedCallbackSafe (IntPtr dependency_object, IntPtr propertyChangeArgs, ref MoonError error, IntPtr unused)
{
DependencyProperty property;
DependencyObject obj;
try {
try {
IntPtr uprop = NativeMethods.property_changed_event_args_get_property (propertyChangeArgs);
if (!properties.TryGetValue (uprop, out property)) {
Console.Error.WriteLine ("DependencyProperty.CustomUnmanagedPropertyChangedCallback: Couldn't find the managed DependencyProperty corresponding with native {0}/{1}", uprop, NativeMethods.property_changed_event_args_get_id (propertyChangeArgs));
return;
}
obj = NativeDependencyObjectHelper.Lookup (dependency_object) as DependencyObject;
if (obj == null)
return;
InvokeChangedCallback (obj, property, property.change_cb,
Value.ToObject (property.PropertyType, NativeMethods.property_changed_event_args_get_old_value (propertyChangeArgs)),
Value.ToObject (property.PropertyType, NativeMethods.property_changed_event_args_get_new_value (propertyChangeArgs)));
} catch (Exception ex) {
error = new MoonError (ex);
}
} catch (Exception ex) {
try {
Console.WriteLine ("Moonlight: Unhandled exception in DependencyProperty.UnmanagedPropertyChangedCallback: {0}", ex.Message);
} catch {
}
}
}
bool HasHiddenDefaultValue {
get {
if (!hasHiddenDefaultValue.HasValue)
hasHiddenDefaultValue = Mono.NativeMethods.dependency_property_get_has_hidden_default_value (native);
return hasHiddenDefaultValue.Value;
}
}
internal string Name {
get { return name; }
}
internal bool IsAttached {
get {
if (!attached.HasValue)
attached = NativeMethods.dependency_property_is_attached (native);
return attached.Value;
}
}
internal bool IsNullable {
get { return NativeMethods.dependency_property_is_nullable (native); }
}
internal bool IsValueType {
get { return NativeMethods.type_get_value_type (Deployment.Current.Types.TypeToKind (PropertyType)); }
}
internal Type DeclaringType {
get { return declaring_type; }
}
internal object GetDefaultValue (object ob)
{
return GetDefaultValue (Deployment.Current.Types.TypeToNativeKind (ob.GetType ()));
}
internal virtual object GetDefaultValue (Kind kind)
{
IntPtr ptr;
object ret = null;
// The value from GetDefaultValue does not need to be deleted
ptr = Mono.NativeMethods.dependency_property_get_default_value (native, kind);
if (ptr == IntPtr.Zero) {
// The value from GetAutoCreatedValue does need to be deleted
ptr = NativeMethods.dependency_property_get_auto_created_value (native, kind, IntPtr.Zero);
ret = Value.ToObject (ptr);
NativeMethods.value_delete_value2 (ptr);
} else {
ret = Value.ToObject (PropertyType, ptr);
}
return ret;
}
internal IntPtr Native {
get { return native; }
}
internal Type PropertyType {
get { return property_type; }
}
internal bool IsReadOnly {
get { return NativeMethods.dependency_property_is_read_only (native); }
}
internal ValueValidator Validate {
get { return validator ?? DefaultValidator; }
set { validator = 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;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.Xml.Linq;
using NuGet.ProjectModel;
using Microsoft.Extensions.DependencyModel;
namespace Microsoft.Tools.ServiceModel.Svcutil
{
internal class MSBuildProj : IDisposable
{
private bool _isSaved;
private bool _ownsDirectory;
private readonly ProjectPropertyResolver _propertyResolver;
private XNamespace _msbuildNS;
private MSBuildProj()
{
_propertyResolver = new ProjectPropertyResolver();
}
#region Properties
// Values in this collection have the effect of properties that are passed to MSBuild in the command line which become global properties.
public Dictionary<string, string> GlobalProperties { get; } = new Dictionary<string, string>();
// Netcore projects can specify TargetFramework and/or TargetFrameworks, TargetFramework is always used.
// When only TargetFrameworks is specified, the build system builds the project specifying TargetFramework for each entry.
private string _targetFramework;
public string TargetFramework
{
get { return _targetFramework; }
set { UpdateTargetFramework(value); }
}
private List<string> _targetFrameworks = new List<string>();
public IEnumerable<string> TargetFrameworks { get { return _targetFrameworks; } }
private string _runtimeIdentifier;
public string RuntimeIdentifier
{
get { return _runtimeIdentifier; }
set { SetRuntimeIdentifier(value); }
}
private SortedSet<ProjectDependency> _dependencies = new SortedSet<ProjectDependency>();
public IEnumerable<ProjectDependency> Dependencies { get { return _dependencies; } }
public SortedDictionary<string, string> _resolvedProperties = new SortedDictionary<string, string>();
public IEnumerable<KeyValuePair<string, string>> ResolvedProperties { get { return this._resolvedProperties; } }
public string FileName { get; private set; }
public string DirectoryPath { get; private set; }
public string FullPath { get { return Path.Combine(DirectoryPath, FileName); } }
public string SdkVersion { get; private set; }
private XElement ProjectNode { get; set; }
private XElement _projectReferenceGroup;
private XElement ProjectReferceGroup
{
get
{
if (_projectReferenceGroup == null)
{
IEnumerable<XElement> refItems = this.ProjectNode.Elements("ProjectReference");
if (refItems == null || refItems.Count() == 0)
{
// add ref subgroup
_projectReferenceGroup = new XElement("ItemGroup");
this.ProjectNode.Add(_projectReferenceGroup);
}
else
{
_projectReferenceGroup = refItems.FirstOrDefault().Parent;
}
}
return _projectReferenceGroup;
}
}
private XElement _referenceGroup;
private XElement ReferenceGroup
{
get
{
if (_referenceGroup == null)
{
IEnumerable<XElement> refItems = this.ProjectNode.Elements("Reference");
if (refItems == null || refItems.Count() == 0)
{
// add ref subgroup
_referenceGroup = new XElement("ItemGroup");
this.ProjectNode.Add(_referenceGroup);
}
else
{
_referenceGroup = refItems.FirstOrDefault().Parent;
}
}
return _referenceGroup;
}
}
#endregion
#region Parsing/Settings Methods
public static async Task<MSBuildProj> FromPathAsync(string filePath, ILogger logger, CancellationToken cancellationToken)
{
var project = await ParseAsync(File.ReadAllText(filePath), filePath, logger, cancellationToken).ConfigureAwait(false);
project._isSaved = true;
return project;
}
public static async Task<MSBuildProj> ParseAsync(string projectText, string projectFullPath, ILogger logger, CancellationToken cancellationToken)
{
using (var safeLogger = await SafeLogger.WriteStartOperationAsync(logger, $"Parsing project {Path.GetFileName(projectFullPath)}").ConfigureAwait(false))
{
projectFullPath = Path.GetFullPath(projectFullPath);
MSBuildProj msbuildProj = new MSBuildProj
{
FileName = Path.GetFileName(projectFullPath),
DirectoryPath = Path.GetDirectoryName(projectFullPath)
};
XDocument projDefinition = XDocument.Parse(projectText);
var msbuildNS = XNamespace.None;
if (projDefinition.Root != null && projDefinition.Root.Name != null)
{
msbuildNS = projDefinition.Root.Name.Namespace;
}
msbuildProj._msbuildNS = msbuildNS;
msbuildProj.ProjectNode = projDefinition.Element(msbuildNS + "Project");
if (msbuildProj.ProjectNode == null)
{
throw new Exception(Shared.Resources.ErrorInvalidProjectFormat);
}
// The user project can declare TargetFramework and/or TargetFrameworks property. If both are provided, TargetFramework wins.
// When TargetFrameworks is provided, the project is built for every entry specified in the TargetFramework property.
IEnumerable<XElement> targetFrameworkElements = GetSubGroupValues(msbuildProj.ProjectNode, msbuildNS, "PropertyGroup", "TargetFramework");
if (targetFrameworkElements.Count() > 0)
{
// If property is specified more than once, MSBuild will resolve it by overwriting it with the last value.
var targetFramework = targetFrameworkElements.Last().Value.Trim();
if (!string.IsNullOrWhiteSpace(targetFramework))
{
if (targetFramework.StartsWith("net5.0-"))
{
targetFramework = "net5.0";
}
msbuildProj._targetFrameworks.Add(targetFramework);
}
}
if (msbuildProj._targetFrameworks.Count == 0)
{
// TargetFramework was not provided, check TargetFrameworks property.
IEnumerable<XElement> targetFrameworksElements = GetSubGroupValues(msbuildProj.ProjectNode, msbuildNS, "PropertyGroup", "TargetFrameworks");
if (targetFrameworksElements.Count() > 0)
{
var targetFrameworks = targetFrameworksElements.Last().Value;
foreach (var targetFx in targetFrameworks.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries).Select(p => p.Trim()))
{
if (!string.IsNullOrWhiteSpace(targetFx))
{
msbuildProj._targetFrameworks.Add(targetFx);
}
}
}
}
msbuildProj._targetFramework = TargetFrameworkHelper.GetBestFitTargetFramework(msbuildProj._targetFrameworks);
// Ensure target framework is valid.
FrameworkInfo frameworkInfo = TargetFrameworkHelper.GetValidFrameworkInfo(msbuildProj.TargetFramework);
IEnumerable<XElement> runtimeIdentifierElements = GetSubGroupValues(msbuildProj.ProjectNode, msbuildNS, "PropertyGroup", "RuntimeIdentifier");
if (runtimeIdentifierElements.Count() > 0)
{
msbuildProj.RuntimeIdentifier = runtimeIdentifierElements.Last().Value.Trim();
}
IEnumerable<XElement> packageReferenceElements = GetSubGroupValues(msbuildProj.ProjectNode, msbuildNS, "ItemGroup", "PackageReference");
foreach (XElement reference in packageReferenceElements)
{
if(!TryGetItemIdentity(reference, out var packageName))
continue;
string version = GetItemValue(reference, "Version");
ProjectDependency packageDep = ProjectDependency.FromPackage(packageName, version);
msbuildProj._dependencies.Add(packageDep);
}
IEnumerable<XElement> toolReferenceElements = GetSubGroupValues(msbuildProj.ProjectNode, msbuildNS, "ItemGroup", "DotNetCliToolReference");
foreach (XElement reference in toolReferenceElements)
{
if (!TryGetItemIdentity(reference, out var packageName))
continue;
string version = GetItemValue(reference, "Version");
ProjectDependency packageDep = ProjectDependency.FromCliTool(packageName, version);
msbuildProj._dependencies.Add(packageDep);
}
IEnumerable<XElement> projectReferenceElements = GetSubGroupValues(msbuildProj.ProjectNode, msbuildNS, "ItemGroup", "ProjectReference");
foreach (XElement reference in projectReferenceElements)
{
string projectPath = GetItemValue(reference, "Include", throwIfMissing: true);
ProjectDependency projectDep = ProjectDependency.FromProject(projectPath);
msbuildProj._dependencies.Add(projectDep);
}
IEnumerable<XElement> binReferenceElements = GetSubGroupValues(msbuildProj.ProjectNode, msbuildNS, "ItemGroup", "Reference");
foreach (XElement reference in binReferenceElements)
{
//Find hint path or path
string binReference = GetItemIdentity(reference);
if (!Path.IsPathRooted(binReference))
{
string fullPath = null;
bool fullPathFound = true;
XElement hintPath = reference.Element("HintPath");
XElement path = reference.Element("Path");
if (path != null)
{
fullPath = path.Value;
}
else if (hintPath != null)
{
fullPath = hintPath.Value;
}
else
{
try
{
fullPath = new FileInfo(Path.Combine(msbuildProj.DirectoryPath, binReference)).FullName;
}
catch
{
}
if (fullPath == null || !File.Exists(fullPath))
{
fullPathFound = false;
// If we're only targeting .NET Core or .NET Standard projects we throw if we can't find the full path to the assembly.
if (!TargetFrameworkHelper.ContainsFullFrameworkTarget(msbuildProj._targetFrameworks))
{
throw new Exception(string.Format(CultureInfo.CurrentCulture, Shared.Resources.ErrorProjectReferenceMissingFilePathFormat, binReference));
}
}
}
if (fullPathFound)
{
if (System.IO.Directory.Exists(fullPath)) // IsDir?
{
fullPath = Path.Combine(fullPath, binReference);
}
else if (Directory.Exists(Path.Combine(msbuildProj.DirectoryPath, fullPath)))
{
fullPath = Path.Combine(msbuildProj.DirectoryPath, fullPath, binReference);
}
binReference = fullPath;
}
}
ProjectDependency projectDep = ProjectDependency.FromAssembly(binReference);
msbuildProj._dependencies.Add(projectDep);
}
// ensure we have a working directory for the ProcessRunner (ProjectPropertyResolver)..
if (!Directory.Exists(msbuildProj.DirectoryPath))
{
Directory.CreateDirectory(msbuildProj.DirectoryPath);
msbuildProj._ownsDirectory = true;
}
var sdkVersion = await ProjectPropertyResolver.GetSdkVersionAsync(msbuildProj.DirectoryPath, logger, cancellationToken).ConfigureAwait(false);
msbuildProj.SdkVersion = sdkVersion ?? string.Empty;
return msbuildProj;
}
}
public static async Task<MSBuildProj> DotNetNewAsync(string fullPath, ILogger logger, CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested();
MSBuildProj project = null;
bool ownsDir = false;
if (fullPath == null)
{
throw new ArgumentNullException(nameof(fullPath));
}
fullPath = Path.GetFullPath(fullPath);
string projectName = Path.GetFileNameWithoutExtension(fullPath);
string projectExtension = Path.GetExtension(fullPath);
string projectDir = Path.GetDirectoryName(fullPath);
if (string.IsNullOrEmpty(projectName) || string.CompareOrdinal(projectExtension.ToLowerInvariant(), ".csproj") != 0)
{
throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, Shared.Resources.ErrorFullPathNotAProjectFilePathFormat, fullPath));
}
if (File.Exists(fullPath))
{
throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, Shared.Resources.ErrorProjectFileAlreadyExistsFormat, fullPath));
}
// ensure we have a working directory for the ProcessRunner (ProjectPropertyResolver).
if (!Directory.Exists(projectDir))
{
Directory.CreateDirectory(projectDir);
ownsDir = true;
}
var sdkVersion = await ProjectPropertyResolver.GetSdkVersionAsync(projectDir, logger, cancellationToken).ConfigureAwait(false);
var dotnetNewParams = $"new console {GetNoRestoreParam(sdkVersion)} --force --type project --language C# --output . --name {projectName}";
await ProcessRunner.RunAsync("dotnet", dotnetNewParams, projectDir, logger, cancellationToken).ConfigureAwait(false);
project = await ParseAsync(File.ReadAllText(fullPath), fullPath, logger, cancellationToken).ConfigureAwait(false);
project._ownsDirectory = ownsDir;
project.SdkVersion = sdkVersion ?? string.Empty;
project._isSaved = true;
return project;
}
private static IEnumerable<XElement> GetGroupValues(XElement projectElement, string group, bool createOnMissing = false)
{
// XElement.Elements() always returns a collection, no need to check for null.
IEnumerable<XElement> groups = projectElement.Elements(group);
if (createOnMissing && groups.Count() == 0)
{
// add a property group
XElement propertyGroup = new XElement(group);
projectElement.Add(propertyGroup);
return new XElement[] { propertyGroup };
}
return groups;
}
//Used for both references and properties
private static IEnumerable<XElement> GetSubGroupValues(XElement projectElement, XNamespace msbuildNS, string group, string subGroupName)
{
IEnumerable<XElement> groups = GetGroupValues(projectElement, group);
IEnumerable<XElement> subGroupValues = groups.Elements(msbuildNS + subGroupName);
return subGroupValues;
}
private static string GetItemValue(XElement reference, string itemName, bool throwIfMissing = false)
{
// XElement.Attributes() alwasy returns a collection, no need to check for null.
var itemAttribue = reference.Attributes().FirstOrDefault(item => item.Name == itemName);
if (itemAttribue != null)
{
return itemAttribue.Value;
}
XElement itemNameElement = null;
itemNameElement = reference.Elements().FirstOrDefault(item => item.Name == itemName);
if (itemNameElement != null)
{
return itemNameElement.Value;
}
if (throwIfMissing)
{
throw new Exception(Shared.Resources.ErrorInvalidProjectFormat);
}
return null;
}
public static bool TryGetItemIdentity(XElement itemName, out string itemIdentity)
{
var itemAttribute = itemName.Attributes().FirstOrDefault(item => item.Name == "Include");
if (itemAttribute != null)
{
itemIdentity = itemAttribute.Value;
return true;
}
itemIdentity = default;
return false;
}
private static string GetItemIdentity(XElement itemName)
{
var itemAttribute = itemName.Attributes().FirstOrDefault(item => item.Name == "Include");
if (itemAttribute != null)
{
return itemAttribute.Value;
}
throw new Exception(Shared.Resources.ErrorInvalidProjectFormat);
}
public bool AddDependency(ProjectDependency dependency)
{
// a nuget package can contain multiple assemblies, we need to filter package references so we don't add dups.
bool addDependency = !_dependencies.Any(d =>
{
switch (d.DependencyType)
{
case ProjectDependencyType.Package:
case ProjectDependencyType.Tool:
return d.Name == dependency.Name;
default:
if (d.FullPath == null && dependency.FullPath == null)
{
goto case ProjectDependencyType.Package;
}
return d.FullPath == dependency.FullPath;
}
});
if (addDependency)
{
switch (dependency.DependencyType)
{
case ProjectDependencyType.Project:
this.ProjectReferceGroup.Add(new XElement("ProjectReference", new XAttribute("Include", dependency.FullPath)));
break;
case ProjectDependencyType.Binary:
this.ReferenceGroup.Add(new XElement("Reference", new XAttribute("Include", dependency.AssemblyName), new XElement("HintPath", dependency.FullPath)));
break;
case ProjectDependencyType.Package:
this.ReferenceGroup.Add(new XElement("PackageReference", new XAttribute("Include", dependency.Name), new XAttribute("Version", dependency.Version)));
break;
case ProjectDependencyType.Tool:
this.ReferenceGroup.Add(new XElement("DotNetCliToolReference", new XAttribute("Include", dependency.Name), new XAttribute("Version", dependency.Version)));
break;
}
_dependencies.Add(dependency);
_isSaved = false;
}
return addDependency;
}
// Sets the property value in a PropertyGroup. Returns true if the value was changed, and false if it was already set to that value.
private bool SetPropertyValue(string propertyName, string value)
{
XElement element = new XElement(propertyName, null);
IEnumerable<XElement> existingElements = GetSubGroupValues(this.ProjectNode, _msbuildNS, "PropertyGroup", propertyName);
if (existingElements.Count() > 0)
{
element = existingElements.Last();
}
else
{
IEnumerable<XElement> propertyGroupItems = GetGroupValues(this.ProjectNode, "PropertyGroup", createOnMissing: true);
XElement propertyGroup = propertyGroupItems.First();
propertyGroup.Add(element);
}
if (element.Value != value)
{
element.SetValue(value);
return true;
}
return false;
}
private void SetRuntimeIdentifier(string runtimeIdentifier)
{
if (this.RuntimeIdentifier != runtimeIdentifier && !string.IsNullOrWhiteSpace(runtimeIdentifier))
{
if (SetPropertyValue("RuntimeIdentifier", runtimeIdentifier))
{
_runtimeIdentifier = runtimeIdentifier;
_isSaved = false;
}
}
}
public void ClearWarningsAsErrors()
{
// Add an empty WarningsAsErrors element to clear the list, and treat them as warnings.
SetPropertyValue("WarningsAsErrors", string.Empty);
}
private void UpdateTargetFramework(string targetFramework)
{
if (_targetFramework != targetFramework && !string.IsNullOrWhiteSpace(targetFramework))
{
// validate framework
TargetFrameworkHelper.GetValidFrameworkInfo(targetFramework);
if (!_targetFrameworks.Contains(targetFramework))
{
// replace values (if existing).
if (_targetFramework != null && _targetFrameworks.Contains(_targetFramework))
{
_targetFrameworks.Remove(_targetFramework);
}
_targetFrameworks.Add(targetFramework);
}
IEnumerable<XElement> targetFrameworkElements = GetSubGroupValues(this.ProjectNode, _msbuildNS, "PropertyGroup", "TargetFramework");
if (targetFrameworkElements.Count() > 0)
{
var targetFrameworkNode = targetFrameworkElements.Last();
targetFrameworkNode.SetValue(targetFramework);
}
// TargetFramework was not provided, check TargetFrameworks property.
IEnumerable<XElement> targetFrameworksElements = GetSubGroupValues(this.ProjectNode, _msbuildNS, "PropertyGroup", "TargetFrameworks");
if (targetFrameworksElements.Count() > 0)
{
var targetFrameworksNode = targetFrameworksElements.Last();
targetFrameworksNode.SetValue(_targetFrameworks.Aggregate((tfs, tf) => $"{tfs};{tf}"));
}
_targetFramework = targetFramework;
_isSaved = false;
}
}
#endregion
#region Operation Methods
public async Task SaveAsync(bool force, ILogger logger, CancellationToken cancellationToken)
{
_isSaved &= !force;
await SaveAsync(logger, cancellationToken).ConfigureAwait(false);
}
public async Task SaveAsync(ILogger logger, CancellationToken cancellationToken)
{
ThrowOnDisposed();
cancellationToken.ThrowIfCancellationRequested();
if (!_isSaved)
{
using (await SafeLogger.WriteStartOperationAsync(logger, $"Saving project file: \"{this.FullPath}\"").ConfigureAwait(false))
{
if (!Directory.Exists(this.DirectoryPath))
{
Directory.CreateDirectory(this.DirectoryPath);
_ownsDirectory = true;
}
using (StreamWriter writer = File.CreateText(this.FullPath))
{
await AsyncHelper.RunAsync(() => ProjectNode.Save(writer), cancellationToken).ConfigureAwait(false);
}
_isSaved = true;
}
}
}
public async Task<ProcessRunner.ProcessResult> RestoreAsync(ILogger logger, CancellationToken cancellationToken)
{
ThrowOnDisposed();
if (!_isSaved)
{
await this.SaveAsync(logger, cancellationToken).ConfigureAwait(false);
}
var restoreParams = "restore --ignore-failed-sources" + (string.IsNullOrWhiteSpace(this.RuntimeIdentifier) ? "" : (" -r " + this.RuntimeIdentifier));
// Restore no-dependencies first to workaround NuGet issue https://github.com/NuGet/Home/issues/4979
await ProcessRunner.TryRunAsync("dotnet", restoreParams + " --no-dependencies", this.DirectoryPath, logger, cancellationToken).ConfigureAwait(false);
var result = await ProcessRunner.TryRunAsync("dotnet", restoreParams, this.DirectoryPath, logger, cancellationToken).ConfigureAwait(false);
return result;
}
/// <summary>
/// Builds the project and optionally restores it before building. If restore is false the project is not saved automatically.
/// </summary>
/// <returns></returns>
public async Task<ProcessRunner.ProcessResult> BuildAsync(bool restore, ILogger logger, CancellationToken cancellationToken)
{
if (restore)
{
await this.RestoreAsync(logger, cancellationToken).ConfigureAwait(false);
}
return await BuildAsync(logger, cancellationToken).ConfigureAwait(false);
}
public async Task<ProcessRunner.ProcessResult> BuildAsync(ILogger logger, CancellationToken cancellationToken)
{
ThrowOnDisposed();
string buildParams = $"build {GetNoRestoreParam(this.SdkVersion)}";
return await ProcessRunner.RunAsync("dotnet", buildParams, this.DirectoryPath, logger, cancellationToken).ConfigureAwait(false);
}
#endregion
#region Helper Methods
public async Task<IEnumerable<ProjectDependency>> ResolveProjectReferencesAsync(IEnumerable<ProjectDependency> excludeDependencies, ILogger logger, CancellationToken cancellationToken)
{
ThrowOnDisposed();
IEnumerable<ProjectDependency> dependencies = null;
if (excludeDependencies == null)
{
excludeDependencies = new List<ProjectDependency>();
}
using (var safeLogger = await SafeLogger.WriteStartOperationAsync(logger, "Resolving project references ...").ConfigureAwait(false))
{
if (_targetFrameworks.Count == 1 && TargetFrameworkHelper.IsSupportedFramework(this.TargetFramework, out var frameworkInfo) && frameworkInfo.IsDnx)
{
await this.RestoreAsync(logger, cancellationToken).ConfigureAwait(false);
var packageReferences = await ResolvePackageReferencesAsync(logger, cancellationToken).ConfigureAwait(false);
var assemblyReferences = await ResolveAssemblyReferencesAsync(logger, cancellationToken).ConfigureAwait(false);
dependencies = packageReferences.Union(assemblyReferences).Except(excludeDependencies);
}
else
{
await safeLogger.WriteWarningAsync(Shared.Resources.WarningMultiFxOrNoSupportedDnxVersion, logToUI: true).ConfigureAwait(false);
dependencies = new List<ProjectDependency>();
}
await safeLogger.WriteMessageAsync($"Resolved project reference count: {dependencies.Count()}", logToUI: false).ConfigureAwait(false);
}
return dependencies;
}
private async Task<List<ProjectDependency>> ResolvePackageReferencesAsync(ILogger logger, CancellationToken cancellationToken)
{
ThrowOnDisposed();
cancellationToken.ThrowIfCancellationRequested();
var packageDependencies = new List<ProjectDependency>();
using (var safeLogger = await SafeLogger.WriteStartOperationAsync(logger, "Resolving package references ...").ConfigureAwait(false))
{
await AsyncHelper.RunAsync(async () =>
{
try
{
var assetsFile = new FileInfo(Path.Combine(this.DirectoryPath, "obj", "project.assets.json")).FullName;
if (File.Exists(assetsFile))
{
LockFile lockFile = LockFileUtilities.GetLockFile(assetsFile, logger as NuGet.Common.ILogger);
if (lockFile != null)
{
if (lockFile.Targets.Count == 1)
{
foreach (var lib in lockFile.Targets[0].Libraries)
{
bool isPackage = StringComparer.OrdinalIgnoreCase.Compare(lib.Type, "package") == 0;
if (isPackage)
{
foreach (var compiletimeAssembly in lib.CompileTimeAssemblies)
{
if (Path.GetExtension(compiletimeAssembly.Path) == ".dll")
{
var dependency = ProjectDependency.FromPackage(Path.GetFileNameWithoutExtension(compiletimeAssembly.Path), lib.Name, lib.Version.ToNormalizedString());
var itemIdx = packageDependencies.IndexOf(dependency);
if (itemIdx == -1)
{
packageDependencies.Add(dependency);
}
else if (dependency.IsFramework)
{
// packages can be described individually and/or as part of a platform metapackage in the lock file; for instance: Microsoft.CSharp is a package that is part of Microsoft.NetCore.
packageDependencies[itemIdx] = dependency;
}
}
}
}
}
packageDependencies.Sort();
}
else
{
await safeLogger.WriteWarningAsync(Shared.Resources.WarningMultiFxOrNoSupportedDnxVersion, logToUI: true).ConfigureAwait(false);
}
}
else
{
await safeLogger.WriteWarningAsync(Shared.Resources.WarningCannotResolveProjectReferences, logToUI: true).ConfigureAwait(false);
}
}
}
catch (Exception ex)
{
if (Utils.IsFatalOrUnexpected(ex)) throw;
await safeLogger.WriteWarningAsync(ex.Message, logToUI: false).ConfigureAwait(false);
}
}, cancellationToken).ConfigureAwait(false);
await safeLogger.WriteMessageAsync($"Package reference count: {packageDependencies.Count}", logToUI: false).ConfigureAwait(false);
}
return packageDependencies;
}
private async Task<List<ProjectDependency>> ResolveAssemblyReferencesAsync(ILogger logger, CancellationToken cancellationToken)
{
ThrowOnDisposed();
cancellationToken.ThrowIfCancellationRequested();
var assemblyDependencies = new List<ProjectDependency>();
using (var safeLogger = await SafeLogger.WriteStartOperationAsync(logger, $"Resolving assembly references for {this.TargetFramework} target framework ...").ConfigureAwait(false))
{
await ResolveProperyValuesAsync(new string[] { "OutputPath", "TargetPath" }, logger, cancellationToken).ConfigureAwait(false);
var outputPath = this._resolvedProperties["OutputPath"];
if (!Path.IsPathRooted(outputPath))
{
outputPath = Path.Combine(this.DirectoryPath, outputPath.Trim(new char[] { '\"' }));
}
var depsFile = this.GlobalProperties.TryGetValue("Configuration", out var activeConfiguration) && !string.IsNullOrWhiteSpace(activeConfiguration) ?
Path.Combine(outputPath, $"{Path.GetFileNameWithoutExtension(this.FileName)}.deps.json") :
await ResolveDepsFilePathFromBuildConfigAsync(outputPath, logger, cancellationToken).ConfigureAwait(false);
if (File.Exists(depsFile))
{
await AsyncHelper.RunAsync(async () =>
{
try
{
DependencyContext depContext = null;
using (var stream = File.OpenRead(depsFile))
{
depContext = new DependencyContextJsonReader().Read(stream);
}
var targetLib = Path.GetFileName(this._resolvedProperties["TargetPath"].Trim('\"'));
if (string.IsNullOrEmpty(targetLib))
{
targetLib = $"{Path.ChangeExtension(this.FileName, ".dll")}";
}
foreach (var rtLib in depContext.RuntimeLibraries.Where(l => l.NativeLibraryGroups.Count == 0))
{
ProjectDependency dependency = null;
switch (rtLib.Type)
{
case "project":
case "reference":
foreach (var assemblyGroup in rtLib.RuntimeAssemblyGroups)
{
foreach (var assetPath in assemblyGroup.AssetPaths)
{
if (!Path.GetFileName(assetPath).Equals(targetLib, RuntimeEnvironmentHelper.FileStringComparison))
{
dependency = ProjectDependency.FromAssembly(Path.Combine(outputPath, assetPath));
if (File.Exists(dependency.FullPath) && !assemblyDependencies.Contains(dependency))
{
assemblyDependencies.Add(dependency);
}
}
}
}
break;
//case "package":
default:
break;
}
}
}
catch (Exception ex)
{
if (Utils.IsFatalOrUnexpected(ex)) throw;
await safeLogger.WriteWarningAsync(ex.Message, logToUI: false).ConfigureAwait(false);
}
}, cancellationToken).ConfigureAwait(false);
assemblyDependencies.Sort();
}
else
{
await safeLogger.WriteWarningAsync("Deps file not found (project not built), unable to resolve assembly/project dependencies!", logToUI: false).ConfigureAwait(false);
}
await safeLogger.WriteMessageAsync($"Assembly reference count: {assemblyDependencies.Count}", logToUI: false).ConfigureAwait(false);
}
return assemblyDependencies;
}
public async Task<IEnumerable<KeyValuePair<string, string>>> ResolveProperyValuesAsync(IEnumerable<string> propertyNames, ILogger logger, CancellationToken cancellationToken)
{
ThrowOnDisposed();
cancellationToken.ThrowIfCancellationRequested();
if (propertyNames == null)
{
throw new ArgumentNullException(nameof(propertyNames));
}
if (!this.GlobalProperties.Any(p => p.Key == "TargetFramework"))
{
this.GlobalProperties["TargetFramework"] = this.TargetFramework;
}
if (!this.GlobalProperties.Any(p => p.Key == "SdkVersion"))
{
this.GlobalProperties["SdkVersion"] = this.SdkVersion;
}
if (!propertyNames.All(p => this._resolvedProperties.Keys.Contains(p)))
{
var propertyTable = this._resolvedProperties.Where(p => propertyNames.Contains(p.Key));
if (propertyTable.Count() != propertyNames.Count())
{
propertyTable = await _propertyResolver.EvaluateProjectPropertiesAsync(this.FullPath, this.TargetFramework, propertyNames, this.GlobalProperties, logger, cancellationToken).ConfigureAwait(false);
foreach (var entry in propertyTable)
{
this._resolvedProperties[entry.Key] = entry.Value;
}
}
}
return this._resolvedProperties.Where(p => propertyNames.Contains(p.Key));
}
private async Task<string> ResolveDepsFilePathFromBuildConfigAsync(string outputPath, ILogger logger, CancellationToken cancellationToken)
{
// Since we are resolving the deps file path it means the passed in outputPath is built using the default build
// configuration (debug/release). We need to resolve the configuration by looking at the most recent build in the
// output path. The output should look something like 'bin\Debug\netcoreapp1.0\HelloSvcutil.deps.json'
using (var safeLogger = await SafeLogger.WriteStartOperationAsync(logger, $"Resolving deps.json file ...").ConfigureAwait(false))
{
var fileName = $"{Path.GetFileNameWithoutExtension(this.FileName)}.deps.json";
var depsFile = string.Empty;
// find the most recent deps.json files under the project's bin folder built for the project's target framework.
var binFolder = await PathHelper.TryFindFolderAsync("bin", outputPath, logger, cancellationToken).ConfigureAwait(false);
if (Directory.Exists(binFolder))
{
var depsFiles = Directory.GetFiles(binFolder, "*", SearchOption.AllDirectories)
.Where(d => Path.GetFileName(d).Equals(fileName, RuntimeEnvironmentHelper.FileStringComparison))
.Where(f => PathHelper.GetFolderName(Path.GetDirectoryName(f)) == this.TargetFramework)
.Select(f => new FileInfo(f))
.OrderByDescending(f => f.CreationTimeUtc);
depsFile = depsFiles.FirstOrDefault()?.FullName;
}
await safeLogger.WriteMessageAsync($"deps file: {depsFile}", logToUI: false).ConfigureAwait(false);
return depsFile;
}
}
public override string ToString()
{
return this.FullPath;
}
private void ThrowOnDisposed()
{
if (_disposed)
{
throw new ObjectDisposedException(nameof(MSBuildProj));
}
}
private static string GetNoRestoreParam(string sdkVersion)
{
if (string.IsNullOrEmpty(sdkVersion) || sdkVersion.StartsWith("1", StringComparison.OrdinalIgnoreCase))
{
return string.Empty;
}
return "--no-restore";
}
#endregion
#region IDisposable Support
private bool _disposed = false;
protected virtual void Dispose(bool disposing)
{
if (!_disposed)
{
if (disposing)
{
try
{
if (_ownsDirectory && Directory.Exists(this.DirectoryPath) && !DebugUtils.KeepTemporaryDirs)
{
try { Directory.Delete(this.DirectoryPath, recursive: true); } catch { }
}
}
catch
{
}
}
_disposed = true;
}
}
public void Dispose()
{
Dispose(true);
}
#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.
/******************************************************************************
* This file is auto-generated from a template file by the GenerateTests.csx *
* script in tests\src\JIT\HardwareIntrinsics\X86\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.X86;
namespace JIT.HardwareIntrinsics.X86
{
public static partial class Program
{
private static void AddInt32()
{
var test = new SimpleBinaryOpTest__AddInt32();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
if (Avx.IsSupported)
{
// Validates basic functionality works, using Load
test.RunBasicScenario_Load();
// Validates basic functionality works, using LoadAligned
test.RunBasicScenario_LoadAligned();
}
// Validates calling via reflection works, using Unsafe.Read
test.RunReflectionScenario_UnsafeRead();
if (Avx.IsSupported)
{
// Validates calling via reflection works, using Load
test.RunReflectionScenario_Load();
// Validates calling via reflection works, using LoadAligned
test.RunReflectionScenario_LoadAligned();
}
// Validates passing a static member works
test.RunClsVarScenario();
if (Avx.IsSupported)
{
// Validates passing a static member works, using pinning and Load
test.RunClsVarScenario_Load();
}
// Validates passing a local works, using Unsafe.Read
test.RunLclVarScenario_UnsafeRead();
if (Avx.IsSupported)
{
// Validates passing a local works, using Load
test.RunLclVarScenario_Load();
// Validates passing a local works, using LoadAligned
test.RunLclVarScenario_LoadAligned();
}
// Validates passing the field of a local class works
test.RunClassLclFldScenario();
if (Avx.IsSupported)
{
// Validates passing the field of a local class works, using pinning and Load
test.RunClassLclFldScenario_Load();
}
// Validates passing an instance member of a class works
test.RunClassFldScenario();
if (Avx.IsSupported)
{
// Validates passing an instance member of a class works, using pinning and Load
test.RunClassFldScenario_Load();
}
// Validates passing the field of a local struct works
test.RunStructLclFldScenario();
if (Avx.IsSupported)
{
// Validates passing the field of a local struct works, using pinning and Load
test.RunStructLclFldScenario_Load();
}
// Validates passing an instance member of a struct works
test.RunStructFldScenario();
if (Avx.IsSupported)
{
// Validates passing an instance member of a struct works, using pinning and Load
test.RunStructFldScenario_Load();
}
}
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 SimpleBinaryOpTest__AddInt32
{
private struct DataTable
{
private byte[] inArray1;
private byte[] inArray2;
private byte[] outArray;
private GCHandle inHandle1;
private GCHandle inHandle2;
private GCHandle outHandle;
private ulong alignment;
public DataTable(Int32[] inArray1, Int32[] inArray2, Int32[] outArray, int alignment)
{
int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Int32>();
int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Int32>();
int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Int32>();
if ((alignment != 32 && alignment != 16) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2 || (alignment * 2) < sizeOfoutArray)
{
throw new ArgumentException("Invalid value of alignment");
}
this.inArray1 = new byte[alignment * 2];
this.inArray2 = new byte[alignment * 2];
this.outArray = new byte[alignment * 2];
this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned);
this.inHandle2 = GCHandle.Alloc(this.inArray2, GCHandleType.Pinned);
this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned);
this.alignment = (ulong)alignment;
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<Int32, byte>(ref inArray1[0]), (uint)sizeOfinArray1);
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<Int32, byte>(ref inArray2[0]), (uint)sizeOfinArray2);
}
public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment);
public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment);
public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment);
public void Dispose()
{
inHandle1.Free();
inHandle2.Free();
outHandle.Free();
}
private static unsafe void* Align(byte* buffer, ulong expectedAlignment)
{
return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1));
}
}
private struct TestStruct
{
public Vector256<Int32> _fld1;
public Vector256<Int32> _fld2;
public static TestStruct Create()
{
var testStruct = new TestStruct();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int32>, byte>(ref testStruct._fld1), ref Unsafe.As<Int32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Int32>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int32>, byte>(ref testStruct._fld2), ref Unsafe.As<Int32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<Int32>>());
return testStruct;
}
public void RunStructFldScenario(SimpleBinaryOpTest__AddInt32 testClass)
{
var result = Avx2.Add(_fld1, _fld2);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr);
}
public void RunStructFldScenario_Load(SimpleBinaryOpTest__AddInt32 testClass)
{
fixed (Vector256<Int32>* pFld1 = &_fld1)
fixed (Vector256<Int32>* pFld2 = &_fld2)
{
var result = Avx2.Add(
Avx.LoadVector256((Int32*)(pFld1)),
Avx.LoadVector256((Int32*)(pFld2))
);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr);
}
}
}
private static readonly int LargestVectorSize = 32;
private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector256<Int32>>() / sizeof(Int32);
private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector256<Int32>>() / sizeof(Int32);
private static readonly int RetElementCount = Unsafe.SizeOf<Vector256<Int32>>() / sizeof(Int32);
private static Int32[] _data1 = new Int32[Op1ElementCount];
private static Int32[] _data2 = new Int32[Op2ElementCount];
private static Vector256<Int32> _clsVar1;
private static Vector256<Int32> _clsVar2;
private Vector256<Int32> _fld1;
private Vector256<Int32> _fld2;
private DataTable _dataTable;
static SimpleBinaryOpTest__AddInt32()
{
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int32>, byte>(ref _clsVar1), ref Unsafe.As<Int32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Int32>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int32>, byte>(ref _clsVar2), ref Unsafe.As<Int32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<Int32>>());
}
public SimpleBinaryOpTest__AddInt32()
{
Succeeded = true;
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int32>, byte>(ref _fld1), ref Unsafe.As<Int32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Int32>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int32>, byte>(ref _fld2), ref Unsafe.As<Int32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<Int32>>());
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt32(); }
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt32(); }
_dataTable = new DataTable(_data1, _data2, new Int32[RetElementCount], LargestVectorSize);
}
public bool IsSupported => Avx2.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead));
var result = Avx2.Add(
Unsafe.Read<Vector256<Int32>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector256<Int32>>(_dataTable.inArray2Ptr)
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load));
var result = Avx2.Add(
Avx.LoadVector256((Int32*)(_dataTable.inArray1Ptr)),
Avx.LoadVector256((Int32*)(_dataTable.inArray2Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned));
var result = Avx2.Add(
Avx.LoadAlignedVector256((Int32*)(_dataTable.inArray1Ptr)),
Avx.LoadAlignedVector256((Int32*)(_dataTable.inArray2Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead));
var result = typeof(Avx2).GetMethod(nameof(Avx2.Add), new Type[] { typeof(Vector256<Int32>), typeof(Vector256<Int32>) })
.Invoke(null, new object[] {
Unsafe.Read<Vector256<Int32>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector256<Int32>>(_dataTable.inArray2Ptr)
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Int32>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load));
var result = typeof(Avx2).GetMethod(nameof(Avx2.Add), new Type[] { typeof(Vector256<Int32>), typeof(Vector256<Int32>) })
.Invoke(null, new object[] {
Avx.LoadVector256((Int32*)(_dataTable.inArray1Ptr)),
Avx.LoadVector256((Int32*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Int32>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned));
var result = typeof(Avx2).GetMethod(nameof(Avx2.Add), new Type[] { typeof(Vector256<Int32>), typeof(Vector256<Int32>) })
.Invoke(null, new object[] {
Avx.LoadAlignedVector256((Int32*)(_dataTable.inArray1Ptr)),
Avx.LoadAlignedVector256((Int32*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Int32>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = Avx2.Add(
_clsVar1,
_clsVar2
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr);
}
public void RunClsVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load));
fixed (Vector256<Int32>* pClsVar1 = &_clsVar1)
fixed (Vector256<Int32>* pClsVar2 = &_clsVar2)
{
var result = Avx2.Add(
Avx.LoadVector256((Int32*)(pClsVar1)),
Avx.LoadVector256((Int32*)(pClsVar2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr);
}
}
public void RunLclVarScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead));
var op1 = Unsafe.Read<Vector256<Int32>>(_dataTable.inArray1Ptr);
var op2 = Unsafe.Read<Vector256<Int32>>(_dataTable.inArray2Ptr);
var result = Avx2.Add(op1, op2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load));
var op1 = Avx.LoadVector256((Int32*)(_dataTable.inArray1Ptr));
var op2 = Avx.LoadVector256((Int32*)(_dataTable.inArray2Ptr));
var result = Avx2.Add(op1, op2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned));
var op1 = Avx.LoadAlignedVector256((Int32*)(_dataTable.inArray1Ptr));
var op2 = Avx.LoadAlignedVector256((Int32*)(_dataTable.inArray2Ptr));
var result = Avx2.Add(op1, op2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new SimpleBinaryOpTest__AddInt32();
var result = Avx2.Add(test._fld1, test._fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load));
var test = new SimpleBinaryOpTest__AddInt32();
fixed (Vector256<Int32>* pFld1 = &test._fld1)
fixed (Vector256<Int32>* pFld2 = &test._fld2)
{
var result = Avx2.Add(
Avx.LoadVector256((Int32*)(pFld1)),
Avx.LoadVector256((Int32*)(pFld2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = Avx2.Add(_fld1, _fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr);
}
public void RunClassFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load));
fixed (Vector256<Int32>* pFld1 = &_fld1)
fixed (Vector256<Int32>* pFld2 = &_fld2)
{
var result = Avx2.Add(
Avx.LoadVector256((Int32*)(pFld1)),
Avx.LoadVector256((Int32*)(pFld2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr);
}
}
public void RunStructLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario));
var test = TestStruct.Create();
var result = Avx2.Add(test._fld1, test._fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunStructLclFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load));
var test = TestStruct.Create();
var result = Avx2.Add(
Avx.LoadVector256((Int32*)(&test._fld1)),
Avx.LoadVector256((Int32*)(&test._fld2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunStructFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario));
var test = TestStruct.Create();
test.RunStructFldScenario(this);
}
public void RunStructFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load));
var test = TestStruct.Create();
test.RunStructFldScenario_Load(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(Vector256<Int32> op1, Vector256<Int32> op2, void* result, [CallerMemberName] string method = "")
{
Int32[] inArray1 = new Int32[Op1ElementCount];
Int32[] inArray2 = new Int32[Op2ElementCount];
Int32[] outArray = new Int32[RetElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<Int32, byte>(ref inArray1[0]), op1);
Unsafe.WriteUnaligned(ref Unsafe.As<Int32, byte>(ref inArray2[0]), op2);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<Int32>>());
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(void* op1, void* op2, void* result, [CallerMemberName] string method = "")
{
Int32[] inArray1 = new Int32[Op1ElementCount];
Int32[] inArray2 = new Int32[Op2ElementCount];
Int32[] outArray = new Int32[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector256<Int32>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector256<Int32>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<Int32>>());
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(Int32[] left, Int32[] right, Int32[] result, [CallerMemberName] string method = "")
{
bool succeeded = true;
if ((int)(left[0] + right[0]) != result[0])
{
succeeded = false;
}
else
{
for (var i = 1; i < RetElementCount; i++)
{
if ((int)(left[i] + right[i]) != result[i])
{
succeeded = false;
break;
}
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(Avx2)}.{nameof(Avx2.Add)}<Int32>(Vector256<Int32>, Vector256<Int32>): {method} failed:");
TestLibrary.TestFramework.LogInformation($" left: ({string.Join(", ", left)})");
TestLibrary.TestFramework.LogInformation($" right: ({string.Join(", ", right)})");
TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reactive.Linq;
using System.Threading.Tasks;
using Obvs.Configuration;
using Obvs.Extensions;
using Obvs.Types;
namespace Obvs
{
public interface IServiceBusClient : IServiceBusClient<IMessage, ICommand, IEvent, IRequest, IResponse>
{
}
public interface IServiceBusClient<TMessage, in TCommand, out TEvent, in TRequest, TResponse>
where TMessage : class
where TCommand : class, TMessage
where TEvent : class, TMessage
where TRequest : class, TMessage
where TResponse : class, TMessage
{
IObservable<TEvent> Events { get; }
Task SendAsync(TCommand command);
Task SendAsync(IEnumerable<TCommand> commands);
IObservable<TResponse> GetResponses(TRequest request);
IObservable<T> GetResponses<T>(TRequest request) where T : TResponse;
IObservable<T> GetResponse<T>(TRequest request) where T : TResponse;
IObservable<Exception> Exceptions { get; }
}
public class ServiceBusClient : IServiceBusClient, IDisposable
{
private readonly IServiceBusClient<IMessage, ICommand, IEvent, IRequest, IResponse> _serviceBusClient;
public ServiceBusClient(IServiceBusClient<IMessage, ICommand, IEvent, IRequest, IResponse> serviceBusClient)
{
_serviceBusClient = serviceBusClient;
}
public IObservable<IEvent> Events => _serviceBusClient.Events;
public Task SendAsync(ICommand command)
{
return _serviceBusClient.SendAsync(command);
}
public Task SendAsync(IEnumerable<ICommand> commands)
{
return _serviceBusClient.SendAsync(commands);
}
public IObservable<IResponse> GetResponses(IRequest request)
{
return _serviceBusClient.GetResponses(request);
}
public IObservable<T> GetResponses<T>(IRequest request) where T : IResponse
{
return _serviceBusClient.GetResponses<T>(request);
}
public IObservable<T> GetResponse<T>(IRequest request) where T : IResponse
{
return _serviceBusClient.GetResponse<T>(request);
}
public IObservable<Exception> Exceptions => _serviceBusClient.Exceptions;
public void Dispose()
{
((IDisposable)_serviceBusClient).Dispose();
}
}
public class ServiceBusClient<TMessage, TCommand, TEvent, TRequest, TResponse> : ServiceBusErrorHandlingBase<TMessage, TCommand, TEvent, TRequest, TResponse>, IServiceBusClient<TMessage, TCommand, TEvent, TRequest, TResponse>
where TMessage : class
where TCommand : class, TMessage
where TEvent : class, TMessage
where TRequest : class, TMessage
where TResponse : class, TMessage
{
protected readonly IEnumerable<IServiceEndpoint<TMessage, TCommand, TEvent, TRequest, TResponse>> Endpoints;
private readonly IEnumerable<IServiceEndpointClient<TMessage, TCommand, TEvent, TRequest, TResponse>> _endpointClients;
private readonly IRequestCorrelationProvider<TRequest, TResponse> _requestCorrelationProvider;
private readonly IServiceBus<TMessage, TCommand, TEvent, TRequest, TResponse> _localBus;
private readonly LocalBusOptions _localBusOption;
public ServiceBusClient(IEnumerable<IServiceEndpointClient<TMessage, TCommand, TEvent, TRequest, TResponse>> endpointClients,
IEnumerable<IServiceEndpoint<TMessage, TCommand, TEvent, TRequest, TResponse>> endpoints,
IRequestCorrelationProvider<TRequest, TResponse> requestCorrelationProvider,
IServiceBus<TMessage, TCommand, TEvent, TRequest, TResponse> localBus = null, LocalBusOptions localBusOption = LocalBusOptions.MessagesWithNoEndpointClients)
{
_localBus = localBus;
_localBusOption = localBusOption;
Endpoints = endpoints.ToList();
_endpointClients = endpointClients.ToArray();
Events = _endpointClients
.Select(endpointClient => endpointClient.EventsWithErrorHandling(_exceptions))
.Merge()
.Merge(GetLocalEvents())
.PublishRefCountRetriable();
_requestCorrelationProvider = requestCorrelationProvider;
}
public IObservable<TEvent> Events { get; }
public Task SendAsync(TCommand command)
{
var exceptions = new List<Exception>();
var tasks = EndpointClientsThatCanHandle(command)
.Select(endpoint => Catch(() => endpoint.SendAsync(command), exceptions, CommandErrorMessage(endpoint)))
.Union(SendLocal(command, exceptions))
.ToArray();
if (exceptions.Any())
{
throw new AggregateException(CommandErrorMessage(command), exceptions);
}
if (tasks.Length == 0)
{
throw new Exception(
$"No endpoint or local bus configured for {command}, please check your ServiceBus configuration.");
}
return Task.WhenAll(tasks);
}
private IObservable<TEvent> GetLocalEvents()
{
return _localBus == null ? Observable.Empty<TEvent>() : _localBus.Events;
}
protected IObservable<TCommand> GetLocalCommands()
{
return _localBus == null ? Observable.Empty<TCommand>() : _localBus.Commands;
}
protected IObservable<TRequest> GetLocalRequests()
{
return _localBus == null ? Observable.Empty<TRequest>() : _localBus.Requests;
}
protected IEnumerable<Task> PublishLocal(TEvent ev, List<Exception> exceptions)
{
return ShouldPublishLocally(ev)
? new[] {Catch(() => _localBus.PublishAsync(ev), exceptions)}
: Enumerable.Empty<Task>();
}
private IEnumerable<Task> SendLocal(TCommand command, List<Exception> exceptions)
{
return ShouldPublishLocally(command)
? new[] { Catch(() => _localBus.SendAsync(command), exceptions) }
: Enumerable.Empty<Task>();
}
protected IEnumerable<Task> ReplyLocal(TRequest request, TResponse response, List<Exception> exceptions)
{
return ShouldPublishLocally(response)
? new[] { Catch(() => _localBus.ReplyAsync(request, response), exceptions) }
: Enumerable.Empty<Task>();
}
private bool ShouldPublishLocally(TMessage message)
{
if (_localBus == null)
{
return false;
}
if (_localBusOption == LocalBusOptions.AllMessages)
{
return true;
}
if (_localBusOption == LocalBusOptions.MessagesWithNoEndpointClients &&
!_endpointClients.Any(e => e.CanHandle(message)))
{
return true;
}
if (_localBusOption == LocalBusOptions.MessagesWithNoEndpoints &&
!Endpoints.Any(e => e.CanHandle(message)) &&
!_endpointClients.Any(e => e.CanHandle(message)))
{
return true;
}
return false;
}
public Task SendAsync(IEnumerable<TCommand> commands)
{
var commandsResolved = commands.ToArray();
if (commandsResolved.Length == 0)
return Task.FromResult(true);
var exceptions = new List<Exception>();
var tasks = commandsResolved.Select(command => Catch(() => SendAsync(command), exceptions)).ToArray();
if (exceptions.Any())
{
Exception[] GetInnerExceptions(Exception e) =>
e is AggregateException aggregateException
? aggregateException.InnerExceptions.ToArray()
: new[] {e};
throw new AggregateException(CommandErrorMessage(), exceptions.SelectMany(GetInnerExceptions));
}
if (tasks.Length == 0)
{
throw new Exception("No endpoint or local bus configured for any of these commands, please check your ServiceBus configuration.");
}
return Task.WhenAll(tasks);
}
public IObservable<TResponse> GetResponses(TRequest request)
{
if (_requestCorrelationProvider == null)
{
throw new InvalidOperationException("Please configure the ServiceBus with a IRequestCorrelationProvider using the fluent configuration extension method .CorrelatesRequestWith()");
}
_requestCorrelationProvider.SetRequestCorrelationIds(request);
return EndpointClientsThatCanHandle(request)
.Select(endpoint => endpoint.GetResponses(request)
.Where(response => _requestCorrelationProvider.AreCorrelated(request, response)))
.Merge()
.Merge(GetLocalResponses(request))
.PublishRefCountRetriable();
}
private IObservable<TResponse> GetLocalResponses(TRequest request)
{
return ShouldPublishLocally(request)
? _localBus.GetResponses(request)
: Observable.Empty<TResponse>();
}
public IObservable<T> GetResponses<T>(TRequest request) where T : TResponse
{
return GetResponses(request).OfType<T>();
}
public IObservable<T> GetResponse<T>(TRequest request) where T : TResponse
{
return GetResponses(request).OfType<T>().Take(1);
}
private IEnumerable<IServiceEndpointClient<TMessage, TCommand, TEvent, TRequest, TResponse>> EndpointClientsThatCanHandle(TMessage message)
{
return _endpointClients.Where(endpoint => endpoint.CanHandle(message)).ToArray();
}
public override void Dispose()
{
base.Dispose();
foreach (var endpointClient in _endpointClients)
{
endpointClient.Dispose();
}
}
}
}
| |
// 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.Runtime.ExceptionServices;
using System.Runtime.InteropServices.WindowsRuntime;
using System.Runtime.InteropServices;
using System.Threading.Tasks;
using System.Threading;
using Windows.Foundation;
using Windows.Storage.Streams;
namespace System.IO
{
#region class StreamOperationAsyncResult
internal abstract partial class StreamOperationAsyncResult : IAsyncResult
{
private AsyncCallback _userCompletionCallback = null;
private object _userAsyncStateInfo = null;
private IAsyncInfo _asyncStreamOperation = null;
private volatile bool _completed = false;
private volatile bool _callbackInvoked = false;
private volatile ManualResetEvent _waitHandle = null;
private long _bytesCompleted = 0;
private ExceptionDispatchInfo _errorInfo = null;
private readonly bool _processCompletedOperationInCallback;
private IAsyncInfo _completedOperation = null;
protected internal StreamOperationAsyncResult(IAsyncInfo asyncStreamOperation,
AsyncCallback userCompletionCallback, object userAsyncStateInfo,
bool processCompletedOperationInCallback)
{
if (asyncStreamOperation == null)
throw new ArgumentNullException("asyncReadOperation");
_userCompletionCallback = userCompletionCallback;
_userAsyncStateInfo = userAsyncStateInfo;
_asyncStreamOperation = asyncStreamOperation;
_completed = false;
_callbackInvoked = false;
_bytesCompleted = 0;
_errorInfo = null;
_processCompletedOperationInCallback = processCompletedOperationInCallback;
}
public object AsyncState
{
get { return _userAsyncStateInfo; }
}
internal bool ProcessCompletedOperationInCallback
{
get { return _processCompletedOperationInCallback; }
}
#pragma warning disable 420 // "a reference to a volatile field will not be treated as volatile"
public WaitHandle AsyncWaitHandle
{
get
{
ManualResetEvent wh = _waitHandle;
if (wh != null)
return wh;
// What if someone calls this public property and decides to wait on it?
// > Use 'completed' in the ctor - this way the handle wait will return as appropriate.
wh = new ManualResetEvent(_completed);
ManualResetEvent otherHandle = Interlocked.CompareExchange(ref _waitHandle, wh, null);
// We lost the race. Dispose OUR handle and return OTHER handle:
if (otherHandle != null)
{
wh.Dispose();
return otherHandle;
}
// We won the race. Return OUR new handle:
return wh;
}
}
#pragma warning restore 420 // "a reference to a volatile field will not be treated as volatile"
public bool CompletedSynchronously
{
get { return false; }
}
public bool IsCompleted
{
get { return _completed; }
}
internal void Wait()
{
if (_completed)
return;
WaitHandle wh = AsyncWaitHandle;
while (_completed == false)
wh.WaitOne();
}
internal long BytesCompleted
{
get { return _bytesCompleted; }
}
internal bool HasError
{
get { return _errorInfo != null; }
}
internal void ThrowCachedError()
{
if (_errorInfo == null)
return;
_errorInfo.Throw();
}
internal bool CancelStreamOperation()
{
if (_callbackInvoked)
return false;
if (_asyncStreamOperation != null)
{
_asyncStreamOperation.Cancel();
_asyncStreamOperation = null;
}
return true;
}
internal void CloseStreamOperation()
{
try
{
if (_asyncStreamOperation != null)
_asyncStreamOperation.Close();
}
catch { }
_asyncStreamOperation = null;
}
~StreamOperationAsyncResult()
{
// This finalisation is not critical, but we can still make an effort to notify the underlying WinRT stream
// that we are not any longer interested in the results:
CancelStreamOperation();
}
internal abstract void ProcessConcreteCompletedOperation(IAsyncInfo completedOperation, out long bytesCompleted);
private static void ProcessCompletedOperation_InvalidOperationThrowHelper(ExceptionDispatchInfo errInfo, string errMsg)
{
Exception errInfoSrc = (errInfo == null) ? null : errInfo.SourceException;
if (errInfoSrc == null)
throw new InvalidOperationException(errMsg);
else
throw new InvalidOperationException(errMsg, errInfoSrc);
}
internal void ProcessCompletedOperation()
{
// The error handling is slightly tricky here:
// Before processing the IO results, we are verifying some basic assumptions and if they do not hold, we are
// throwing InvalidOperation. However, by the time this method is called, we might have already stored something
// into errorInfo, e.g. if an error occurred in StreamOperationCompletedCallback. If that is the case, then that
// previous exception might include some important info relevant for detecting the problem. So, we take that
// previous exception and attach it as the inner exception to the InvalidOperationException being thrown.
// In cases where we have a good understanding of the previously saved errorInfo, and we know for sure that it
// the immediate reason for the state validation to fail, we can avoid throwing InvalidOperation altogether
// and only rethrow the errorInfo.
if (!_callbackInvoked)
ProcessCompletedOperation_InvalidOperationThrowHelper(_errorInfo, SR.InvalidOperation_CannotCallThisMethodInCurrentState);
if (!_processCompletedOperationInCallback && !_completed)
ProcessCompletedOperation_InvalidOperationThrowHelper(_errorInfo, SR.InvalidOperation_CannotCallThisMethodInCurrentState);
if (_completedOperation == null)
{
ExceptionDispatchInfo errInfo = _errorInfo;
Exception errInfoSrc = (errInfo == null) ? null : errInfo.SourceException;
// See if errorInfo is set because we observed completedOperation == null previously (being slow is Ok on error path):
if (errInfoSrc != null && errInfoSrc is NullReferenceException
&& SR.NullReference_IOCompletionCallbackCannotProcessNullAsyncInfo.Equals(errInfoSrc.Message))
{
errInfo.Throw();
}
else
{
throw new InvalidOperationException(SR.InvalidOperation_CannotCallThisMethodInCurrentState);
}
}
if (_completedOperation.Id != _asyncStreamOperation.Id)
ProcessCompletedOperation_InvalidOperationThrowHelper(_errorInfo, SR.InvalidOperation_UnexpectedAsyncOperationID);
if (_completedOperation.Status == AsyncStatus.Error)
{
_bytesCompleted = 0;
ThrowWithIOExceptionDispatchInfo(_completedOperation.ErrorCode);
}
ProcessConcreteCompletedOperation(_completedOperation, out _bytesCompleted);
}
internal void StreamOperationCompletedCallback(IAsyncInfo completedOperation, AsyncStatus unusedCompletionStatus)
{
try
{
if (_callbackInvoked)
throw new InvalidOperationException(SR.InvalidOperation_MultipleIOCompletionCallbackInvocation);
_callbackInvoked = true;
// This happens in rare stress cases in Console mode and the WinRT folks said they are unlikely to fix this in Dev11.
// Moreover, this can happen if the underlying WinRT stream has a faulty user implementation.
// If we did not do this check, we would either get the same exception without the explaining message when dereferencing
// completedOperation later, or we will get an InvalidOperation when processing the Op. With the check, they will be
// aggregated and the user will know what went wrong.
if (completedOperation == null)
throw new NullReferenceException(SR.NullReference_IOCompletionCallbackCannotProcessNullAsyncInfo);
_completedOperation = completedOperation;
// processCompletedOperationInCallback == false indicates that the stream is doing a blocking wait on the waitHandle of this IAsyncResult.
// In that case calls on completedOperation may deadlock if completedOperation is not free threaded.
// By setting processCompletedOperationInCallback to false the stream that created this IAsyncResult indicated that it
// will call ProcessCompletedOperation after the waitHandle is signalled to fetch the results.
if (_processCompletedOperationInCallback)
ProcessCompletedOperation();
}
catch (Exception ex)
{
_bytesCompleted = 0;
_errorInfo = ExceptionDispatchInfo.Capture(ex);
}
finally
{
_completed = true;
Interlocked.MemoryBarrier();
// From this point on, AsyncWaitHandle would create a handle that is readily set,
// so we do not need to check if it is being produced asynchronously.
if (_waitHandle != null)
_waitHandle.Set();
}
if (_userCompletionCallback != null)
_userCompletionCallback(this);
}
} // class StreamOperationAsyncResult
#endregion class StreamOperationAsyncResult
#region class StreamReadAsyncResult
internal class StreamReadAsyncResult : StreamOperationAsyncResult
{
private IBuffer _userBuffer = null;
internal StreamReadAsyncResult(IAsyncOperationWithProgress<IBuffer, uint> asyncStreamReadOperation, IBuffer buffer,
AsyncCallback userCompletionCallback, object userAsyncStateInfo,
bool processCompletedOperationInCallback)
: base(asyncStreamReadOperation, userCompletionCallback, userAsyncStateInfo, processCompletedOperationInCallback)
{
if (buffer == null)
throw new ArgumentNullException(nameof(buffer));
_userBuffer = buffer;
asyncStreamReadOperation.Completed = this.StreamOperationCompletedCallback;
}
internal override void ProcessConcreteCompletedOperation(IAsyncInfo completedOperation, out long bytesCompleted)
{
ProcessConcreteCompletedOperation((IAsyncOperationWithProgress<IBuffer, uint>)completedOperation, out bytesCompleted);
}
private void ProcessConcreteCompletedOperation(IAsyncOperationWithProgress<IBuffer, uint> completedOperation, out long bytesCompleted)
{
IBuffer resultBuffer = completedOperation.GetResults();
Debug.Assert(resultBuffer != null);
WinRtIOHelper.EnsureResultsInUserBuffer(_userBuffer, resultBuffer);
bytesCompleted = _userBuffer.Length;
}
} // class StreamReadAsyncResult
#endregion class StreamReadAsyncResult
#region class StreamWriteAsyncResult
internal class StreamWriteAsyncResult : StreamOperationAsyncResult
{
internal StreamWriteAsyncResult(IAsyncOperationWithProgress<uint, uint> asyncStreamWriteOperation,
AsyncCallback userCompletionCallback, object userAsyncStateInfo,
bool processCompletedOperationInCallback)
: base(asyncStreamWriteOperation, userCompletionCallback, userAsyncStateInfo, processCompletedOperationInCallback)
{
asyncStreamWriteOperation.Completed = this.StreamOperationCompletedCallback;
}
internal override void ProcessConcreteCompletedOperation(IAsyncInfo completedOperation, out long bytesCompleted)
{
ProcessConcreteCompletedOperation((IAsyncOperationWithProgress<uint, uint>)completedOperation, out bytesCompleted);
}
private void ProcessConcreteCompletedOperation(IAsyncOperationWithProgress<uint, uint> completedOperation, out long bytesCompleted)
{
uint bytesWritten = completedOperation.GetResults();
bytesCompleted = bytesWritten;
}
} // class StreamWriteAsyncResult
#endregion class StreamWriteAsyncResult
#region class StreamFlushAsyncResult
internal class StreamFlushAsyncResult : StreamOperationAsyncResult
{
internal StreamFlushAsyncResult(IAsyncOperation<bool> asyncStreamFlushOperation, bool processCompletedOperationInCallback)
: base(asyncStreamFlushOperation, null, null, processCompletedOperationInCallback)
{
asyncStreamFlushOperation.Completed = this.StreamOperationCompletedCallback;
}
internal override void ProcessConcreteCompletedOperation(IAsyncInfo completedOperation, out long bytesCompleted)
{
ProcessConcreteCompletedOperation((IAsyncOperation<bool>)completedOperation, out bytesCompleted);
}
private void ProcessConcreteCompletedOperation(IAsyncOperation<bool> completedOperation, out long bytesCompleted)
{
bool success = completedOperation.GetResults();
bytesCompleted = (success ? 0 : -1);
}
} // class StreamFlushAsyncResult
#endregion class StreamFlushAsyncResult
} // namespace
// StreamOperationAsyncResult.cs
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* 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 OpenSimulator Project 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 DEVELOPERS ``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 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.Collections.Generic;
using System.Threading;
namespace OpenSim.Framework
{
public delegate bool ExpireDelegate(string index);
// The delegate we will use for performing fetch from backing store
//
public delegate Object FetchDelegate(string index);
public enum CacheFlags
{
CacheMissing = 1,
AllowUpdate = 2
}
// Select classes to store data on different media
//
public enum CacheMedium
{
Memory = 0,
File = 1
}
// Strategy
//
// Conservative = Minimize memory. Expire items quickly.
// Balanced = Expire items with few hits quickly.
// Aggressive = Keep cache full. Expire only when over 90% and adding
//
public enum CacheStrategy
{
Conservative = 0,
Balanced = 1,
Aggressive = 2
}
// The main cache class. This is the class you instantiate to create
// a cache
//
public class Cache
{
public ExpireDelegate OnExpire;
private TimeSpan m_DefaultTTL = new TimeSpan(0);
private CacheFlags m_Flags = 0;
/// <summary>
/// Must only be accessed under lock.
/// </summary>
private List<CacheItemBase> m_Index = new List<CacheItemBase>();
private ReaderWriterLock m_IndexRwLock = new ReaderWriterLock();
/// <summary>
/// Must only be accessed under m_Index lock.
/// </summary>
private Dictionary<string, CacheItemBase> m_Lookup =
new Dictionary<string, CacheItemBase>();
private CacheMedium m_Medium;
private int m_Size = 1024;
private CacheStrategy m_Strategy;
// Convenience constructors
//
public Cache()
{
m_Strategy = CacheStrategy.Balanced;
m_Medium = CacheMedium.Memory;
m_Flags = 0;
}
public Cache(CacheMedium medium) :
this(medium, CacheStrategy.Balanced)
{
}
public Cache(CacheMedium medium, CacheFlags flags) :
this(medium, CacheStrategy.Balanced, flags)
{
}
public Cache(CacheMedium medium, CacheStrategy strategy) :
this(medium, strategy, 0)
{
}
public Cache(CacheStrategy strategy, CacheFlags flags) :
this(CacheMedium.Memory, strategy, flags)
{
}
public Cache(CacheFlags flags) :
this(CacheMedium.Memory, CacheStrategy.Balanced, flags)
{
}
public Cache(CacheMedium medium, CacheStrategy strategy,
CacheFlags flags)
{
m_Strategy = strategy;
m_Medium = medium;
m_Flags = flags;
}
// Count of the items currently in cache
//
public int Count
{
get
{
m_IndexRwLock.AcquireReaderLock(-1);
try
{
return m_Index.Count;
}
finally
{
m_IndexRwLock.ReleaseReaderLock();
}
}
}
public TimeSpan DefaultTTL
{
get { return m_DefaultTTL; }
set { m_DefaultTTL = value; }
}
// Maximum number of items this cache will hold
//
public int Size
{
get { return m_Size; }
set { SetSize(value); }
}
public void Clear()
{
m_IndexRwLock.AcquireWriterLock(-1);
try
{
m_Index.Clear();
m_Lookup.Clear();
}
finally
{
m_IndexRwLock.ReleaseWriterLock();
}
}
// Find an object in cache by delegate.
//
public Object Find(Predicate<CacheItemBase> d)
{
CacheItemBase item;
m_IndexRwLock.AcquireReaderLock(-1);
try
{
item = m_Index.Find(d);
}
finally
{
m_IndexRwLock.ReleaseWriterLock();
}
if (item == null)
return null;
return item.Retrieve();
}
// Get an item from cache. Do not try to fetch from source if not
// present. Just return null
//
public virtual Object Get(string index)
{
CacheItemBase item = GetItem(index);
if (item == null)
return null;
return item.Retrieve();
}
// Fetch an object from backing store if not cached, serve from
// cache if it is.
//
public virtual Object Get(string index, FetchDelegate fetch)
{
Object item = Get(index);
if (item != null)
return item;
Object data = fetch(index);
if (data == null)
{
if ((m_Flags & CacheFlags.CacheMissing) != 0)
{
m_IndexRwLock.AcquireWriterLock(-1);
try
{
CacheItemBase missing = new CacheItemBase(index);
if (!m_Index.Contains(missing))
{
m_Index.Add(missing);
m_Lookup[index] = missing;
}
}
finally
{
m_IndexRwLock.ReleaseWriterLock();
}
}
return null;
}
Store(index, data);
return data;
}
public void Invalidate(string uuid)
{
m_IndexRwLock.AcquireWriterLock(-1);
try
{
if (!m_Lookup.ContainsKey(uuid))
return;
CacheItemBase item = m_Lookup[uuid];
m_Lookup.Remove(uuid);
m_Index.Remove(item);
}
finally
{
m_IndexRwLock.ReleaseWriterLock();
}
}
public virtual void Store(string index, Object data)
{
Type container;
switch (m_Medium)
{
case CacheMedium.Memory:
container = typeof(MemoryCacheItem);
break;
case CacheMedium.File:
return;
default:
return;
}
Store(index, data, container);
}
public virtual void Store(string index, Object data, Type container)
{
Store(index, data, container, new Object[] { index });
}
public virtual void Store(string index, Object data, Type container,
Object[] parameters)
{
CacheItemBase item;
m_IndexRwLock.AcquireWriterLock(-1);
try
{
Expire(false);
if (m_Index.Contains(new CacheItemBase(index)))
{
if ((m_Flags & CacheFlags.AllowUpdate) != 0)
{
item = GetItem(index);
item.hits++;
item.lastUsed = DateTime.Now;
if (m_DefaultTTL.Ticks != 0)
item.expires = DateTime.Now + m_DefaultTTL;
item.Store(data);
}
return;
}
item = (CacheItemBase)Activator.CreateInstance(container,
parameters);
if (m_DefaultTTL.Ticks != 0)
item.expires = DateTime.Now + m_DefaultTTL;
m_Index.Add(item);
m_Lookup[index] = item;
}
finally
{
m_IndexRwLock.ReleaseWriterLock();
}
item.Store(data);
}
/// <summary>
/// Expire items as appropriate.
/// </summary>
/// <remarks>
/// Callers must lock m_Index.
/// </remarks>
/// <param name='getting'></param>
protected virtual void Expire(bool getting)
{
if (getting && (m_Strategy == CacheStrategy.Aggressive))
return;
if (m_DefaultTTL.Ticks != 0)
{
DateTime now = DateTime.Now;
foreach (CacheItemBase item in new List<CacheItemBase>(m_Index))
{
if (item.expires.Ticks == 0 ||
item.expires <= now)
{
m_Index.Remove(item);
m_Lookup.Remove(item.uuid);
}
}
}
switch (m_Strategy)
{
case CacheStrategy.Aggressive:
if (Count < Size)
return;
m_Index.Sort(new SortLRU());
m_Index.Reverse();
int target = (int)((float)Size * 0.9);
if (target == Count) // Cover ridiculous cache sizes
return;
ExpireDelegate doExpire = OnExpire;
if (doExpire != null)
{
List<CacheItemBase> candidates =
m_Index.GetRange(target, Count - target);
foreach (CacheItemBase i in candidates)
{
if (doExpire(i.uuid))
{
m_Index.Remove(i);
m_Lookup.Remove(i.uuid);
}
}
}
else
{
m_Index.RemoveRange(target, Count - target);
m_Lookup.Clear();
foreach (CacheItemBase item in m_Index)
m_Lookup[item.uuid] = item;
}
break;
default:
break;
}
}
// Get an item from cache. Return the raw item, not it's data
//
protected virtual CacheItemBase GetItem(string index)
{
CacheItemBase item = null;
m_IndexRwLock.AcquireReaderLock(-1);
try
{
if (m_Lookup.ContainsKey(index))
item = m_Lookup[index];
if (item == null)
{
LockCookie lc = m_IndexRwLock.UpgradeToWriterLock(-1);
try
{
Expire(true);
}
finally
{
m_IndexRwLock.DowngradeFromWriterLock(ref lc);
}
return null;
}
item.hits++;
item.lastUsed = DateTime.Now;
{
LockCookie lc = m_IndexRwLock.UpgradeToWriterLock(-1);
try
{
Expire(true);
}
finally
{
m_IndexRwLock.DowngradeFromWriterLock(ref lc);
}
}
}
finally
{
m_IndexRwLock.ReleaseReaderLock();
}
return item;
}
private void SetSize(int newSize)
{
m_IndexRwLock.AcquireWriterLock(-1);
try
{
if (Count <= Size)
return;
m_Index.Sort(new SortLRU());
m_Index.Reverse();
m_Index.RemoveRange(newSize, Count - newSize);
m_Size = newSize;
m_Lookup.Clear();
foreach (CacheItemBase item in m_Index)
m_Lookup[item.uuid] = item;
}
finally
{
m_IndexRwLock.ReleaseWriterLock();
}
}
// Comparison interfaces
//
private class SortLRU : IComparer<CacheItemBase>
{
public int Compare(CacheItemBase a, CacheItemBase b)
{
if (a == null && b == null)
return 0;
if (a == null)
return -1;
if (b == null)
return 1;
return (a.lastUsed.CompareTo(b.lastUsed));
}
}
}
// The base class of all cache objects. Implements comparison and sorting
// by the string member.
//
// This is not abstract because we need to instantiate it briefly as a
// method parameter
//
public class CacheItemBase : IEquatable<CacheItemBase>, IComparable<CacheItemBase>
{
public DateTime entered;
public DateTime expires = new DateTime(0);
public int hits = 0;
public DateTime lastUsed;
public string uuid;
public CacheItemBase(string index)
{
uuid = index;
entered = DateTime.Now;
lastUsed = entered;
}
public CacheItemBase(string index, DateTime ttl)
{
uuid = index;
entered = DateTime.Now;
lastUsed = entered;
expires = ttl;
}
public virtual int CompareTo(CacheItemBase item)
{
return uuid.CompareTo(item.uuid);
}
public virtual bool Equals(CacheItemBase item)
{
return uuid == item.uuid;
}
public virtual bool IsLocked()
{
return false;
}
public virtual Object Retrieve()
{
return null;
}
public virtual void Store(Object data)
{
}
}
// Simple persistent file storage
//
public class FileCacheItem : CacheItemBase
{
public FileCacheItem(string index) :
base(index)
{
}
public FileCacheItem(string index, DateTime ttl) :
base(index, ttl)
{
}
public FileCacheItem(string index, Object data) :
base(index)
{
Store(data);
}
public FileCacheItem(string index, DateTime ttl, Object data) :
base(index, ttl)
{
Store(data);
}
public override Object Retrieve()
{
//TODO: Add file access code
return null;
}
public override void Store(Object data)
{
//TODO: Add file access code
}
}
// Simple in-memory storage. Boxes the object and stores it in a variable
//
public class MemoryCacheItem : CacheItemBase
{
private Object m_Data;
public MemoryCacheItem(string index) :
base(index)
{
}
public MemoryCacheItem(string index, DateTime ttl) :
base(index, ttl)
{
}
public MemoryCacheItem(string index, Object data) :
base(index)
{
Store(data);
}
public MemoryCacheItem(string index, DateTime ttl, Object data) :
base(index, ttl)
{
Store(data);
}
public override Object Retrieve()
{
return m_Data;
}
public override void Store(Object data)
{
m_Data = data;
}
}
}
| |
// Copyright (c) 2021 Alachisoft
//
// 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;
#if !NETCORE
using System.Runtime.Remoting.Channels;
using System.Runtime.Remoting.Channels.Http;
using System.Runtime.Remoting.Channels.Tcp;
using System.Runtime.Remoting.Channels.Ipc;
using System.Runtime.Serialization.Formatters;
#endif
namespace Alachisoft.NCache.Common.Remoting
{
/// <summary>
/// Summary description for NCacheChannels.
/// </summary>
public class RemotingChannels
{
#if !NETCORE
/// <summary> The underlying TCP server channel. </summary>
private IChannel _tcpServerChannel;
/// <summary> The underlying TCP client channel. </summary>
private IChannel _tcpClientChannel;
/// <summary> The underlying HTTP server channel. </summary>
private IChannel _httpServerChannel;
/// <summary> The underlying HTTP client channel. </summary>
private IChannel _httpClientChannel;
/// <summary> The underlying IPO Server channel. </summary>
private IChannel _ipcServerChannel;
/// <summary> The underlying IPC client channel. </summary>
private IChannel _ipcClientChannel;
#endif
public RemotingChannels()
{
//
// TODO: Add constructor logic here
//
}
#if !NETCORE
/// <summary> Returns the underlying TCP server channel. </summary>
public IChannel TcpServerChannel { get { return _tcpServerChannel; } }
/// <summary> Returns the underlying TCP client channel. </summary>
public IChannel TcpClientChannel { get { return _tcpClientChannel; } }
/// <summary> Returns the underlying HTTP server channel. </summary>
public IChannel HttpServerChannel { get { return _httpServerChannel; } }
/// <summary> Returns the underlying HTTP client channel. </summary>
public IChannel HttpClientChannel { get { return _httpClientChannel; } }
#endif
#region / --- TcpChannel --- /
/// <summary>
///
/// </summary>
/// <param name="channelName"></param>
/// <param name="port"></param>
public void RegisterTcpChannels(string channelName, int port)
{
RegisterTcpServerChannel(String.Concat(channelName, ".s"), port);
RegisterTcpClientChannel(String.Concat(channelName, ".c"));
}
/// <summary>
///
/// </summary>
/// <param name="channelName"></param>
/// <param name="port"></param>
public void RegisterTcpChannels(string channelName, string ip, int port)
{
RegisterTcpServerChannel(String.Concat(channelName, ".s"), ip, port);
RegisterTcpClientChannel(String.Concat(channelName, ".c"));
}
/// <summary>
/// Stop this service.
/// </summary>
public void UnregisterTcpChannels()
{
UnregisterTcpServerChannel();
UnregisterTcpClientChannel();
}
/// <summary>
///
/// </summary>
/// <param name="channelName"></param>
/// <param name="port"></param>
public void RegisterTcpServerChannel(string channelName, int port)
{
#if !NETCORE
_tcpServerChannel = ChannelServices.GetChannel(channelName);
if (_tcpServerChannel == null)
{
BinaryServerFormatterSinkProvider sprovider = new BinaryServerFormatterSinkProvider();
sprovider.TypeFilterLevel = TypeFilterLevel.Full;
_tcpServerChannel = new TcpServerChannel(channelName, port, sprovider);
ChannelServices.RegisterChannel(_tcpServerChannel);
}
#endif
}
public void RegisterTcpServerChannel(string channelName, string ip, int port)
{
try
{
#if !NETCORE
_tcpServerChannel = ChannelServices.GetChannel(channelName);
if (_tcpServerChannel == null)
{
IDictionary properties = new Hashtable();
properties["name"] = channelName;
{
properties["port"] = port;
properties["bindTo"] =ip ;
}
BinaryServerFormatterSinkProvider sprovider = new BinaryServerFormatterSinkProvider();
sprovider.TypeFilterLevel = TypeFilterLevel.Full;
_tcpServerChannel = new TcpServerChannel(properties, sprovider);
ChannelServices.RegisterChannel(_tcpServerChannel);
}
#endif
}
catch (System.Net.Sockets.SocketException se)
{
switch (se.ErrorCode)
{
// 10049 --> address not available.
case 10049:
throw new Exception("The address " + ip + " specified for NCacheServer.BindToIP is not valid");
default:
throw;
}
}
}
/// <summary>
///
/// </summary>
/// <param name="channelName"></param>
/// <param name="port"></param>
public void RegisterTcpClientChannel(string channelName)
{
#if !NETCORE
_tcpClientChannel = ChannelServices.GetChannel(channelName);
if (_tcpClientChannel == null)
{
BinaryClientFormatterSinkProvider cprovider = new BinaryClientFormatterSinkProvider();
_tcpClientChannel = new TcpClientChannel(channelName, cprovider);
ChannelServices.RegisterChannel(_tcpClientChannel);
}
#endif
}
/// <summary>
/// Stop this service.
/// </summary>
public void UnregisterTcpServerChannel()
{
#if !NETCORE
if (_tcpServerChannel != null)
{
ChannelServices.UnregisterChannel(_tcpServerChannel);
_tcpServerChannel = null;
}
#endif
}
/// <summary>
/// Stop this service.
/// </summary>
public void UnregisterTcpClientChannel()
{
#if !NETCORE
if (_tcpClientChannel != null)
{
ChannelServices.UnregisterChannel(_tcpClientChannel);
_tcpClientChannel = null;
}
#endif
}
#endregion
#region / --- HttpChannel --- /
/// <summary>
///
/// </summary>
/// <param name="channelName"></param>
/// <param name="port"></param>
public void RegisterHttpChannels(string channelName, int port)
{
RegisterHttpServerChannel(String.Concat(channelName, ".sh"), port);
RegisterHttpClientChannel(String.Concat(channelName, ".ch"));
}
/// <summary>
///
/// </summary>
/// <param name="channelName"></param>
/// <param name="port"></param>
public void RegisterHttpChannels(string channelName, string ip, int port)
{
RegisterHttpServerChannel(String.Concat(channelName, ".sh"), ip, port);
RegisterHttpClientChannel(String.Concat(channelName, ".ch"));
}
/// <summary>
/// Stop this service.
/// </summary>
public void UnregisterHttpChannels()
{
UnregisterHttpServerChannel();
UnregisterHttpClientChannel();
}
/// <summary>
///
/// </summary>
/// <param name="channelName"></param>
/// <param name="port"></param>
public void RegisterHttpServerChannel(string channelName, int port)
{
#if !NETCORE
_httpServerChannel = ChannelServices.GetChannel(channelName);
if (_httpServerChannel == null)
{
BinaryServerFormatterSinkProvider sprovider = new BinaryServerFormatterSinkProvider();
sprovider.TypeFilterLevel = TypeFilterLevel.Full;
_httpServerChannel = new HttpServerChannel(channelName, port, sprovider);
ChannelServices.RegisterChannel(_httpServerChannel);
}
#endif
}
/// <summary>
///
/// </summary>
/// <param name="channelName"></param>
/// <param name="port"></param>
public void RegisterHttpServerChannel(string channelName, string ip, int port)
{
try
{
#if !NETCORE
_httpServerChannel = ChannelServices.GetChannel(channelName);
if (_httpServerChannel == null)
{
IDictionary properties = new Hashtable();
properties["name"] = channelName;
{
properties["port"] = port;
properties["bindTo"] = ip;
}
BinaryServerFormatterSinkProvider sprovider = new BinaryServerFormatterSinkProvider();
sprovider.TypeFilterLevel = TypeFilterLevel.Full;
_httpServerChannel = new HttpServerChannel(properties, sprovider);
ChannelServices.RegisterChannel(_httpServerChannel);
}
#endif
}
catch (System.Net.Sockets.SocketException se)
{
switch (se.ErrorCode)
{
// 10049 --> address not available.
case 10049:
throw new Exception("The address " + ip + " specified for NCacheServer.BindToIP is not valid");
default:
throw;
}
}
}
/// <summary>
///
/// </summary>
/// <param name="channelName"></param>
/// <param name="port"></param>
public void RegisterHttpClientChannel(string channelName)
{
#if !NETCORE
_httpClientChannel = ChannelServices.GetChannel(channelName);
if (_httpClientChannel == null)
{
BinaryClientFormatterSinkProvider cprovider = new BinaryClientFormatterSinkProvider();
_httpClientChannel = new HttpClientChannel(channelName, cprovider);
ChannelServices.RegisterChannel(_httpClientChannel);
}
#endif
}
/// <summary>
/// Stop this service.
/// </summary>
public void UnregisterHttpServerChannel()
{
#if !NETCORE
if (_httpServerChannel != null)
{
ChannelServices.UnregisterChannel(_httpServerChannel);
_httpServerChannel = null;
}
#endif
}
/// <summary>
/// Stop this service.
/// </summary>
public void UnregisterHttpClientChannel()
{
#if !NETCORE
if (_httpClientChannel != null)
{
ChannelServices.UnregisterChannel(_httpClientChannel);
_httpClientChannel = null;
}
#endif
}
#endregion
#region / --- IPCChannel --- /
/// <summary>
///
/// </summary>
/// <param name="channelName"></param>
/// <param name="port"></param>
public void RegisterIPCChannels(string channelName, string portName)
{
RegisterIPCServerChannel(String.Concat(channelName, ".s"), portName);
RegisterIPCClientChannel(String.Concat(channelName, ".c"));
AppUtil.LogEvent("IPC channel registered at port: " + portName, System.Diagnostics.EventLogEntryType.Information);
}
/// <summary>
/// Stop this service.
/// </summary>
public void UnregisterIPCChannels()
{
UnregisterTcpServerChannel();
UnregisterTcpClientChannel();
}
/// <summary>
/// Registers IPC server channel.
/// </summary>
/// <param name="channelName"></param>
/// <param name="port"></param>
public void RegisterIPCServerChannel(string channelName, string portName)
{
#if !NETCORE
_ipcServerChannel = ChannelServices.GetChannel(channelName);
if (_ipcServerChannel == null)
{
BinaryServerFormatterSinkProvider sprovider = new BinaryServerFormatterSinkProvider();
sprovider.TypeFilterLevel = TypeFilterLevel.Full;
_ipcServerChannel = new IpcServerChannel(channelName,portName, sprovider); ;
ChannelServices.RegisterChannel(_ipcServerChannel);
}
#endif
}
/// <summary>
/// Registers IPC Client Channel.
/// </summary>
/// <param name="channelName"></param>
/// <param name="port"></param>
public void RegisterIPCClientChannel(string channelName)
{
#if !NETCORE
_ipcClientChannel = ChannelServices.GetChannel(channelName);
if (_ipcClientChannel == null)
{
BinaryClientFormatterSinkProvider cprovider = new BinaryClientFormatterSinkProvider();
_ipcClientChannel = new IpcClientChannel(channelName, cprovider);
ChannelServices.RegisterChannel(_ipcClientChannel);
}
#endif
}
/// <summary>
/// Stop this service.
/// </summary>
public void UnregisterIPCServerChannel()
{
#if !NETCORE
if (_ipcServerChannel != null)
{
ChannelServices.UnregisterChannel(_ipcServerChannel);
_ipcServerChannel = null;
}
#endif
}
/// <summary>
/// Stop this service.
/// </summary>
public void UnregisterIPCClientChannel()
{
#if !NETCORE
if (_ipcClientChannel != null)
{
ChannelServices.UnregisterChannel(_ipcClientChannel);
_ipcClientChannel = null;
}
#endif
}
#endregion
}
}
| |
/// @file
/// @author Ondrej Mocny http://www.hardwire.cz
/// See LICENSE.txt for license information.
using UnityEngine;
/// Helper class of the library. Contains logging methods and some math functions.
public static class e2dUtils
{
#region Debug
/// Turns on/off all debug stuff.
private static bool DEBUG = false;
/// Rebuilds the run-time data each time the component is reloaded (action start/stop and script reload).
public static bool DEBUG_REBUILD_ON_ENABLE { get { return DEBUG && true; } }
/// Displays debug information in the inspector view of the components.
public static bool DEBUG_INSPECTOR { get { return DEBUG && false; } }
/// Displays a curve produced by the generator last time it was executed.
public static bool DEBUG_GENERATOR_CURVE { get { return DEBUG && false; } }
/// Displays control textures in the Terrain component inspector.
public static bool DEBUG_CONTROL_TEXTURES { get { return DEBUG && false; } }
/// Displays cursor related information at the current cursor position.
public static bool DEBUG_CURSOR_INFO { get { return DEBUG && false; } }
/// Displays points defining the curve stripe.
public static bool DEBUG_STRIPE_POINTS { get { return DEBUG && false; } }
/// Displays points defining the curve stripe.
public static bool DEBUG_SHOW_SUBOBJECTS { get { return DEBUG && false; } }
/// Displays points projected from the curve endpoints to the boundary.
public static bool DEBUG_BOUNDARY_PROJECTIONS { get { return DEBUG && false; } }
/// Displays position of the nodes next to each of them.
public static bool DEBUG_NODE_VALUES { get { return DEBUG && false; } }
/// Shows the mesh wireframe of terrain objects.
public static bool DEBUG_SHOW_WIREFRAME { get { return DEBUG && false; } }
/// Hides target area of the generator.
public static bool DEBUG_NO_TARGET_AREA { get { return DEBUG && false; } }
/// Uses fixed seed for the generator.
public static bool DEBUG_FIXED_GENERATOR_SEED { get { return DEBUG && false; } }
/// Style to dump from the current skin.
public static string DEBUG_DUMP_STYLES { get { return DEBUG ? "" : ""; } }
/// Asserts the condition variable is true.
public static void Assert(bool variable)
{
if (!variable)
{
Debug.LogError("!!! ASSERTION FAILED !!!");
Object fail = null;
fail.GetHashCode();
}
}
/// Timer start time.
private static float sTimerStartTime;
/// Timer label.
private static string sTimerLabel;
/// Starts the internal performance timer.
public static void StartTimer(string label)
{
sTimerLabel = label;
sTimerStartTime = Time.realtimeSinceStartup;
}
/// Stops the timer and logs the time passed.
public static void StopTimer()
{
Debug.Log(sTimerLabel + " finished in " + (Time.realtimeSinceStartup - sTimerStartTime));
}
#endregion
#region Logging
/// Writes a message into the log. The messages are filtered based on their source.
public static void Log(string message)
{
System.Type callerType = new System.Diagnostics.StackTrace(1).GetFrame(0).GetMethod().DeclaringType;
// this is the place to disable logging of certain parts of the library
//if (callerType == typeof(e2dMaterialAtlas)) return;
Debug.Log(callerType.Name + ": " + message);
}
/// Reports and error into the log. The messages are filtered based on their source.
public static void Error(string message)
{
Debug.LogError(message);
}
/// Reports a warning into the log. The messages are filtered based on their source.
public static void Warning(string message)
{
Debug.LogWarning(message);
}
#endregion
#region Math
/// Returns the cross product of two 2D vectors.
public static float Cross(Vector2 a, Vector2 b)
{
return a.x * b.y - a.y * b.x;
}
/// Returns true if P is in the triangle defined by A, B, C.
/// Taken from http://www.blackpawn.com/texts/pointinpoly/default.html (based on Real-Time Collision Detection)
public static bool PointInTriangle(Vector2 P, Vector2 A, Vector2 B, Vector2 C)
{
// Compute vectors
Vector2 v0 = C - A;
Vector2 v1 = B - A;
Vector2 v2 = P - A;
// Compute dot products
float dot00 = Vector2.Dot(v0, v0);
float dot01 = Vector2.Dot(v0, v1);
float dot02 = Vector2.Dot(v0, v2);
float dot11 = Vector2.Dot(v1, v1);
float dot12 = Vector2.Dot(v1, v2);
// Compute barycentric coordinates
float invDenom = 1.0f / (dot00 * dot11 - dot01 * dot01);
float u = (dot11 * dot02 - dot01 * dot12) * invDenom;
float v = (dot00 * dot12 - dot01 * dot02) * invDenom;
// Check if point is in triangle
return (u > 0) && (v > 0) && (u + v < 1);
}
/// Returns true if segment (a, b) intersects segment (c, d).
public static bool SegmentsIntersect(Vector2 a, Vector2 b, Vector2 c, Vector2 d)
{
Vector2 intersection;
return SegmentsIntersect(a, b, c, d, out intersection);
}
/// Returns true if segment (a, b) intersects segment (c, d).
public static bool SegmentsIntersect(Vector2 a, Vector2 b, Vector2 c, Vector2 d, out Vector2 intersection)
{
intersection = Vector2.zero;
float cross = (a.x - b.x) * (c.y - d.y) - (a.y - b.y) * (c.x - d.x);
if (Mathf.Abs(cross) <= float.Epsilon)
{
return false; // near parallel
}
intersection.x = ((c.x - d.x) * (a.x * b.y - a.y * b.x) - (a.x - b.x) * (c.x * d.y - c.y * d.x)) / cross;
intersection.y = ((c.y - d.y) * (a.x * b.y - a.y * b.x) - (a.y - b.y) * (c.x * d.y - c.y * d.x)) / cross;
// attempt to prevent imprecision errors
float delta1 = 0;
if (Mathf.Abs(a.x - b.x) <= float.Epsilon || Mathf.Abs(a.y - b.y) <= float.Epsilon) delta1 = 0.01f;
if (intersection.x < Mathf.Min(a.x, b.x) - delta1 || intersection.x > Mathf.Max(a.x, b.x) + delta1)
{
return false;
}
if (intersection.y < Mathf.Min(a.y, b.y) - delta1 || intersection.y > Mathf.Max(a.y, b.y) + delta1)
{
return false;
}
// attempt to prevent imprecision errors
float delta2 = 0;
if (Mathf.Abs(c.x - d.x) <= float.Epsilon || Mathf.Abs(c.y - d.y) <= float.Epsilon) delta2 = 0.01f;
if (intersection.x < Mathf.Min(c.x, d.x) - delta2 || intersection.x > Mathf.Max(c.x, d.x) + delta2)
{
return false;
}
if (intersection.y < Mathf.Min(c.y, d.y) - delta2 || intersection.y > Mathf.Max(c.y, d.y) + delta2)
{
return false;
}
return true;
}
/// Returns true if line (a, b) intersects line (c, d). The intersection is returned in result.
public static bool LinesIntersect(Vector2 a, Vector2 b, Vector2 c, Vector2 d, out Vector2 result)
{
result = Vector2.zero;
float cross = (a.x - b.x) * (c.y - d.y) - (a.y - b.y) * (c.x - d.x);
if (Mathf.Abs(cross) < float.MinValue) return false; // near parallel
float xi = ((c.x - d.x) * (a.x * b.y - a.y * b.x) - (a.x - b.x) * (c.x * d.y - c.y * d.x)) / cross;
float yi = ((c.y - d.y) * (a.x * b.y - a.y * b.x) - (a.y - b.y) * (c.x * d.y - c.y * d.x)) / cross;
result.x = xi;
result.y = yi;
return true;
}
/// Returns true if half line (a, b) intersects line (c, d). The intersection is returned in result.
public static bool HalfLineAndLineIntersect(Vector2 a, Vector2 b, Vector2 c, Vector2 d, out Vector2 result)
{
result = Vector2.zero;
float cross = (a.x - b.x) * (c.y - d.y) - (a.y - b.y) * (c.x - d.x);
if (Mathf.Abs(cross) < float.MinValue) return false; // near parallel
result.x = ((c.x - d.x) * (a.x * b.y - a.y * b.x) - (a.x - b.x) * (c.x * d.y - c.y * d.x)) / cross;
result.y = ((c.y - d.y) * (a.x * b.y - a.y * b.x) - (a.y - b.y) * (c.x * d.y - c.y * d.x)) / cross;
// check if the result is in the right half plane
if (Vector2.Dot(result, b - a) < 0) return false;
return true;
}
/// Returns true if the segment intersects the convex polygon.
public static bool SegmentIntersectsPolygon(Vector2 a, Vector2 b, Vector2[] poly)
{
bool intersect = false;
Vector2 lastVertex = poly[poly.Length - 1];
foreach (Vector2 vertex in poly)
{
intersect = intersect || SegmentsIntersect(a, b, lastVertex, vertex);
lastVertex = vertex;
}
return intersect;
}
/// Returns true if the point is in the convex polygon.
public static bool PointInConvexPolygon(Vector2 p, Vector2[] poly)
{
bool inside = true;
Vector2 lastVertex = poly[poly.Length - 1];
foreach (Vector2 vertex in poly)
{
float cross = Cross(vertex - lastVertex, p - lastVertex);
inside = inside && cross <= 0;
lastVertex = vertex;
}
return inside;
}
/// Returns a 2D vector having the specified angle (between itself and the X axis).
public static Vector2 Vector2dFromAngle(float angle)
{
// angle is in degrees
angle *= Mathf.Deg2Rad;
return new Vector2(Mathf.Cos(angle), Mathf.Sin(angle));
}
/// Linear interpolation without limits on the parameter.
public static float Lerp(float a, float b, float t)
{
return a * (1 - t) + b * t;
}
/// Linear interpolation of vectors.
public static Vector3 Lerp(Vector3 a, Vector3 b, float t)
{
return new Vector3(Lerp(a.x, b.x, t), Lerp(a.y, b.y, t), Lerp(a.z, b.z, t));
}
#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.
using System.Buffers;
using System.ComponentModel;
using System.Diagnostics;
using System.Runtime;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
namespace System
{
[DebuggerTypeProxy(typeof(ReadOnlyBufferDebuggerView<>))]
public struct ReadOnlyBuffer<T>
{
// The highest order bit of _index is used to discern whether _arrayOrOwnedBuffer is an array or an owned buffer
// if (_index >> 31) == 1, object _arrayOrOwnedBuffer is an OwnedBuffer<T>
// else, object _arrayOrOwnedBuffer is a T[]
readonly object _arrayOrOwnedBuffer;
readonly int _index;
readonly int _length;
private const int bitMask = 0x7FFFFFFF;
internal ReadOnlyBuffer(OwnedBuffer<T> owner, int index, int length)
{
_arrayOrOwnedBuffer = owner;
_index = index | (1 << 31); // Before using _index, check if _index < 0, then 'and' it with bitMask
_length = length;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public ReadOnlyBuffer(T[] array)
{
if (array == null)
BufferPrimitivesThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
_arrayOrOwnedBuffer = array;
_index = 0;
_length = array.Length;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public ReadOnlyBuffer(T[] array, int start)
{
if (array == null)
BufferPrimitivesThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
int arrayLength = array.Length;
if ((uint)start > (uint)arrayLength)
BufferPrimitivesThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.start);
_arrayOrOwnedBuffer = array;
_index = start;
_length = arrayLength - start;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public ReadOnlyBuffer(T[] array, int start, int length)
{
if (array == null)
BufferPrimitivesThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
if ((uint)start > (uint)array.Length || (uint)length > (uint)(array.Length - start))
BufferPrimitivesThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.start);
_arrayOrOwnedBuffer = array;
_index = start;
_length = length;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static implicit operator ReadOnlyBuffer<T>(T[] array)
{
return new ReadOnlyBuffer<T>(array, 0, array.Length);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static implicit operator ReadOnlyBuffer<T>(ArraySegment<T> arraySegment)
{
return new ReadOnlyBuffer<T>(arraySegment.Array, arraySegment.Offset, arraySegment.Count);
}
public static ReadOnlyBuffer<T> Empty { get; } = OwnedBuffer<T>.EmptyArray;
public int Length => _length;
public bool IsEmpty => Length == 0;
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public ReadOnlyBuffer<T> Slice(int start)
{
if ((uint)start > (uint)_length)
BufferPrimitivesThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.start);
// There is no need to 'and' _index by the bit mask here
// since the constructor will set the highest order bit again anyway
if (_index < 0)
return new ReadOnlyBuffer<T>(Unsafe.As<OwnedBuffer<T>>(_arrayOrOwnedBuffer), _index + start, _length - start);
return new ReadOnlyBuffer<T>(Unsafe.As<T[]>(_arrayOrOwnedBuffer), _index + start, _length - start);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public ReadOnlyBuffer<T> Slice(int start, int length)
{
if ((uint)start > (uint)_length || (uint)length > (uint)(_length - start))
BufferPrimitivesThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.start);
// There is no need to 'and' _index by the bit mask here
// since the constructor will set the highest order bit again anyway
if (_index < 0)
return new ReadOnlyBuffer<T>(Unsafe.As<OwnedBuffer<T>>(_arrayOrOwnedBuffer), _index + start, length);
return new ReadOnlyBuffer<T>(Unsafe.As<T[]>(_arrayOrOwnedBuffer), _index + start, length);
}
public ReadOnlySpan<T> Span
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get
{
if (_index < 0)
return Unsafe.As<OwnedBuffer<T>>(_arrayOrOwnedBuffer).AsSpan(_index & bitMask, _length);
return new ReadOnlySpan<T>(Unsafe.As<T[]>(_arrayOrOwnedBuffer), _index, _length);
}
}
public BufferHandle Retain(bool pin = false)
{
BufferHandle bufferHandle;
if (pin)
{
if (_index < 0)
{
bufferHandle = Unsafe.As<OwnedBuffer<T>>(_arrayOrOwnedBuffer).Pin(_index & bitMask);
}
else
{
var handle = GCHandle.Alloc(Unsafe.As<T[]>(_arrayOrOwnedBuffer), GCHandleType.Pinned);
unsafe
{
var pointer = OwnedBuffer<T>.Add((void*)handle.AddrOfPinnedObject(), _index);
bufferHandle = new BufferHandle(null, pointer, handle);
}
}
}
else
{
if (_index < 0)
{
Unsafe.As<OwnedBuffer<T>>(_arrayOrOwnedBuffer).Retain();
bufferHandle = new BufferHandle(Unsafe.As<OwnedBuffer<T>>(_arrayOrOwnedBuffer));
}
else
{
bufferHandle = new BufferHandle(null);
}
}
return bufferHandle;
}
public T[] ToArray() => Span.ToArray();
[EditorBrowsable(EditorBrowsableState.Never)]
public bool DangerousTryGetArray(out ArraySegment<T> arraySegment)
{
if (_index < 0)
{
if (Unsafe.As<OwnedBuffer<T>>(_arrayOrOwnedBuffer).TryGetArray(out var segment))
{
arraySegment = new ArraySegment<T>(segment.Array, segment.Offset + (_index & bitMask), _length);
return true;
}
}
else
{
arraySegment = new ArraySegment<T>(Unsafe.As<T[]>(_arrayOrOwnedBuffer), _index, _length);
return true;
}
arraySegment = default;
return false;
}
public void CopyTo(Span<T> span) => Span.CopyTo(span);
public void CopyTo(Buffer<T> buffer) => Span.CopyTo(buffer.Span);
public bool TryCopyTo(Span<T> span) => Span.TryCopyTo(span);
public bool TryCopyTo(Buffer<T> buffer) => Span.TryCopyTo(buffer.Span);
[EditorBrowsable(EditorBrowsableState.Never)]
public override bool Equals(object obj)
{
if (obj is ReadOnlyBuffer<T> readOnlyBuffer)
{
return Equals(readOnlyBuffer);
}
else if (obj is Buffer<T> buffer)
{
return Equals(buffer);
}
else
{
return false;
}
}
public bool Equals(ReadOnlyBuffer<T> other)
{
return
_arrayOrOwnedBuffer == other._arrayOrOwnedBuffer &&
(_index & bitMask) == (other._index & bitMask) &&
_length == other._length;
}
[EditorBrowsable(EditorBrowsableState.Never)]
public override int GetHashCode()
{
return HashingHelper.CombineHashCodes(_arrayOrOwnedBuffer.GetHashCode(), (_index & bitMask).GetHashCode(), _length.GetHashCode());
}
}
}
| |
// 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.Diagnostics;
using System.Globalization;
#if !FEATURE_SERIALIZATION
namespace System.CodeDom
#else
namespace System.Runtime.Serialization
#endif
{
[Flags]
#if !FEATURE_SERIALIZATION
public enum CodeTypeReferenceOptions
#else
internal enum CodeTypeReferenceOptions
#endif
{
GlobalReference = 0x00000001,
GenericTypeParameter = 0x00000002
}
[Serializable]
#if !FEATURE_SERIALIZATION
public class CodeTypeReference : CodeObject
#else
internal class CodeTypeReference : CodeObject
#endif
{
private string _baseType;
private readonly bool _isInterface;
private CodeTypeReferenceCollection _typeArguments;
private bool _needsFixup = false;
public CodeTypeReference()
{
_baseType = string.Empty;
ArrayRank = 0;
ArrayElementType = null;
}
public CodeTypeReference(Type type)
{
if (type == null)
{
throw new ArgumentNullException(nameof(type));
}
if (type.IsArray)
{
ArrayRank = type.GetArrayRank();
ArrayElementType = new CodeTypeReference(type.GetElementType());
_baseType = null;
}
else
{
InitializeFromType(type);
ArrayRank = 0;
ArrayElementType = null;
}
_isInterface = type.IsInterface;
}
public CodeTypeReference(Type type, CodeTypeReferenceOptions codeTypeReferenceOption) : this(type)
{
Options = codeTypeReferenceOption;
}
public CodeTypeReference(string typeName, CodeTypeReferenceOptions codeTypeReferenceOption)
{
Initialize(typeName, codeTypeReferenceOption);
}
public CodeTypeReference(string typeName)
{
Initialize(typeName);
}
private void InitializeFromType(Type type)
{
_baseType = type.Name;
if (!type.IsGenericParameter)
{
Type currentType = type;
while (currentType.IsNested)
{
currentType = currentType.DeclaringType;
_baseType = currentType.Name + "+" + _baseType;
}
if (!string.IsNullOrEmpty(type.Namespace))
{
_baseType = type.Namespace + "." + _baseType;
}
}
// pick up the type arguments from an instantiated generic type but not an open one
if (type.IsGenericType && !type.ContainsGenericParameters)
{
Type[] genericArgs = type.GetGenericArguments();
for (int i = 0; i < genericArgs.Length; i++)
{
TypeArguments.Add(new CodeTypeReference(genericArgs[i]));
}
}
else if (!type.IsGenericTypeDefinition)
{
// if the user handed us a non-generic type, but later
// appends generic type arguments, we'll pretend
// it's a generic type for their sake - this is good for
// them if they pass in System.Nullable class when they
// meant the System.Nullable<T> value type.
_needsFixup = true;
}
}
private void Initialize(string typeName)
{
Initialize(typeName, Options);
}
private void Initialize(string typeName, CodeTypeReferenceOptions options)
{
Options = options;
if (string.IsNullOrEmpty(typeName))
{
typeName = typeof(void).FullName;
_baseType = typeName;
ArrayRank = 0;
ArrayElementType = null;
return;
}
typeName = RipOffAssemblyInformationFromTypeName(typeName);
int end = typeName.Length - 1;
int current = end;
_needsFixup = true; // default to true, and if we find arity or generic type args, we'll clear the flag.
// Scan the entire string for valid array tails and store ranks for array tails
// we found in a queue.
var q = new Queue<int>();
while (current >= 0)
{
int rank = 1;
if (typeName[current--] == ']')
{
while (current >= 0 && typeName[current] == ',')
{
rank++;
current--;
}
if (current >= 0 && typeName[current] == '[')
{
// found a valid array tail
q.Enqueue(rank);
current--;
end = current;
continue;
}
}
break;
}
// Try find generic type arguments
current = end;
var typeArgumentList = new List<CodeTypeReference>();
var subTypeNames = new Stack<string>();
if (current > 0 && typeName[current--] == ']')
{
_needsFixup = false;
int unmatchedRightBrackets = 1;
int subTypeNameEndIndex = end;
// Try find the matching '[', if we can't find it, we will not try to parse the string
while (current >= 0)
{
if (typeName[current] == '[')
{
// break if we found matched brackets
if (--unmatchedRightBrackets == 0) break;
}
else if (typeName[current] == ']')
{
++unmatchedRightBrackets;
}
else if (typeName[current] == ',' && unmatchedRightBrackets == 1)
{
//
// Type name can contain nested generic types. Following is an example:
// System.Collections.Generic.Dictionary`2[[System.string, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089],
// [System.Collections.Generic.List`1[[System.Int32, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]],
// mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]
//
// Spliltting by ',' won't work. We need to do first-level split by ','.
//
if (current + 1 < subTypeNameEndIndex)
{
subTypeNames.Push(typeName.Substring(current + 1, subTypeNameEndIndex - current - 1));
}
subTypeNameEndIndex = current;
}
--current;
}
if (current > 0 && (end - current - 1) > 0)
{
// push the last generic type argument name if there is any
if (current + 1 < subTypeNameEndIndex)
{
subTypeNames.Push(typeName.Substring(current + 1, subTypeNameEndIndex - current - 1));
}
// we found matched brackets and the brackets contains some characters.
while (subTypeNames.Count > 0)
{
string name = RipOffAssemblyInformationFromTypeName(subTypeNames.Pop());
typeArgumentList.Add(new CodeTypeReference(name));
}
end = current - 1;
}
}
if (end < 0)
{
// this can happen if we have some string like "[...]"
_baseType = typeName;
return;
}
if (q.Count > 0)
{
CodeTypeReference type = new CodeTypeReference(typeName.Substring(0, end + 1), Options);
for (int i = 0; i < typeArgumentList.Count; i++)
{
type.TypeArguments.Add(typeArgumentList[i]);
}
while (q.Count > 1)
{
type = new CodeTypeReference(type, q.Dequeue());
}
// we don't need to create a new CodeTypeReference for the last one.
Debug.Assert(q.Count == 1, "We should have one and only one in the rank queue.");
_baseType = null;
ArrayRank = q.Dequeue();
ArrayElementType = type;
}
else if (typeArgumentList.Count > 0)
{
for (int i = 0; i < typeArgumentList.Count; i++)
{
TypeArguments.Add(typeArgumentList[i]);
}
_baseType = typeName.Substring(0, end + 1);
}
else
{
_baseType = typeName;
}
// Now see if we have some arity. baseType could be null if this is an array type.
if (_baseType != null && _baseType.IndexOf('`') != -1)
{
_needsFixup = false;
}
}
public CodeTypeReference(string typeName, params CodeTypeReference[] typeArguments) : this(typeName)
{
if (typeArguments != null && typeArguments.Length > 0)
{
TypeArguments.AddRange(typeArguments);
}
}
#if !FEATURE_SERIALIZATION
public CodeTypeReference(CodeTypeParameter typeParameter) :
this(typeParameter?.Name)
{
Options = CodeTypeReferenceOptions.GenericTypeParameter;
}
#endif
public CodeTypeReference(string baseType, int rank)
{
_baseType = null;
ArrayRank = rank;
ArrayElementType = new CodeTypeReference(baseType);
}
public CodeTypeReference(CodeTypeReference arrayType, int rank)
{
_baseType = null;
ArrayRank = rank;
ArrayElementType = arrayType;
}
public CodeTypeReference ArrayElementType { get; set; }
public int ArrayRank { get; set; }
internal int NestedArrayDepth => ArrayElementType == null ? 0 : 1 + ArrayElementType.NestedArrayDepth;
public string BaseType
{
get
{
if (ArrayRank > 0 && ArrayElementType != null)
{
return ArrayElementType.BaseType;
}
if (string.IsNullOrEmpty(_baseType))
{
return string.Empty;
}
string returnType = _baseType;
return _needsFixup && TypeArguments.Count > 0 ?
returnType + '`' + TypeArguments.Count.ToString(CultureInfo.InvariantCulture) :
returnType;
}
set
{
_baseType = value;
Initialize(_baseType);
}
}
public CodeTypeReferenceOptions Options { get; set; }
public CodeTypeReferenceCollection TypeArguments
{
get
{
if (ArrayRank > 0 && ArrayElementType != null)
{
return ArrayElementType.TypeArguments;
}
if (_typeArguments == null)
{
_typeArguments = new CodeTypeReferenceCollection();
}
return _typeArguments;
}
}
internal bool IsInterface => _isInterface; // Note that this only works correctly if the Type ctor was used. Otherwise, it's always false.
//
// The string for generic type argument might contain assembly information and square bracket pair.
// There might be leading spaces in front the type name.
// Following function will rip off assembly information and brackets
// Following is an example:
// " [System.Collections.Generic.List[[System.string, mscorlib, Version=2.0.0.0, Culture=neutral,
// PublicKeyToken=b77a5c561934e089]], mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]"
//
private string RipOffAssemblyInformationFromTypeName(string typeName)
{
int start = 0;
int end = typeName.Length - 1;
string result = typeName;
// skip whitespace in the beginning
while (start < typeName.Length && char.IsWhiteSpace(typeName[start])) start++;
while (end >= 0 && char.IsWhiteSpace(typeName[end])) end--;
if (start < end)
{
if (typeName[start] == '[' && typeName[end] == ']')
{
start++;
end--;
}
// if we still have a ] at the end, there's no assembly info.
if (typeName[end] != ']')
{
int commaCount = 0;
for (int index = end; index >= start; index--)
{
if (typeName[index] == ',')
{
commaCount++;
if (commaCount == 4)
{
result = typeName.Substring(start, index - start);
break;
}
}
}
}
}
return result;
}
}
}
| |
using System;
using System.Data;
using System.Data.SqlClient;
using Csla;
using Csla.Data;
namespace ParentLoadSoftDelete.Business.ERLevel
{
/// <summary>
/// E10Level11111 (editable child object).<br/>
/// This is a generated base class of <see cref="E10Level11111"/> business object.
/// </summary>
/// <remarks>
/// This class contains one child collection:<br/>
/// - <see cref="E11Level111111Objects"/> of type <see cref="E11Level111111Coll"/> (1:M relation to <see cref="E12Level111111"/>)<br/>
/// This class is an item of <see cref="E09Level11111Coll"/> collection.
/// </remarks>
[Serializable]
public partial class E10Level11111 : BusinessBase<E10Level11111>
{
#region Static Fields
private static int _lastID;
#endregion
#region State Fields
[NotUndoable]
[NonSerialized]
internal int narentID1 = 0;
#endregion
#region Business Properties
/// <summary>
/// Maintains metadata about <see cref="Level_1_1_1_1_1_ID"/> property.
/// </summary>
public static readonly PropertyInfo<int> Level_1_1_1_1_1_IDProperty = RegisterProperty<int>(p => p.Level_1_1_1_1_1_ID, "Level_1_1_1_1_1 ID");
/// <summary>
/// Gets the Level_1_1_1_1_1 ID.
/// </summary>
/// <value>The Level_1_1_1_1_1 ID.</value>
public int Level_1_1_1_1_1_ID
{
get { return GetProperty(Level_1_1_1_1_1_IDProperty); }
}
/// <summary>
/// Maintains metadata about <see cref="Level_1_1_1_1_1_Name"/> property.
/// </summary>
public static readonly PropertyInfo<string> Level_1_1_1_1_1_NameProperty = RegisterProperty<string>(p => p.Level_1_1_1_1_1_Name, "Level_1_1_1_1_1 Name");
/// <summary>
/// Gets or sets the Level_1_1_1_1_1 Name.
/// </summary>
/// <value>The Level_1_1_1_1_1 Name.</value>
public string Level_1_1_1_1_1_Name
{
get { return GetProperty(Level_1_1_1_1_1_NameProperty); }
set { SetProperty(Level_1_1_1_1_1_NameProperty, value); }
}
/// <summary>
/// Maintains metadata about child <see cref="E11Level111111SingleObject"/> property.
/// </summary>
public static readonly PropertyInfo<E11Level111111Child> E11Level111111SingleObjectProperty = RegisterProperty<E11Level111111Child>(p => p.E11Level111111SingleObject, "E11 Level111111 Single Object", RelationshipTypes.Child);
/// <summary>
/// Gets the E11 Level111111 Single Object ("parent load" child property).
/// </summary>
/// <value>The E11 Level111111 Single Object.</value>
public E11Level111111Child E11Level111111SingleObject
{
get { return GetProperty(E11Level111111SingleObjectProperty); }
private set { LoadProperty(E11Level111111SingleObjectProperty, value); }
}
/// <summary>
/// Maintains metadata about child <see cref="E11Level111111ASingleObject"/> property.
/// </summary>
public static readonly PropertyInfo<E11Level111111ReChild> E11Level111111ASingleObjectProperty = RegisterProperty<E11Level111111ReChild>(p => p.E11Level111111ASingleObject, "E11 Level111111 ASingle Object", RelationshipTypes.Child);
/// <summary>
/// Gets the E11 Level111111 ASingle Object ("parent load" child property).
/// </summary>
/// <value>The E11 Level111111 ASingle Object.</value>
public E11Level111111ReChild E11Level111111ASingleObject
{
get { return GetProperty(E11Level111111ASingleObjectProperty); }
private set { LoadProperty(E11Level111111ASingleObjectProperty, value); }
}
/// <summary>
/// Maintains metadata about child <see cref="E11Level111111Objects"/> property.
/// </summary>
public static readonly PropertyInfo<E11Level111111Coll> E11Level111111ObjectsProperty = RegisterProperty<E11Level111111Coll>(p => p.E11Level111111Objects, "E11 Level111111 Objects", RelationshipTypes.Child);
/// <summary>
/// Gets the E11 Level111111 Objects ("parent load" child property).
/// </summary>
/// <value>The E11 Level111111 Objects.</value>
public E11Level111111Coll E11Level111111Objects
{
get { return GetProperty(E11Level111111ObjectsProperty); }
private set { LoadProperty(E11Level111111ObjectsProperty, value); }
}
#endregion
#region Factory Methods
/// <summary>
/// Factory method. Creates a new <see cref="E10Level11111"/> object.
/// </summary>
/// <returns>A reference to the created <see cref="E10Level11111"/> object.</returns>
internal static E10Level11111 NewE10Level11111()
{
return DataPortal.CreateChild<E10Level11111>();
}
/// <summary>
/// Factory method. Loads a <see cref="E10Level11111"/> object from the given SafeDataReader.
/// </summary>
/// <param name="dr">The SafeDataReader to use.</param>
/// <returns>A reference to the fetched <see cref="E10Level11111"/> object.</returns>
internal static E10Level11111 GetE10Level11111(SafeDataReader dr)
{
E10Level11111 obj = new E10Level11111();
// show the framework that this is a child object
obj.MarkAsChild();
obj.Fetch(dr);
obj.LoadProperty(E11Level111111ObjectsProperty, E11Level111111Coll.NewE11Level111111Coll());
obj.MarkOld();
return obj;
}
#endregion
#region Constructor
/// <summary>
/// Initializes a new instance of the <see cref="E10Level11111"/> class.
/// </summary>
/// <remarks> Do not use to create a Csla object. Use factory methods instead.</remarks>
private E10Level11111()
{
// Prevent direct creation
// show the framework that this is a child object
MarkAsChild();
}
#endregion
#region Data Access
/// <summary>
/// Loads default values for the <see cref="E10Level11111"/> object properties.
/// </summary>
[Csla.RunLocal]
protected override void Child_Create()
{
LoadProperty(Level_1_1_1_1_1_IDProperty, System.Threading.Interlocked.Decrement(ref _lastID));
LoadProperty(E11Level111111SingleObjectProperty, DataPortal.CreateChild<E11Level111111Child>());
LoadProperty(E11Level111111ASingleObjectProperty, DataPortal.CreateChild<E11Level111111ReChild>());
LoadProperty(E11Level111111ObjectsProperty, DataPortal.CreateChild<E11Level111111Coll>());
var args = new DataPortalHookArgs();
OnCreate(args);
base.Child_Create();
}
/// <summary>
/// Loads a <see cref="E10Level11111"/> object from the given SafeDataReader.
/// </summary>
/// <param name="dr">The SafeDataReader to use.</param>
private void Fetch(SafeDataReader dr)
{
// Value properties
LoadProperty(Level_1_1_1_1_1_IDProperty, dr.GetInt32("Level_1_1_1_1_1_ID"));
LoadProperty(Level_1_1_1_1_1_NameProperty, dr.GetString("Level_1_1_1_1_1_Name"));
narentID1 = dr.GetInt32("NarentID1");
var args = new DataPortalHookArgs(dr);
OnFetchRead(args);
}
/// <summary>
/// Loads child <see cref="E11Level111111Child"/> object.
/// </summary>
/// <param name="child">The child object to load.</param>
internal void LoadChild(E11Level111111Child child)
{
LoadProperty(E11Level111111SingleObjectProperty, child);
}
/// <summary>
/// Loads child <see cref="E11Level111111ReChild"/> object.
/// </summary>
/// <param name="child">The child object to load.</param>
internal void LoadChild(E11Level111111ReChild child)
{
LoadProperty(E11Level111111ASingleObjectProperty, child);
}
/// <summary>
/// Inserts a new <see cref="E10Level11111"/> object in the database.
/// </summary>
/// <param name="parent">The parent object.</param>
[Transactional(TransactionalTypes.TransactionScope)]
private void Child_Insert(E08Level1111 parent)
{
using (var ctx = ConnectionManager<SqlConnection>.GetManager("DeepLoad"))
{
using (var cmd = new SqlCommand("AddE10Level11111", ctx.Connection))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@Level_1_1_1_1_ID", parent.Level_1_1_1_1_ID).DbType = DbType.Int32;
cmd.Parameters.AddWithValue("@Level_1_1_1_1_1_ID", ReadProperty(Level_1_1_1_1_1_IDProperty)).Direction = ParameterDirection.Output;
cmd.Parameters.AddWithValue("@Level_1_1_1_1_1_Name", ReadProperty(Level_1_1_1_1_1_NameProperty)).DbType = DbType.String;
var args = new DataPortalHookArgs(cmd);
OnInsertPre(args);
cmd.ExecuteNonQuery();
OnInsertPost(args);
LoadProperty(Level_1_1_1_1_1_IDProperty, (int) cmd.Parameters["@Level_1_1_1_1_1_ID"].Value);
}
FieldManager.UpdateChildren(this);
}
}
/// <summary>
/// Updates in the database all changes made to the <see cref="E10Level11111"/> object.
/// </summary>
[Transactional(TransactionalTypes.TransactionScope)]
private void Child_Update()
{
using (var ctx = ConnectionManager<SqlConnection>.GetManager("DeepLoad"))
{
using (var cmd = new SqlCommand("UpdateE10Level11111", ctx.Connection))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@Level_1_1_1_1_1_ID", ReadProperty(Level_1_1_1_1_1_IDProperty)).DbType = DbType.Int32;
cmd.Parameters.AddWithValue("@Level_1_1_1_1_1_Name", ReadProperty(Level_1_1_1_1_1_NameProperty)).DbType = DbType.String;
var args = new DataPortalHookArgs(cmd);
OnUpdatePre(args);
cmd.ExecuteNonQuery();
OnUpdatePost(args);
}
FieldManager.UpdateChildren(this);
}
}
/// <summary>
/// Self deletes the <see cref="E10Level11111"/> object from database.
/// </summary>
[Transactional(TransactionalTypes.TransactionScope)]
private void Child_DeleteSelf()
{
using (var ctx = ConnectionManager<SqlConnection>.GetManager("DeepLoad"))
{
// flushes all pending data operations
FieldManager.UpdateChildren(this);
using (var cmd = new SqlCommand("DeleteE10Level11111", ctx.Connection))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@Level_1_1_1_1_1_ID", ReadProperty(Level_1_1_1_1_1_IDProperty)).DbType = DbType.Int32;
var args = new DataPortalHookArgs(cmd);
OnDeletePre(args);
cmd.ExecuteNonQuery();
OnDeletePost(args);
}
}
// removes all previous references to children
LoadProperty(E11Level111111SingleObjectProperty, DataPortal.CreateChild<E11Level111111Child>());
LoadProperty(E11Level111111ASingleObjectProperty, DataPortal.CreateChild<E11Level111111ReChild>());
LoadProperty(E11Level111111ObjectsProperty, DataPortal.CreateChild<E11Level111111Coll>());
}
#endregion
#region Pseudo Events
/// <summary>
/// Occurs after setting all defaults for object creation.
/// </summary>
partial void OnCreate(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Delete, after setting query parameters and before the delete operation.
/// </summary>
partial void OnDeletePre(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Delete, after the delete operation, before Commit().
/// </summary>
partial void OnDeletePost(DataPortalHookArgs args);
/// <summary>
/// Occurs after setting query parameters and before the fetch operation.
/// </summary>
partial void OnFetchPre(DataPortalHookArgs args);
/// <summary>
/// Occurs after the fetch operation (object or collection is fully loaded and set up).
/// </summary>
partial void OnFetchPost(DataPortalHookArgs args);
/// <summary>
/// Occurs after the low level fetch operation, before the data reader is destroyed.
/// </summary>
partial void OnFetchRead(DataPortalHookArgs args);
/// <summary>
/// Occurs after setting query parameters and before the update operation.
/// </summary>
partial void OnUpdatePre(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Insert, after the update operation, before setting back row identifiers (RowVersion) and Commit().
/// </summary>
partial void OnUpdatePost(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Insert, after setting query parameters and before the insert operation.
/// </summary>
partial void OnInsertPre(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Insert, after the insert operation, before setting back row identifiers (ID and RowVersion) and Commit().
/// </summary>
partial void OnInsertPost(DataPortalHookArgs args);
#endregion
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
namespace FogCreek.Wasabi.AST
{
public class CParameters : INodeParent
{
public class ParameterList : IEnumerable<CNode>
{
private readonly INodeParent parent;
private List<CNode> items = new List<CNode>();
public ParameterList(INodeParent parent)
{
this.parent = parent;
}
public ParameterList(INodeParent parent, ParameterList source)
{
this.parent = parent;
items.AddRange(source.items);
}
public void Add(CNode parameter)
{
if (parameter != null)
parameter.Parent = parent;
items.Add(parameter);
}
public void RemoveAt(int ix)
{
items.RemoveAt(ix);
}
public int Count
{
get { return items.Count; }
}
public CNode this[int ix]
{
get { return items[ix]; }
set
{
items[ix] = value;
value.Parent = parent;
}
}
public void Replace(CNode child, CNode newchild)
{
for (int ix = 0; ix < items.Count; ix++)
{
if (items[ix] == child)
{
items[ix] = newchild;
newchild.Parent = parent;
}
}
}
internal void UpdateParents()
{
foreach (CNode node in items)
if (node != null)
node.Parent = parent;
}
#region IEnumerable<CNode> Members
IEnumerator<CNode> IEnumerable<CNode>.GetEnumerator()
{
return items.GetEnumerator();
}
#endregion
#region IEnumerable Members
IEnumerator IEnumerable.GetEnumerator()
{
return items.GetEnumerator();
}
#endregion
}
public class NamedParameterList : object, IEnumerable<KeyValuePair<string, CNode>>, INodeParent
{
CParameters parent;
int count = 0;
KeyValuePair<string, CNode>[] items;
public NamedParameterList(CParameters parent, int size)
{
this.parent = parent;
items = new KeyValuePair<string, CNode>[size * 2];
count = 0;
}
public NamedParameterList(CParameters parent)
: this(parent, 16)
{
}
public NamedParameterList(CParameters parent, NamedParameterList src)
: this(parent, src.count)
{
Array.Copy(src.items, items, src.count);
count = src.count;
}
public CNode this[string key]
{
get
{
for (int i = 0; i < count; i++)
{
if (items[i].Key == key) return items[i].Value;
}
throw new ArgumentOutOfRangeException("key");
}
}
public KeyValuePair<string, CNode> this[int ix]
{
get { return items[ix]; }
}
public int Count
{
get { return count; }
}
#region INodeParent Members
public void Replace(CNode child, CNode newchild)
{
for (int i = 0; i < count; i++)
{
if (items[i].Value == child)
{
items[i] = new KeyValuePair<string, CNode>(items[i].Key, newchild);
newchild.Parent = parent;
}
}
}
#endregion
#region IEnumerable<KeyValuePair<string,CNode>> Members
public IEnumerator<KeyValuePair<string, CNode>> GetEnumerator()
{
for (int i = 0; i < count; i++)
{
yield return items[i];
}
}
#endregion
#region IEnumerable Members
IEnumerator IEnumerable.GetEnumerator()
{
for (int i = 0; i < count; i++)
{
yield return items[i];
}
}
#endregion
internal bool ContainsKey(string p)
{
for (int i = 0; i < count; i++)
{
if (items[i].Key == p) return true;
}
return false;
}
internal void Add(string p, CExpression cExpression)
{
if (items.Length == count)
Array.Resize(ref items, items.Length * 2);
items[count++] = new KeyValuePair<string, CNode>(p, cExpression);
cExpression.Parent = parent;
}
}
private ParameterList unnamedParams;
private NamedParameterList namedParams;
private bool _semanticallyComplete = false;
private CNode parent;
public CParameters()
{
namedParams = new NamedParameterList(this);
unnamedParams = new ParameterList(this);
}
public CParameters(CParameters @params)
{
parent = @params.parent;
unnamedParams = new ParameterList(this, @params.unnamedParams);
namedParams = new NamedParameterList(this, @params.namedParams);
}
public CParameters(params CExpression[] exprs)
: this()
{
foreach (CExpression node in exprs)
{
unnamedParams.Add(node);
}
}
public void Accept(IVisitor visit)
{
visit.VisitParameters(this);
}
internal List<CNode> GetDistinctNodes()
{
List<CNode> list = new List<CNode>();
foreach (CNode node in unnamedParams)
if (node != null && !list.Contains(node))
list.Add(node);
foreach (KeyValuePair<string, CNode> pair in namedParams)
if (pair.Value != null && !list.Contains(pair.Value))
list.Add(pair.Value);
return list;
}
public bool SemanticallyComplete
{
get { return _semanticallyComplete; }
}
public ParameterList Unnamed
{
get { return unnamedParams; }
}
public NamedParameterList Named
{
get { return namedParams; }
}
public CNode this[int ix]
{
get { return unnamedParams[ix]; }
}
public CNode Parent
{
get { return parent; }
set { parent = value; }
}
public void setSemanticallyComplete()
{
_semanticallyComplete = true;
}
public void resetSemanticallyComplete()
{
_semanticallyComplete = false;
}
public void Replace(CNode child, CNode newchild)
{
namedParams.Replace(child, newchild);
unnamedParams.Replace(child, newchild);
}
}
}
| |
using System;
using System.Threading.Tasks;
using Orleans.Runtime.Configuration;
namespace Orleans.Runtime
{
/// <summary>
/// This interface is for use with the Orleans timers.
/// </summary>
internal interface ITimebound
{
/// <summary>
/// This method is called by the timer when the time out is reached.
/// </summary>
void OnTimeout();
TimeSpan RequestedTimeout();
}
internal class CallbackData : ITimebound, IDisposable
{
private readonly Action<Message, TaskCompletionSource<object>> callback;
private readonly Func<Message, bool> resendFunc;
private readonly Action unregister;
private readonly TaskCompletionSource<object> context;
private bool alreadyFired;
private TimeSpan timeout;
private SafeTimer timer;
private ITimeInterval timeSinceIssued;
private IMessagingConfiguration config;
private static readonly Logger logger = LogManager.GetLogger("CallbackData");
public Message Message { get; set; } // might hold metadata used by response pipeline
public CallbackData(
Action<Message, TaskCompletionSource<object>> callback,
Func<Message, bool> resendFunc,
TaskCompletionSource<object> ctx,
Message msg,
Action unregisterDelegate,
IMessagingConfiguration config)
{
// We are never called without a callback func, but best to double check.
if (callback == null) throw new ArgumentNullException(nameof(callback));
// We are never called without a resend func, but best to double check.
if (resendFunc == null) throw new ArgumentNullException(nameof(resendFunc));
this.callback = callback;
this.resendFunc = resendFunc;
context = ctx;
Message = msg;
unregister = unregisterDelegate;
alreadyFired = false;
this.config = config;
}
/// <summary>
/// Start this callback timer
/// </summary>
/// <param name="time">Timeout time</param>
public void StartTimer(TimeSpan time)
{
if (time < TimeSpan.Zero)
throw new ArgumentOutOfRangeException(nameof(time), "The timeout parameter is negative.");
timeout = time;
if (StatisticsCollector.CollectApplicationRequestsStats)
{
timeSinceIssued = TimeIntervalFactory.CreateTimeInterval(true);
timeSinceIssued.Start();
}
TimeSpan firstPeriod = timeout;
TimeSpan repeatPeriod = Constants.INFINITE_TIMESPAN; // Single timeout period --> No repeat
if (config.ResendOnTimeout && config.MaxResendCount > 0)
{
firstPeriod = repeatPeriod = timeout.Divide(config.MaxResendCount + 1);
}
// Start time running
DisposeTimer();
timer = new SafeTimer(TimeoutCallback, null, firstPeriod, repeatPeriod);
}
private void TimeoutCallback(object obj)
{
OnTimeout();
}
public void OnTimeout()
{
if (alreadyFired)
return;
var msg = Message; // Local working copy
string messageHistory = msg.GetTargetHistory();
string errorMsg = $"Response did not arrive on time in {timeout} for message: {msg}. Target History is: {messageHistory}.";
logger.Warn(ErrorCode.Runtime_Error_100157, "{0} About to break its promise.", errorMsg);
var error = msg.CreatePromptExceptionResponse(new TimeoutException(errorMsg));
OnFail(msg, error, "OnTimeout - Resend {0} for {1}", true);
}
public void OnTargetSiloFail()
{
if (alreadyFired)
return;
var msg = Message;
var messageHistory = msg.GetTargetHistory();
string errorMsg =
$"The target silo became unavailable for message: {msg}. Target History is: {messageHistory}. See {Constants.TroubleshootingHelpLink} for troubleshooting help.";
logger.Warn(ErrorCode.Runtime_Error_100157, "{0} About to break its promise.", errorMsg);
var error = msg.CreatePromptExceptionResponse(new SiloUnavailableException(errorMsg));
OnFail(msg, error, "On silo fail - Resend {0} for {1}");
}
public void DoCallback(Message response)
{
if (alreadyFired)
return;
lock (this)
{
if (alreadyFired)
return;
if (response.Result == Message.ResponseTypes.Rejection && response.RejectionType == Message.RejectionTypes.Transient)
{
if (resendFunc(Message))
{
return;
}
}
alreadyFired = true;
DisposeTimer();
if (StatisticsCollector.CollectApplicationRequestsStats)
{
timeSinceIssued.Stop();
}
unregister?.Invoke();
}
if (StatisticsCollector.CollectApplicationRequestsStats)
{
ApplicationRequestsStatisticsGroup.OnAppRequestsEnd(timeSinceIssued.Elapsed);
}
// do callback outside the CallbackData lock. Just not a good practice to hold a lock for this unrelated operation.
callback(response, context);
}
public void Dispose()
{
DisposeTimer();
GC.SuppressFinalize(this);
}
private void DisposeTimer()
{
try
{
var tmp = timer;
if (tmp != null)
{
timer = null;
tmp.Dispose();
}
}
catch (Exception) { } // Ignore any problems with Dispose
}
private void OnFail(Message msg, Message error, string resendLogMessageFormat, bool isOnTimeout = false)
{
lock (this)
{
if (alreadyFired)
return;
if (config.ResendOnTimeout && resendFunc(msg))
{
if (logger.IsVerbose) logger.Verbose(resendLogMessageFormat, msg.ResendCount, msg);
return;
}
alreadyFired = true;
DisposeTimer();
if (StatisticsCollector.CollectApplicationRequestsStats)
{
timeSinceIssued.Stop();
}
unregister?.Invoke();
}
if (StatisticsCollector.CollectApplicationRequestsStats)
{
ApplicationRequestsStatisticsGroup.OnAppRequestsEnd(timeSinceIssued.Elapsed);
if (isOnTimeout)
{
ApplicationRequestsStatisticsGroup.OnAppRequestsTimedOut();
}
}
callback(error, context);
}
public TimeSpan RequestedTimeout()
{
return timeout;
}
}
}
| |
// 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.Diagnostics.Contracts;
namespace System.Globalization
{
//
// This class implements the Julian calendar. In 48 B.C. Julius Caesar ordered a calendar reform, and this calendar
// is called Julian calendar. It consisted of a solar year of twelve months and of 365 days with an extra day
// every fourth year.
//*
//* Calendar support range:
//* Calendar Minimum Maximum
//* ========== ========== ==========
//* Gregorian 0001/01/01 9999/12/31
//* Julia 0001/01/03 9999/10/19
[System.Runtime.InteropServices.ComVisible(true)]
public class JulianCalendar : Calendar
{
public static readonly int JulianEra = 1;
private const int DatePartYear = 0;
private const int DatePartDayOfYear = 1;
private const int DatePartMonth = 2;
private const int DatePartDay = 3;
// Number of days in a non-leap year
private const int JulianDaysPerYear = 365;
// Number of days in 4 years
private const int JulianDaysPer4Years = JulianDaysPerYear * 4 + 1;
//internal static Calendar m_defaultInstance;
private static readonly int[] DaysToMonth365 =
{
0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365
};
private static readonly int[] DaysToMonth366 =
{
0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335, 366
};
// Gregorian Calendar 9999/12/31 = Julian Calendar 9999/10/19
// keep it as variable field for serialization compat.
internal int MaxYear = 9999;
[System.Runtime.InteropServices.ComVisible(false)]
public override DateTime MinSupportedDateTime
{
get
{
return (DateTime.MinValue);
}
}
[System.Runtime.InteropServices.ComVisible(false)]
public override DateTime MaxSupportedDateTime
{
get
{
return (DateTime.MaxValue);
}
}
// Return the type of the Julian calendar.
//
//[System.Runtime.InteropServices.ComVisible(false)]
//public override CalendarAlgorithmType AlgorithmType
//{
// get
// {
// return CalendarAlgorithmType.SolarCalendar;
// }
//}
/*=================================GetDefaultInstance==========================
**Action: Internal method to provide a default intance of JulianCalendar. Used by NLS+ implementation
** and other calendars.
**Returns:
**Arguments:
**Exceptions:
============================================================================*/
/*
internal static Calendar GetDefaultInstance() {
if (m_defaultInstance == null) {
m_defaultInstance = new JulianCalendar();
}
return (m_defaultInstance);
}
*/
// Construct an instance of gregorian calendar.
public JulianCalendar()
{
// There is no system setting of TwoDigitYear max, so set the value here.
twoDigitYearMax = 2029;
}
internal override CalendarId ID
{
get
{
return CalendarId.JULIAN;
}
}
static internal void CheckEraRange(int era)
{
if (era != CurrentEra && era != JulianEra)
{
throw new ArgumentOutOfRangeException("era", SR.ArgumentOutOfRange_InvalidEraValue);
}
}
internal void CheckYearEraRange(int year, int era)
{
CheckEraRange(era);
if (year <= 0 || year > MaxYear)
{
throw new ArgumentOutOfRangeException(
"year",
String.Format(
CultureInfo.CurrentCulture,
SR.ArgumentOutOfRange_Range,
1,
MaxYear));
}
}
static internal void CheckMonthRange(int month)
{
if (month < 1 || month > 12)
{
throw new ArgumentOutOfRangeException("month", SR.ArgumentOutOfRange_Month);
}
}
/*=================================GetDefaultInstance==========================
**Action: Check for if the day value is valid.
**Returns:
**Arguments:
**Exceptions:
**Notes:
** Before calling this method, call CheckYearEraRange()/CheckMonthRange() to make
** sure year/month values are correct.
============================================================================*/
static internal void CheckDayRange(int year, int month, int day)
{
if (year == 1 && month == 1)
{
// The mimimum supported Julia date is Julian 0001/01/03.
if (day < 3)
{
throw new ArgumentOutOfRangeException(null,
SR.ArgumentOutOfRange_BadYearMonthDay);
}
}
bool isLeapYear = (year % 4) == 0;
int[] days = isLeapYear ? DaysToMonth366 : DaysToMonth365;
int monthDays = days[month] - days[month - 1];
if (day < 1 || day > monthDays)
{
throw new ArgumentOutOfRangeException(
"day",
String.Format(
CultureInfo.CurrentCulture,
SR.ArgumentOutOfRange_Range,
1,
monthDays));
}
}
// Returns a given date part of this DateTime. This method is used
// to compute the year, day-of-year, month, or day part.
static internal int GetDatePart(long ticks, int part)
{
// Gregorian 1/1/0001 is Julian 1/3/0001. Remember DateTime(0) is refered to Gregorian 1/1/0001.
// The following line convert Gregorian ticks to Julian ticks.
long julianTicks = ticks + TicksPerDay * 2;
// n = number of days since 1/1/0001
int n = (int)(julianTicks / TicksPerDay);
// y4 = number of whole 4-year periods within 100-year period
int y4 = n / JulianDaysPer4Years;
// n = day number within 4-year period
n -= y4 * JulianDaysPer4Years;
// y1 = number of whole years within 4-year period
int y1 = n / JulianDaysPerYear;
// Last year has an extra day, so decrement result if 4
if (y1 == 4) y1 = 3;
// If year was requested, compute and return it
if (part == DatePartYear)
{
return (y4 * 4 + y1 + 1);
}
// n = day number within year
n -= y1 * JulianDaysPerYear;
// If day-of-year was requested, return it
if (part == DatePartDayOfYear)
{
return (n + 1);
}
// Leap year calculation looks different from IsLeapYear since y1, y4,
// and y100 are relative to year 1, not year 0
bool leapYear = (y1 == 3);
int[] days = leapYear ? DaysToMonth366 : DaysToMonth365;
// All months have less than 32 days, so n >> 5 is a good conservative
// estimate for the month
int m = n >> 5 + 1;
// m = 1-based month number
while (n >= days[m]) m++;
// If month was requested, return it
if (part == DatePartMonth) return (m);
// Return 1-based day-of-month
return (n - days[m - 1] + 1);
}
// Returns the tick count corresponding to the given year, month, and day.
static internal long DateToTicks(int year, int month, int day)
{
int[] days = (year % 4 == 0) ? DaysToMonth366 : DaysToMonth365;
int y = year - 1;
int n = y * 365 + y / 4 + days[month - 1] + day - 1;
// Gregorian 1/1/0001 is Julian 1/3/0001. n * TicksPerDay is the ticks in JulianCalendar.
// Therefore, we subtract two days in the following to convert the ticks in JulianCalendar
// to ticks in Gregorian calendar.
return ((n - 2) * TicksPerDay);
}
public override DateTime AddMonths(DateTime time, int months)
{
if (months < -120000 || months > 120000)
{
throw new ArgumentOutOfRangeException(
"months",
String.Format(
CultureInfo.CurrentCulture,
SR.ArgumentOutOfRange_Range,
-120000,
120000));
}
Contract.EndContractBlock();
int y = GetDatePart(time.Ticks, DatePartYear);
int m = GetDatePart(time.Ticks, DatePartMonth);
int d = GetDatePart(time.Ticks, DatePartDay);
int i = m - 1 + months;
if (i >= 0)
{
m = i % 12 + 1;
y = y + i / 12;
}
else
{
m = 12 + (i + 1) % 12;
y = y + (i - 11) / 12;
}
int[] daysArray = (y % 4 == 0 && (y % 100 != 0 || y % 400 == 0)) ? DaysToMonth366 : DaysToMonth365;
int days = (daysArray[m] - daysArray[m - 1]);
if (d > days)
{
d = days;
}
long ticks = DateToTicks(y, m, d) + time.Ticks % TicksPerDay;
Calendar.CheckAddResult(ticks, MinSupportedDateTime, MaxSupportedDateTime);
return (new DateTime(ticks));
}
public override DateTime AddYears(DateTime time, int years)
{
return (AddMonths(time, years * 12));
}
public override int GetDayOfMonth(DateTime time)
{
return (GetDatePart(time.Ticks, DatePartDay));
}
public override DayOfWeek GetDayOfWeek(DateTime time)
{
return ((DayOfWeek)((int)(time.Ticks / TicksPerDay + 1) % 7));
}
public override int GetDayOfYear(DateTime time)
{
return (GetDatePart(time.Ticks, DatePartDayOfYear));
}
public override int GetDaysInMonth(int year, int month, int era)
{
CheckYearEraRange(year, era);
CheckMonthRange(month);
int[] days = (year % 4 == 0) ? DaysToMonth366 : DaysToMonth365;
return (days[month] - days[month - 1]);
}
public override int GetDaysInYear(int year, int era)
{
// Year/Era range is done in IsLeapYear().
return (IsLeapYear(year, era) ? 366 : 365);
}
public override int GetEra(DateTime time)
{
return (JulianEra);
}
public override int GetMonth(DateTime time)
{
return (GetDatePart(time.Ticks, DatePartMonth));
}
public override int[] Eras
{
get
{
return (new int[] { JulianEra });
}
}
public override int GetMonthsInYear(int year, int era)
{
CheckYearEraRange(year, era);
return (12);
}
public override int GetYear(DateTime time)
{
return (GetDatePart(time.Ticks, DatePartYear));
}
public override bool IsLeapDay(int year, int month, int day, int era)
{
CheckMonthRange(month);
// Year/Era range check is done in IsLeapYear().
if (IsLeapYear(year, era))
{
CheckDayRange(year, month, day);
return (month == 2 && day == 29);
}
CheckDayRange(year, month, day);
return (false);
}
// Returns the leap month in a calendar year of the specified era. This method returns 0
// if this calendar does not have leap month, or this year is not a leap year.
//
[System.Runtime.InteropServices.ComVisible(false)]
public override int GetLeapMonth(int year, int era)
{
CheckYearEraRange(year, era);
return (0);
}
public override bool IsLeapMonth(int year, int month, int era)
{
CheckYearEraRange(year, era);
CheckMonthRange(month);
return (false);
}
// Checks whether a given year in the specified era is a leap year. This method returns true if
// year is a leap year, or false if not.
//
public override bool IsLeapYear(int year, int era)
{
CheckYearEraRange(year, era);
return (year % 4 == 0);
}
public override DateTime ToDateTime(int year, int month, int day, int hour, int minute, int second, int millisecond, int era)
{
CheckYearEraRange(year, era);
CheckMonthRange(month);
CheckDayRange(year, month, day);
if (millisecond < 0 || millisecond >= MillisPerSecond)
{
throw new ArgumentOutOfRangeException(
"millisecond",
String.Format(
CultureInfo.CurrentCulture,
SR.ArgumentOutOfRange_Range,
0,
MillisPerSecond - 1));
}
if (hour >= 0 && hour < 24 && minute >= 0 && minute < 60 && second >= 0 && second < 60)
{
return new DateTime(DateToTicks(year, month, day) + (new TimeSpan(0, hour, minute, second, millisecond)).Ticks);
}
else
{
throw new ArgumentOutOfRangeException(null, SR.ArgumentOutOfRange_BadHourMinuteSecond);
}
}
public override int TwoDigitYearMax
{
get
{
return (twoDigitYearMax);
}
set
{
VerifyWritable();
if (value < 99 || value > MaxYear)
{
throw new ArgumentOutOfRangeException(
"year",
String.Format(
CultureInfo.CurrentCulture,
SR.ArgumentOutOfRange_Range,
99,
MaxYear));
}
twoDigitYearMax = value;
}
}
public override int ToFourDigitYear(int year)
{
if (year < 0)
{
throw new ArgumentOutOfRangeException("year",
SR.ArgumentOutOfRange_NeedNonNegNum);
}
Contract.EndContractBlock();
if (year > MaxYear)
{
throw new ArgumentOutOfRangeException(
"year",
String.Format(
CultureInfo.CurrentCulture,
SR.ArgumentOutOfRange_Bounds_Lower_Upper,
1,
MaxYear));
}
return (base.ToFourDigitYear(year));
}
}
}
| |
// Copyright (c) 2010-2014 SharpDX - Alexandre Mutel
//
// 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 SharpDX.Mathematics.Interop;
namespace SharpDX.DirectSound
{
public partial class SoundBuffer3D
{
/// <summary>
/// Default cone angle, in degrees.
/// </summary>
public const float DefaultConeAngle = 360f;
/// <summary>
/// Default outside cone volume. Volume levels are expressed as attenuation, in hundredths of a decibel.
/// </summary>
public const int DefaultConeOutsideVolume = 0;
/// <summary>
/// Default maximum distance, in meters.
/// </summary>
public const float DefaultMaxDistance = 1E+09f;
/// <summary>
/// Default minimum distance, in meters.
/// </summary>
public const float DefaultMinDistance = 1f;
/// <summary>
/// Maximum cone angle, in degrees.
/// </summary>
public const float MaxConeAngle = 360f;
/// <summary>
/// Minimum cone angle, in degrees.
/// </summary>
public const float MinConeAngle = 0f;
/// <summary>
/// Initializes a new instance of the <see cref="T:SharpDX.DirectSound.SoundBuffer3D" /> class.
/// </summary>
/// <param name="soundBuffer" />
/// <returns />
public SoundBuffer3D(SoundBuffer soundBuffer)
{
QueryInterfaceFrom(soundBuffer);
}
/// <summary>
/// Gets or sets all the parameters of a buffer
/// </summary>
public Buffer3DSettings AllParameters
{
get
{
Buffer3DSettings temp;
GetAllParameters(out temp);
return temp;
}
set
{
SetAllParameters(value, Deferred ? 1 : 0);
}
}
/// <summary>
/// The orientation of the sound projection cone.
/// </summary>
public RawVector3 ConeOrientation
{
get {
RawVector3 temp;
GetConeOrientation(out temp);
return temp;
}
set
{
SetConeOrientation(value.X, value.Y, value.Z, Deferred ? 1 : 0);
}
}
/// <summary>
/// The volume of the sound outside the outside angle of the sound projection cone.
/// </summary>
public int ConeOutsideVolume
{
get
{
int temp;
GetConeOutsideVolume(out temp);
return temp;
}
set
{
SetConeOutsideVolume(value, Deferred ? 1 : 0);
}
}
/// <summary>
/// Settings are not applied until the application calls the SoundListener3D.CommitDeferredSettings() if true.
/// </summary>
public bool Deferred { get; set; }
/// <summary>
/// The inside angle of the sound projection cone.
/// </summary>
public int InsideConeAngle
{
get
{
int insideCondeAngle;
int outsideConeAngle;
GetConeAngles(out insideCondeAngle, out outsideConeAngle);
return insideCondeAngle;
}
set
{
SetConeAngles(value, OutsideConeAngle, Deferred ? 1 : 0);
}
}
/// <summary>
/// The maximum distance, which is the distance from the listener beyond which sounds in this buffer are no longer attenuated.
/// </summary>
public float MaxDistance
{
get
{
float temp;
GetMaxDistance(out temp);
return temp;
}
set
{
SetMaxDistance(value, Deferred ? 1 : 0);
}
}
/// <summary>
/// The minimum distance, which is the distance from the listener at which sounds in this buffer begin to be attenuated.
/// </summary>
public float MinDistance
{
get
{
float temp;
GetMinDistance(out temp);
return temp;
}
set
{
SetMinDistance(value, Deferred ? 1 : 0);
}
}
/// <summary>
/// The operation mode for 3-D sound processing.
/// </summary>
public Mode3D Mode
{
get
{
int temp;
GetMode(out temp);
return (Mode3D)temp;
}
set
{
SetMode((int)value, Deferred ? 1 : 0);
}
}
/// <summary>
/// The outside angle of the sound projection cone.
/// </summary>
public int OutsideConeAngle
{
get
{
int insideCondeAngle;
int outsideConeAngle;
GetConeAngles(out insideCondeAngle, out outsideConeAngle);
return outsideConeAngle;
}
set
{
SetConeAngles(InsideConeAngle, value, Deferred ? 1 : 0);
}
}
/// <summary>
/// The position of the sound source.
/// </summary>
public RawVector3 Position
{
get
{
RawVector3 temp;
GetPosition(out temp);
return temp;
}
set
{
SetPosition(value.X, value.Y, value.Z, Deferred ? 1 : 0);
}
}
/// <summary>
/// The velocity of the sound source.
/// </summary>
public RawVector3 Velocity
{
get
{
RawVector3 temp;
GetVelocity(out temp);
return temp;
}
set
{
SetVelocity(value.X, value.Y, value.Z, Deferred ? 1 : 0);
}
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Reflection;
namespace CodeJewels.Service.Areas.HelpPage
{
/// <summary>
/// This class will create an object of a given type and populate it with sample data.
/// </summary>
public class ObjectGenerator
{
private const int DefaultCollectionSize = 3;
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);
}
}
}
}
| |
// 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.0.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Management.Network
{
using Azure;
using Management;
using Rest;
using Rest.Azure;
using Models;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// Extension methods for NetworkSecurityGroupsOperations.
/// </summary>
public static partial class NetworkSecurityGroupsOperationsExtensions
{
/// <summary>
/// Deletes the specified network security group.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='networkSecurityGroupName'>
/// The name of the network security group.
/// </param>
public static void Delete(this INetworkSecurityGroupsOperations operations, string resourceGroupName, string networkSecurityGroupName)
{
operations.DeleteAsync(resourceGroupName, networkSecurityGroupName).GetAwaiter().GetResult();
}
/// <summary>
/// Deletes the specified network security group.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='networkSecurityGroupName'>
/// The name of the network security group.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task DeleteAsync(this INetworkSecurityGroupsOperations operations, string resourceGroupName, string networkSecurityGroupName, CancellationToken cancellationToken = default(CancellationToken))
{
await operations.DeleteWithHttpMessagesAsync(resourceGroupName, networkSecurityGroupName, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Gets the specified network security group.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='networkSecurityGroupName'>
/// The name of the network security group.
/// </param>
/// <param name='expand'>
/// Expands referenced resources.
/// </param>
public static NetworkSecurityGroup Get(this INetworkSecurityGroupsOperations operations, string resourceGroupName, string networkSecurityGroupName, string expand = default(string))
{
return operations.GetAsync(resourceGroupName, networkSecurityGroupName, expand).GetAwaiter().GetResult();
}
/// <summary>
/// Gets the specified network security group.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='networkSecurityGroupName'>
/// The name of the network security group.
/// </param>
/// <param name='expand'>
/// Expands referenced resources.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<NetworkSecurityGroup> GetAsync(this INetworkSecurityGroupsOperations operations, string resourceGroupName, string networkSecurityGroupName, string expand = default(string), CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetWithHttpMessagesAsync(resourceGroupName, networkSecurityGroupName, expand, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Creates or updates a network security group in the specified resource
/// group.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='networkSecurityGroupName'>
/// The name of the network security group.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to the create or update network security group
/// operation.
/// </param>
public static NetworkSecurityGroup CreateOrUpdate(this INetworkSecurityGroupsOperations operations, string resourceGroupName, string networkSecurityGroupName, NetworkSecurityGroup parameters)
{
return operations.CreateOrUpdateAsync(resourceGroupName, networkSecurityGroupName, parameters).GetAwaiter().GetResult();
}
/// <summary>
/// Creates or updates a network security group in the specified resource
/// group.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='networkSecurityGroupName'>
/// The name of the network security group.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to the create or update network security group
/// operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<NetworkSecurityGroup> CreateOrUpdateAsync(this INetworkSecurityGroupsOperations operations, string resourceGroupName, string networkSecurityGroupName, NetworkSecurityGroup parameters, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.CreateOrUpdateWithHttpMessagesAsync(resourceGroupName, networkSecurityGroupName, parameters, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Gets all network security groups in a subscription.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
public static IPage<NetworkSecurityGroup> ListAll(this INetworkSecurityGroupsOperations operations)
{
return operations.ListAllAsync().GetAwaiter().GetResult();
}
/// <summary>
/// Gets all network security groups in a subscription.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<NetworkSecurityGroup>> ListAllAsync(this INetworkSecurityGroupsOperations operations, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListAllWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Gets all network security groups in a resource group.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
public static IPage<NetworkSecurityGroup> List(this INetworkSecurityGroupsOperations operations, string resourceGroupName)
{
return operations.ListAsync(resourceGroupName).GetAwaiter().GetResult();
}
/// <summary>
/// Gets all network security groups in a resource group.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<NetworkSecurityGroup>> ListAsync(this INetworkSecurityGroupsOperations operations, string resourceGroupName, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListWithHttpMessagesAsync(resourceGroupName, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Deletes the specified network security group.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='networkSecurityGroupName'>
/// The name of the network security group.
/// </param>
public static void BeginDelete(this INetworkSecurityGroupsOperations operations, string resourceGroupName, string networkSecurityGroupName)
{
operations.BeginDeleteAsync(resourceGroupName, networkSecurityGroupName).GetAwaiter().GetResult();
}
/// <summary>
/// Deletes the specified network security group.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='networkSecurityGroupName'>
/// The name of the network security group.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task BeginDeleteAsync(this INetworkSecurityGroupsOperations operations, string resourceGroupName, string networkSecurityGroupName, CancellationToken cancellationToken = default(CancellationToken))
{
await operations.BeginDeleteWithHttpMessagesAsync(resourceGroupName, networkSecurityGroupName, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Creates or updates a network security group in the specified resource
/// group.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='networkSecurityGroupName'>
/// The name of the network security group.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to the create or update network security group
/// operation.
/// </param>
public static NetworkSecurityGroup BeginCreateOrUpdate(this INetworkSecurityGroupsOperations operations, string resourceGroupName, string networkSecurityGroupName, NetworkSecurityGroup parameters)
{
return operations.BeginCreateOrUpdateAsync(resourceGroupName, networkSecurityGroupName, parameters).GetAwaiter().GetResult();
}
/// <summary>
/// Creates or updates a network security group in the specified resource
/// group.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='networkSecurityGroupName'>
/// The name of the network security group.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to the create or update network security group
/// operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<NetworkSecurityGroup> BeginCreateOrUpdateAsync(this INetworkSecurityGroupsOperations operations, string resourceGroupName, string networkSecurityGroupName, NetworkSecurityGroup parameters, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.BeginCreateOrUpdateWithHttpMessagesAsync(resourceGroupName, networkSecurityGroupName, parameters, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Gets all network security groups in a subscription.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
public static IPage<NetworkSecurityGroup> ListAllNext(this INetworkSecurityGroupsOperations operations, string nextPageLink)
{
return operations.ListAllNextAsync(nextPageLink).GetAwaiter().GetResult();
}
/// <summary>
/// Gets all network security groups in a subscription.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<NetworkSecurityGroup>> ListAllNextAsync(this INetworkSecurityGroupsOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListAllNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Gets all network security groups in a resource group.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
public static IPage<NetworkSecurityGroup> ListNext(this INetworkSecurityGroupsOperations operations, string nextPageLink)
{
return operations.ListNextAsync(nextPageLink).GetAwaiter().GetResult();
}
/// <summary>
/// Gets all network security groups in a resource group.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<NetworkSecurityGroup>> ListNextAsync(this INetworkSecurityGroupsOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
}
}
| |
// 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.Data.Common;
using System.Diagnostics;
namespace System.Data.SqlClient
{
internal class TdsParserSessionPool
{
// NOTE: This is a very simplistic, lightweight pooler. It wasn't
// intended to handle huge number of items, just to keep track
// of the session objects to ensure that they're cleaned up in
// a timely manner, to avoid holding on to an unacceptible
// amount of server-side resources in the event that consumers
// let their data readers be GC'd, instead of explicitly
// closing or disposing of them
private const int MaxInactiveCount = 10; // pick something, preferably small...
private readonly TdsParser _parser; // parser that owns us
private readonly List<TdsParserStateObject> _cache; // collection of all known sessions
private int _cachedCount; // lock-free _cache.Count
private TdsParserStateObject[] _freeStateObjects; // collection of all sessions available for reuse
private int _freeStateObjectCount; // Number of available free sessions
internal TdsParserSessionPool(TdsParser parser)
{
_parser = parser;
_cache = new List<TdsParserStateObject>();
_freeStateObjects = new TdsParserStateObject[MaxInactiveCount];
_freeStateObjectCount = 0;
}
private bool IsDisposed
{
get
{
return (null == _freeStateObjects);
}
}
internal void Deactivate()
{
// When being deactivated, we check all the sessions in the
// cache to make sure they're cleaned up and then we dispose of
// sessions that are past what we want to keep around.
lock (_cache)
{
// NOTE: The PutSession call below may choose to remove the
// session from the cache, which will throw off our
// enumerator. We avoid that by simply indexing backward
// through the array.
for (int i = _cache.Count - 1; i >= 0; i--)
{
TdsParserStateObject session = _cache[i];
if (null != session)
{
if (session.IsOrphaned)
{
// TODO: consider adding a performance counter for the number of sessions we reclaim
PutSession(session);
}
}
}
// TODO: re-enable this assert when the connection isn't doomed.
//Debug.Assert (_cachedCount < MaxInactiveCount, "non-orphaned connection past initial allocation?");
}
}
// This is called from a ThreadAbort - ensure that it can be run from a CER Catch
internal void BestEffortCleanup()
{
for (int i = 0; i < _cache.Count; i++)
{
TdsParserStateObject session = _cache[i];
if (null != session)
{
var sessionHandle = session.Handle;
if (sessionHandle != null)
{
sessionHandle.Dispose();
}
}
}
}
internal void Dispose()
{
lock (_cache)
{
// Dispose free sessions
for (int i = 0; i < _freeStateObjectCount; i++)
{
if (_freeStateObjects[i] != null)
{
_freeStateObjects[i].Dispose();
}
}
_freeStateObjects = null;
_freeStateObjectCount = 0;
// Dispose orphaned sessions
for (int i = 0; i < _cache.Count; i++)
{
if (_cache[i] != null)
{
if (_cache[i].IsOrphaned)
{
_cache[i].Dispose();
}
else
{
// Remove the "initial" callback (this will allow the stateObj to be GC collected if need be)
_cache[i].DecrementPendingCallbacks(false);
}
}
}
_cache.Clear();
_cachedCount = 0;
// Any active sessions will take care of themselves
// (It's too dangerous to dispose them, as this can cause AVs)
}
}
internal TdsParserStateObject GetSession(object owner)
{
TdsParserStateObject session;
lock (_cache)
{
if (IsDisposed)
{
throw ADP.ClosedConnectionError();
}
else if (_freeStateObjectCount > 0)
{
// Free state object - grab it
_freeStateObjectCount--;
session = _freeStateObjects[_freeStateObjectCount];
_freeStateObjects[_freeStateObjectCount] = null;
Debug.Assert(session != null, "There was a null session in the free session list?");
}
else
{
// No free objects, create a new one
session = _parser.CreateSession();
_cache.Add(session);
_cachedCount = _cache.Count;
}
session.Activate(owner);
}
return session;
}
internal void PutSession(TdsParserStateObject session)
{
Debug.Assert(null != session, "null session?");
//Debug.Assert(null != session.Owner, "session without owner?");
bool okToReuse = session.Deactivate();
lock (_cache)
{
if (IsDisposed)
{
// We're diposed - just clean out the session
Debug.Assert(_cachedCount == 0, "SessionPool is disposed, but there are still sessions in the cache?");
session.Dispose();
}
else if ((okToReuse) && (_freeStateObjectCount < MaxInactiveCount))
{
// Session is good to re-use and our cache has space
Debug.Assert(!session._pendingData, "pending data on a pooled session?");
_freeStateObjects[_freeStateObjectCount] = session;
_freeStateObjectCount++;
}
else
{
// Either the session is bad, or we have no cache space - so dispose the session and remove it
bool removed = _cache.Remove(session);
Debug.Assert(removed, "session not in pool?");
_cachedCount = _cache.Count;
session.Dispose();
}
session.RemoveOwner();
}
}
internal int ActiveSessionsCount
{
get
{
return _cachedCount - _freeStateObjectCount;
}
}
}
}
| |
using System;
using System.Threading;
namespace Amib.Threading.Internal
{
public abstract class WorkItemsGroupBase : IWorkItemsGroup
{
#region Private Fields
/// <summary>
/// Contains the name of this instance of SmartThreadPool.
/// Can be changed by the user.
/// </summary>
private string _name = "WorkItemsGroupBase";
public WorkItemsGroupBase()
{
IsIdle = true;
}
#endregion Private Fields
#region IWorkItemsGroup Members
#region Public Methods
/// <summary>
/// Get/Set the name of the SmartThreadPool/WorkItemsGroup instance
/// </summary>
public string Name
{
get { return _name; }
set { _name = value; }
}
#endregion Public Methods
#region Abstract Methods
public abstract event WorkItemsGroupIdleHandler OnIdle;
public abstract int Concurrency { get; set; }
public abstract int WaitingCallbacks { get; }
public abstract WIGStartInfo WIGStartInfo { get; }
public abstract void Cancel(bool abortExecution);
public abstract object[] GetStates();
public abstract void Start();
public abstract bool WaitForIdle(int millisecondsTimeout);
internal abstract void Enqueue(WorkItem workItem);
internal virtual void PreQueueWorkItem()
{
}
#endregion Abstract Methods
#region Common Base Methods
/// <summary>
/// IsIdle is true when there are no work items running or queued.
/// </summary>
public bool IsIdle { get; protected set; }
/// <summary>
/// Cancel all the work items.
/// Same as Cancel(false)
/// </summary>
public virtual void Cancel()
{
Cancel(false);
}
/// <summary>
/// Wait for the SmartThreadPool/WorkItemsGroup to be idle
/// </summary>
public void WaitForIdle()
{
WaitForIdle(Timeout.Infinite);
}
/// <summary>
/// Wait for the SmartThreadPool/WorkItemsGroup to be idle
/// </summary>
public bool WaitForIdle(TimeSpan timeout)
{
return WaitForIdle((int)timeout.TotalMilliseconds);
}
#endregion Common Base Methods
#region QueueWorkItem
/// <summary>
/// Queue a work item
/// </summary>
/// <param name="callback">A callback to execute</param>
/// <returns>Returns a work item result</returns>
public IWorkItemResult QueueWorkItem(WorkItemCallback callback)
{
WorkItem workItem = WorkItemFactory.CreateWorkItem(this, WIGStartInfo, callback);
Enqueue(workItem);
return workItem.GetWorkItemResult();
}
/// <summary>
/// Queue a work item
/// </summary>
/// <param name="callback">A callback to execute</param>
/// <param name="workItemPriority">The priority of the work item</param>
/// <returns>Returns a work item result</returns>
public IWorkItemResult QueueWorkItem(WorkItemCallback callback, WorkItemPriority workItemPriority)
{
PreQueueWorkItem();
WorkItem workItem = WorkItemFactory.CreateWorkItem(this, WIGStartInfo, callback, workItemPriority);
Enqueue(workItem);
return workItem.GetWorkItemResult();
}
/// <summary>
/// Queue a work item
/// </summary>
/// <param name="workItemInfo">Work item info</param>
/// <param name="callback">A callback to execute</param>
/// <returns>Returns a work item result</returns>
public IWorkItemResult QueueWorkItem(WorkItemInfo workItemInfo, WorkItemCallback callback)
{
PreQueueWorkItem();
WorkItem workItem = WorkItemFactory.CreateWorkItem(this, WIGStartInfo, workItemInfo, callback);
Enqueue(workItem);
return workItem.GetWorkItemResult();
}
/// <summary>
/// Queue a work item
/// </summary>
/// <param name="callback">A callback to execute</param>
/// <param name="state">
/// The context object of the work item. Used for passing arguments to the work item.
/// </param>
/// <returns>Returns a work item result</returns>
public IWorkItemResult QueueWorkItem(WorkItemCallback callback, object state)
{
WorkItem workItem = WorkItemFactory.CreateWorkItem(this, WIGStartInfo, callback, state);
Enqueue(workItem);
return workItem.GetWorkItemResult();
}
/// <summary>
/// Queue a work item
/// </summary>
/// <param name="callback">A callback to execute</param>
/// <param name="state">
/// The context object of the work item. Used for passing arguments to the work item.
/// </param>
/// <param name="workItemPriority">The work item priority</param>
/// <returns>Returns a work item result</returns>
public IWorkItemResult QueueWorkItem(WorkItemCallback callback, object state, WorkItemPriority workItemPriority)
{
PreQueueWorkItem();
WorkItem workItem = WorkItemFactory.CreateWorkItem(this, WIGStartInfo, callback, state, workItemPriority);
Enqueue(workItem);
return workItem.GetWorkItemResult();
}
/// <summary>
/// Queue a work item
/// </summary>
/// <param name="workItemInfo">Work item information</param>
/// <param name="callback">A callback to execute</param>
/// <param name="state">
/// The context object of the work item. Used for passing arguments to the work item.
/// </param>
/// <returns>Returns a work item result</returns>
public IWorkItemResult QueueWorkItem(WorkItemInfo workItemInfo, WorkItemCallback callback, object state)
{
PreQueueWorkItem();
WorkItem workItem = WorkItemFactory.CreateWorkItem(this, WIGStartInfo, workItemInfo, callback, state);
Enqueue(workItem);
return workItem.GetWorkItemResult();
}
/// <summary>
/// Queue a work item
/// </summary>
/// <param name="callback">A callback to execute</param>
/// <param name="state">
/// The context object of the work item. Used for passing arguments to the work item.
/// </param>
/// <param name="postExecuteWorkItemCallback">
/// A delegate to call after the callback completion
/// </param>
/// <returns>Returns a work item result</returns>
public IWorkItemResult QueueWorkItem(
WorkItemCallback callback,
object state,
PostExecuteWorkItemCallback postExecuteWorkItemCallback)
{
PreQueueWorkItem();
WorkItem workItem = WorkItemFactory.CreateWorkItem(this, WIGStartInfo, callback, state, postExecuteWorkItemCallback);
Enqueue(workItem);
return workItem.GetWorkItemResult();
}
/// <summary>
/// Queue a work item
/// </summary>
/// <param name="callback">A callback to execute</param>
/// <param name="state">
/// The context object of the work item. Used for passing arguments to the work item.
/// </param>
/// <param name="postExecuteWorkItemCallback">
/// A delegate to call after the callback completion
/// </param>
/// <param name="workItemPriority">The work item priority</param>
/// <returns>Returns a work item result</returns>
public IWorkItemResult QueueWorkItem(
WorkItemCallback callback,
object state,
PostExecuteWorkItemCallback postExecuteWorkItemCallback,
WorkItemPriority workItemPriority)
{
PreQueueWorkItem();
WorkItem workItem = WorkItemFactory.CreateWorkItem(this, WIGStartInfo, callback, state, postExecuteWorkItemCallback, workItemPriority);
Enqueue(workItem);
return workItem.GetWorkItemResult();
}
/// <summary>
/// Queue a work item
/// </summary>
/// <param name="callback">A callback to execute</param>
/// <param name="state">
/// The context object of the work item. Used for passing arguments to the work item.
/// </param>
/// <param name="postExecuteWorkItemCallback">
/// A delegate to call after the callback completion
/// </param>
/// <param name="callToPostExecute">Indicates on which cases to call to the post execute callback</param>
/// <returns>Returns a work item result</returns>
public IWorkItemResult QueueWorkItem(
WorkItemCallback callback,
object state,
PostExecuteWorkItemCallback postExecuteWorkItemCallback,
CallToPostExecute callToPostExecute)
{
PreQueueWorkItem();
WorkItem workItem = WorkItemFactory.CreateWorkItem(this, WIGStartInfo, callback, state, postExecuteWorkItemCallback, callToPostExecute);
Enqueue(workItem);
return workItem.GetWorkItemResult();
}
/// <summary>
/// Queue a work item
/// </summary>
/// <param name="callback">A callback to execute</param>
/// <param name="state">
/// The context object of the work item. Used for passing arguments to the work item.
/// </param>
/// <param name="postExecuteWorkItemCallback">
/// A delegate to call after the callback completion
/// </param>
/// <param name="callToPostExecute">Indicates on which cases to call to the post execute callback</param>
/// <param name="workItemPriority">The work item priority</param>
/// <returns>Returns a work item result</returns>
public IWorkItemResult QueueWorkItem(
WorkItemCallback callback,
object state,
PostExecuteWorkItemCallback postExecuteWorkItemCallback,
CallToPostExecute callToPostExecute,
WorkItemPriority workItemPriority)
{
PreQueueWorkItem();
WorkItem workItem = WorkItemFactory.CreateWorkItem(this, WIGStartInfo, callback, state, postExecuteWorkItemCallback, callToPostExecute, workItemPriority);
Enqueue(workItem);
return workItem.GetWorkItemResult();
}
#endregion QueueWorkItem
#region QueueWorkItem(Action<...>)
public IWorkItemResult QueueWorkItem(Action action)
{
return QueueWorkItem(action, SmartThreadPool.DefaultWorkItemPriority);
}
public IWorkItemResult QueueWorkItem(Action action, WorkItemPriority priority)
{
PreQueueWorkItem();
WorkItem workItem = WorkItemFactory.CreateWorkItem(
this,
WIGStartInfo,
delegate
{
action.Invoke();
return null;
}, priority);
Enqueue(workItem);
return workItem.GetWorkItemResult();
}
public IWorkItemResult QueueWorkItem<T>(Action<T> action, T arg)
{
return QueueWorkItem<T>(action, arg, SmartThreadPool.DefaultWorkItemPriority);
}
public IWorkItemResult QueueWorkItem<T>(Action<T> action, T arg, WorkItemPriority priority)
{
PreQueueWorkItem();
WorkItem workItem = WorkItemFactory.CreateWorkItem(
this,
WIGStartInfo,
state =>
{
action.Invoke(arg);
return null;
},
WIGStartInfo.FillStateWithArgs ? new object[] { arg } : null, priority);
Enqueue(workItem);
return workItem.GetWorkItemResult();
}
public IWorkItemResult QueueWorkItem<T1, T2>(Action<T1, T2> action, T1 arg1, T2 arg2)
{
return QueueWorkItem<T1, T2>(action, arg1, arg2, SmartThreadPool.DefaultWorkItemPriority);
}
public IWorkItemResult QueueWorkItem<T1, T2>(Action<T1, T2> action, T1 arg1, T2 arg2, WorkItemPriority priority)
{
PreQueueWorkItem();
WorkItem workItem = WorkItemFactory.CreateWorkItem(
this,
WIGStartInfo,
state =>
{
action.Invoke(arg1, arg2);
return null;
},
WIGStartInfo.FillStateWithArgs ? new object[] { arg1, arg2 } : null, priority);
Enqueue(workItem);
return workItem.GetWorkItemResult();
}
public IWorkItemResult QueueWorkItem<T1, T2, T3>(Action<T1, T2, T3> action, T1 arg1, T2 arg2, T3 arg3)
{
return QueueWorkItem<T1, T2, T3>(action, arg1, arg2, arg3, SmartThreadPool.DefaultWorkItemPriority);
;
}
public IWorkItemResult QueueWorkItem<T1, T2, T3>(Action<T1, T2, T3> action, T1 arg1, T2 arg2, T3 arg3, WorkItemPriority priority)
{
PreQueueWorkItem();
WorkItem workItem = WorkItemFactory.CreateWorkItem(
this,
WIGStartInfo,
state =>
{
action.Invoke(arg1, arg2, arg3);
return null;
},
WIGStartInfo.FillStateWithArgs ? new object[] { arg1, arg2, arg3 } : null, priority);
Enqueue(workItem);
return workItem.GetWorkItemResult();
}
public IWorkItemResult QueueWorkItem<T1, T2, T3, T4>(
Action<T1, T2, T3, T4> action, T1 arg1, T2 arg2, T3 arg3, T4 arg4)
{
return QueueWorkItem<T1, T2, T3, T4>(action, arg1, arg2, arg3, arg4,
SmartThreadPool.DefaultWorkItemPriority);
}
public IWorkItemResult QueueWorkItem<T1, T2, T3, T4>(
Action<T1, T2, T3, T4> action, T1 arg1, T2 arg2, T3 arg3, T4 arg4, WorkItemPriority priority)
{
PreQueueWorkItem();
WorkItem workItem = WorkItemFactory.CreateWorkItem(
this,
WIGStartInfo,
state =>
{
action.Invoke(arg1, arg2, arg3, arg4);
return null;
},
WIGStartInfo.FillStateWithArgs ? new object[] { arg1, arg2, arg3, arg4 } : null, priority);
Enqueue(workItem);
return workItem.GetWorkItemResult();
}
#endregion QueueWorkItem(Action<...>)
#region QueueWorkItem(Func<...>)
public IWorkItemResult<TResult> QueueWorkItem<TResult>(Func<TResult> func)
{
PreQueueWorkItem();
WorkItem workItem = WorkItemFactory.CreateWorkItem(
this,
WIGStartInfo,
state =>
{
return func.Invoke();
});
Enqueue(workItem);
return new WorkItemResultTWrapper<TResult>(workItem.GetWorkItemResult());
}
public IWorkItemResult<TResult> QueueWorkItem<T, TResult>(Func<T, TResult> func, T arg)
{
PreQueueWorkItem();
WorkItem workItem = WorkItemFactory.CreateWorkItem(
this,
WIGStartInfo,
state =>
{
return func.Invoke(arg);
},
WIGStartInfo.FillStateWithArgs ? new object[] { arg } : null);
Enqueue(workItem);
return new WorkItemResultTWrapper<TResult>(workItem.GetWorkItemResult());
}
public IWorkItemResult<TResult> QueueWorkItem<T1, T2, TResult>(Func<T1, T2, TResult> func, T1 arg1, T2 arg2)
{
PreQueueWorkItem();
WorkItem workItem = WorkItemFactory.CreateWorkItem(
this,
WIGStartInfo,
state =>
{
return func.Invoke(arg1, arg2);
},
WIGStartInfo.FillStateWithArgs ? new object[] { arg1, arg2 } : null);
Enqueue(workItem);
return new WorkItemResultTWrapper<TResult>(workItem.GetWorkItemResult());
}
public IWorkItemResult<TResult> QueueWorkItem<T1, T2, T3, TResult>(
Func<T1, T2, T3, TResult> func, T1 arg1, T2 arg2, T3 arg3)
{
PreQueueWorkItem();
WorkItem workItem = WorkItemFactory.CreateWorkItem(
this,
WIGStartInfo,
state =>
{
return func.Invoke(arg1, arg2, arg3);
},
WIGStartInfo.FillStateWithArgs ? new object[] { arg1, arg2, arg3 } : null);
Enqueue(workItem);
return new WorkItemResultTWrapper<TResult>(workItem.GetWorkItemResult());
}
public IWorkItemResult<TResult> QueueWorkItem<T1, T2, T3, T4, TResult>(
Func<T1, T2, T3, T4, TResult> func, T1 arg1, T2 arg2, T3 arg3, T4 arg4)
{
PreQueueWorkItem();
WorkItem workItem = WorkItemFactory.CreateWorkItem(
this,
WIGStartInfo,
state =>
{
return func.Invoke(arg1, arg2, arg3, arg4);
},
WIGStartInfo.FillStateWithArgs ? new object[] { arg1, arg2, arg3, arg4 } : null);
Enqueue(workItem);
return new WorkItemResultTWrapper<TResult>(workItem.GetWorkItemResult());
}
#endregion QueueWorkItem(Func<...>)
#endregion IWorkItemsGroup Members
}
}
| |
//
// Copyright (c) 2004-2016 Jaroslaw Kowalski <jaak@jkowalski.net>, 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.Layouts
{
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using NLog.Layouts;
using Xunit;
public class CsvLayoutTests : NLogTestBase
{
#if !SILVERLIGHT
[Fact]
public void EndToEndTest()
{
try
{
LogManager.Configuration = CreateConfigurationFromString(@"
<nlog>
<targets>
<target name='f' type='File' fileName='CSVLayoutEndToEnd1.txt'>
<layout type='CSVLayout'>
<column name='level' layout='${level}' />
<column name='message' layout='${message}' />
<column name='counter' layout='${counter}' />
<delimiter>Comma</delimiter>
</layout>
</target>
</targets>
<rules>
<logger name='*' minlevel='Debug' writeTo='f' />
</rules>
</nlog>");
ILogger logger = LogManager.GetLogger("A");
logger.Debug("msg");
logger.Info("msg2");
logger.Warn("Message with, a comma");
using (StreamReader sr = File.OpenText("CSVLayoutEndToEnd1.txt"))
{
Assert.Equal("level,message,counter", sr.ReadLine());
Assert.Equal("Debug,msg,1", sr.ReadLine());
Assert.Equal("Info,msg2,2", sr.ReadLine());
Assert.Equal("Warn,\"Message with, a comma\",3", sr.ReadLine());
}
}
finally
{
if (File.Exists("CSVLayoutEndToEnd1.txt"))
{
File.Delete("CSVLayoutEndToEnd1.txt");
}
}
}
[Fact]
public void NoHeadersTest()
{
try
{
LogManager.Configuration = CreateConfigurationFromString(@"
<nlog>
<targets>
<target name='f' type='File' fileName='CSVLayoutEndToEnd2.txt'>
<layout type='CSVLayout' withHeader='false'>
<delimiter>Comma</delimiter>
<column name='level' layout='${level}' />
<column name='message' layout='${message}' />
<column name='counter' layout='${counter}' />
</layout>
</target>
</targets>
<rules>
<logger name='*' minlevel='Debug' writeTo='f' />
</rules>
</nlog>");
ILogger logger = LogManager.GetLogger("A");
logger.Debug("msg");
logger.Info("msg2");
logger.Warn("Message with, a comma");
using (StreamReader sr = File.OpenText("CSVLayoutEndToEnd2.txt"))
{
Assert.Equal("Debug,msg,1", sr.ReadLine());
Assert.Equal("Info,msg2,2", sr.ReadLine());
Assert.Equal("Warn,\"Message with, a comma\",3", sr.ReadLine());
}
}
finally
{
if (File.Exists("CSVLayoutEndToEnd2.txt"))
{
File.Delete("CSVLayoutEndToEnd2.txt");
}
}
}
#endif
[Fact]
public void CsvLayoutRenderingNoQuoting()
{
var delimiters = new Dictionary<CsvColumnDelimiterMode, string>
{
{ CsvColumnDelimiterMode.Auto, CultureInfo.CurrentCulture.TextInfo.ListSeparator },
{ CsvColumnDelimiterMode.Comma, "," },
{ CsvColumnDelimiterMode.Semicolon, ";" },
{ CsvColumnDelimiterMode.Space, " " },
{ CsvColumnDelimiterMode.Tab, "\t" },
{ CsvColumnDelimiterMode.Pipe, "|" },
{ CsvColumnDelimiterMode.Custom, "zzz" },
};
foreach (var delim in delimiters)
{
var csvLayout = new CsvLayout()
{
Quoting = CsvQuotingMode.Nothing,
Columns =
{
new CsvColumn("date", "${longdate}"),
new CsvColumn("level", "${level}"),
new CsvColumn("message;text", "${message}"),
},
Delimiter = delim.Key,
CustomColumnDelimiter = "zzz",
};
var ev = new LogEventInfo();
ev.TimeStamp = new DateTime(2010, 01, 01, 12, 34, 56);
ev.Level = LogLevel.Info;
ev.Message = "hello, world";
string sep = delim.Value;
Assert.Equal("2010-01-01 12:34:56.0000" + sep + "Info" + sep + "hello, world", csvLayout.Render(ev));
Assert.Equal("date" + sep + "level" + sep + "message;text", csvLayout.Header.Render(ev));
}
}
[Fact]
public void CsvLayoutRenderingFullQuoting()
{
var delimiters = new Dictionary<CsvColumnDelimiterMode, string>
{
{ CsvColumnDelimiterMode.Auto, CultureInfo.CurrentCulture.TextInfo.ListSeparator },
{ CsvColumnDelimiterMode.Comma, "," },
{ CsvColumnDelimiterMode.Semicolon, ";" },
{ CsvColumnDelimiterMode.Space, " " },
{ CsvColumnDelimiterMode.Tab, "\t" },
{ CsvColumnDelimiterMode.Pipe, "|" },
{ CsvColumnDelimiterMode.Custom, "zzz" },
};
foreach (var delim in delimiters)
{
var csvLayout = new CsvLayout()
{
Quoting = CsvQuotingMode.All,
Columns =
{
new CsvColumn("date", "${longdate}"),
new CsvColumn("level", "${level}"),
new CsvColumn("message;text", "${message}"),
},
QuoteChar = "'",
Delimiter = delim.Key,
CustomColumnDelimiter = "zzz",
};
var ev = new LogEventInfo();
ev.TimeStamp = new DateTime(2010, 01, 01, 12, 34, 56);
ev.Level = LogLevel.Info;
ev.Message = "hello, world";
string sep = delim.Value;
Assert.Equal("'2010-01-01 12:34:56.0000'" + sep + "'Info'" + sep + "'hello, world'", csvLayout.Render(ev));
Assert.Equal("'date'" + sep + "'level'" + sep + "'message;text'", csvLayout.Header.Render(ev));
}
}
[Fact]
public void CsvLayoutRenderingAutoQuoting()
{
var csvLayout = new CsvLayout()
{
Quoting = CsvQuotingMode.Auto,
Columns =
{
new CsvColumn("date", "${longdate}"),
new CsvColumn("level", "${level}"),
new CsvColumn("message;text", "${message}"),
},
QuoteChar = "'",
Delimiter = CsvColumnDelimiterMode.Semicolon,
};
// no quoting
Assert.Equal(
"2010-01-01 12:34:56.0000;Info;hello, world",
csvLayout.Render(new LogEventInfo
{
TimeStamp = new DateTime(2010, 01, 01, 12, 34, 56),
Level = LogLevel.Info,
Message = "hello, world"
}));
// multi-line string - requires quoting
Assert.Equal(
"2010-01-01 12:34:56.0000;Info;'hello\rworld'",
csvLayout.Render(new LogEventInfo
{
TimeStamp = new DateTime(2010, 01, 01, 12, 34, 56),
Level = LogLevel.Info,
Message = "hello\rworld"
}));
// multi-line string - requires quoting
Assert.Equal(
"2010-01-01 12:34:56.0000;Info;'hello\nworld'",
csvLayout.Render(new LogEventInfo
{
TimeStamp = new DateTime(2010, 01, 01, 12, 34, 56),
Level = LogLevel.Info,
Message = "hello\nworld"
}));
// quote character used in string, will be quoted and doubled
Assert.Equal(
"2010-01-01 12:34:56.0000;Info;'hello''world'",
csvLayout.Render(new LogEventInfo
{
TimeStamp = new DateTime(2010, 01, 01, 12, 34, 56),
Level = LogLevel.Info,
Message = "hello'world"
}));
Assert.Equal("date;level;'message;text'", csvLayout.Header.Render(LogEventInfo.CreateNullEvent()));
}
[Fact]
public void CsvLayoutCachingTest()
{
var csvLayout = new CsvLayout()
{
Quoting = CsvQuotingMode.Auto,
Columns =
{
new CsvColumn("date", "${longdate}"),
new CsvColumn("level", "${level}"),
new CsvColumn("message", "${message}"),
},
QuoteChar = "'",
Delimiter = CsvColumnDelimiterMode.Semicolon,
};
var e1 = new LogEventInfo
{
TimeStamp = new DateTime(2010, 01, 01, 12, 34, 56),
Level = LogLevel.Info,
Message = "hello, world"
};
var e2 = new LogEventInfo
{
TimeStamp = new DateTime(2010, 01, 01, 12, 34, 57),
Level = LogLevel.Info,
Message = "hello, world"
};
var r11 = csvLayout.Render(e1);
var r12 = csvLayout.Render(e1);
var r21 = csvLayout.Render(e2);
var r22 = csvLayout.Render(e2);
var h11 = csvLayout.Header.Render(e1);
var h12 = csvLayout.Header.Render(e1);
var h21 = csvLayout.Header.Render(e2);
var h22 = csvLayout.Header.Render(e2);
Assert.Same(r11, r12);
Assert.Same(r21, r22);
Assert.NotSame(r11, r21);
Assert.NotSame(r12, r22);
Assert.Same(h11, h12);
Assert.Same(h21, h22);
Assert.NotSame(h11, h21);
Assert.NotSame(h12, h22);
}
}
}
| |
using Core.IO;
using System;
using System.Diagnostics;
namespace Core
{
public partial class Vdbe
{
#region IncrBlob
#if !OMIT_INCRBLOB
class Incrblob : Blob
{
public int Flags; // Copy of "flags" passed to sqlite3_blob_open()
public int Bytes; // Size of open blob, in bytes
public uint Offset; // Byte offset of blob in cursor data
public int Col; // Table column this handle is open on
public Btree.BtCursor Cursor; // Cursor pointing at blob row
public Vdbe Stmt; // Statement holding cursor open
public Context Ctx; // The associated database
}
static RC BlobSeekToRow(Incrblob p, long row, out string errOut)
{
string err = null; // Error message
Vdbe v = p.Stmt;
// Set the value of the SQL statements only variable to integer iRow. This is done directly instead of using sqlite3_bind_int64() to avoid
// triggering asserts related to mutexes.
Debug.Assert((v.Vars[0].Flags & MEM.Int) != 0);
v.Vars[0].u.I = row;
RC rc = v.Step();
if (rc == RC.ROW)
{
uint type = v.Cursors[0].Types[p.Col];
if (type < 12)
{
err = C._mtagprintf(p.Ctx, "cannot open value of type %s", type == 0 ? "null" : type == 7 ? "real" : "integer");
rc = RC.ERROR;
Vdbe.Finalize(v);
p.Stmt = null;
}
else
{
p.Offset = v.Cursors[0].Offsets[p.Col];
p.Bytes = SerialTypeLen(type);
p.Cursor = v.Cursors[0].Cursor;
p.Cursor.EnterCursor();
Btree.CacheOverflow(p.Cursor);
p.Cursor.LeaveCursor();
}
}
if (rc == RC.ROW)
rc = RC.OK;
else if (p.Stmt != null)
{
rc = Vdbe.Finalize(p.Stmt);
p.Stmt = null;
if (rc == RC.OK)
{
err = C._mtagprintf(p.Ctx, "no such rowid: %lld", row);
rc = RC.ERROR;
}
else
err = C._mtagprintf(p.Ctx, "%s", DataEx.Errmsg(p.Ctx));
}
Debug.Assert(rc != RC.OK || err == null);
Debug.Assert(rc != RC.ROW && rc != RC.DONE);
errOut = err;
return rc;
}
static const Vdbe.VdbeOpList[] _openBlob =
{
new Vdbe.VdbeOpList(OP.Transaction, 0, 0, 0), // 0: Start a transaction
new Vdbe.VdbeOpList(OP.VerifyCookie, 0, 0, 0), // 1: Check the schema cookie
new Vdbe.VdbeOpList(OP.TableLock, 0, 0, 0), // 2: Acquire a read or write lock
// One of the following two instructions is replaced by an OP_Noop.
new Vdbe.VdbeOpList(OP.OpenRead, 0, 0, 0), // 3: Open cursor 0 for reading
new Vdbe.VdbeOpList(OP.OpenWrite, 0, 0, 0), // 4: Open cursor 0 for read/write
new Vdbe.VdbeOpList(OP.Variable, 1, 1, 1), // 5: Push the rowid to the stack
new Vdbe.VdbeOpList(OP.NotExists, 0, 9, 1), // 6: Seek the cursor
new Vdbe.VdbeOpList(OP.Column, 0, 0, 1), // 7
new Vdbe.VdbeOpList(OP.ResultRow, 1, 0, 0), // 8
new Vdbe.VdbeOpList(OP.Close, 0, 0, 0), // 9
new Vdbe.VdbeOpList(OP.Halt, 0, 0, 0), // 10
};
public RC Blob_Open(Context ctx, string dbName, string tableName, string columnName, long row, int flags, ref Blob blobOut)
{
// This VDBE program seeks a btree cursor to the identified db/table/row entry. The reason for using a vdbe program instead
// of writing code to use the b-tree layer directly is that the vdbe program will take advantage of the various transaction,
// locking and error handling infrastructure built into the vdbe.
//
// After seeking the cursor, the vdbe executes an OP_ResultRow. Code external to the Vdbe then "borrows" the b-tree cursor and
// uses it to implement the blob_read(), blob_write() and blob_bytes() functions.
//
// The sqlite3_blob_close() function finalizes the vdbe program, which closes the b-tree cursor and (possibly) commits the transaction.
RC rc = RC.OK;
flags = (flags != 0 ? 1 : 0);
blobOut = null;
MutexEx.Enter(ctx.Mutex);
Incrblob blob = new Incrblob();
if (blob == null) goto blob_open_out;
Parse parse = new Parse();
if (parse == null) goto blob_open_out;
string err = null;
int attempts = 0;
do
{
parse._memset();
parse.Ctx = ctx;
C._tagfree(ctx, ref err);
err = null;
Btree.EnterAll(ctx);
Table table = sqlite3LocateTable(parse, 0, tableName, dbName);
if (table != null && E.IsVirtual(table))
{
table = null;
parse.ErrorMsg("cannot open virtual table: %s", tableName);
}
#if !OMIT_VIEW
if (table != null && table.Select != null)
{
table = null;
parse.ErrorMsg("cannot open view: %s", tableName);
}
#endif
if (table == null)
{
if (parse.ErrMsg != null)
{
C._tagfree(ctx, ref err);
err = parse.ErrMsg;
parse.ErrMsg = null;
}
rc = RC.ERROR;
Btree.LeaveAll(ctx);
goto blob_open_out;
}
// Now search table for the exact column.
int col; // Index of zColumn in row-record
for (col = 0; col < table.Cols.length; col++)
if (string.Equals(table.Cols[col].Name, columnName))
break;
if (col == table.Cols.length)
{
C._tagfree(ctx, ref err);
err = C._mtagprintf(ctx, "no such column: \"%s\"", columnName);
rc = RC.ERROR;
Btree.LeaveAll(ctx);
goto blob_open_out;
}
// If the value is being opened for writing, check that the column is not indexed, and that it is not part of a foreign key.
// It is against the rules to open a column to which either of these descriptions applies for writing.
if (flags != 0)
{
string fault = null;
#if !OMIT_FOREIGN_KEY
if ((ctx.Flags & BContext.FLAG.ForeignKeys) != 0)
{
// Check that the column is not part of an FK child key definition. It is not necessary to check if it is part of a parent key, as parent
// key columns must be indexed. The check below will pick up this case.
for (FKey fkey = table.FKeys; fkey != null; fkey = fkey.NextFrom)
for (int j = 0; j < fkey.Cols.length; j++)
if (fkey.Cols[j].From == col)
fault = "foreign key";
}
#endif
for (Index index = table.Index; index != null; index = index.Next)
for (int j = 0; j < index.Columns.length; j++)
if (index.Columns[j] == col)
fault = "indexed";
if (fault != null)
{
C._tagfree(ctx, ref err);
err = C._mtagprintf(ctx, "cannot open %s column for writing", fault);
rc = RC.ERROR;
Btree.LeaveAll(ctx);
goto blob_open_out;
}
}
blob.Stmt = Vdbe.Create(ctx);
Debug.Assert(blob.Stmt != null || ctx.MallocFailed);
if (blob.Stmt != null)
{
Vdbe v = blob.Stmt;
int db = sqlite3SchemaToIndex(ctx, table.Schema);
v.AddOpList(_openBlob.Length, _openBlob);
// Configure the OP_Transaction
v.ChangeP1(0, db);
v.ChangeP2(0, flags);
// Configure the OP_VerifyCookie
v.ChangeP1(1, db);
v.ChangeP2(1, table.Schema.SchemaCookie);
v.ChangeP3(1, table.Schema.Generation);
// Make sure a mutex is held on the table to be accessed
v.UsesBtree(db);
// Configure the OP_TableLock instruction
#if OMIT_SHARED_CACHE
v.ChangeToNoop(2);
#else
v.ChangeP1(2, db);
v.ChangeP2(2, table.Id);
v.ChangeP3(2, flags);
v.ChangeP4(2, table.Name, Vdbe.P4T.TRANSIENT);
#endif
// Remove either the OP_OpenWrite or OpenRead. Set the P2 parameter of the other to table->tnum.
v.ChangeToNoop(4 - flags);
v.ChangeP2(3 + flags, table.Id);
v.ChangeP3(3 + flags, db);
// Configure the number of columns. Configure the cursor to think that the table has one more column than it really
// does. An OP_Column to retrieve this imaginary column will always return an SQL NULL. This is useful because it means
// we can invoke OP_Column to fill in the vdbe cursors type and offset cache without causing any IO.
v.ChangeP4(3 + flags, table.Cols.length + 1, Vdbe.P4T.INT32);
v.ChangeP2(7, table.Cols.length);
if (!ctx.MallocFailed)
{
parse.Vars.length = 1;
parse.Mems = 1;
parse.Tabs = 1;
v.MakeReady(parse);
}
}
blob.Flags = flags;
blob.Col = col;
blob.Ctx = ctx;
Btree.LeaveAll(ctx);
if (ctx.MallocFailed)
goto blob_open_out;
Vdbe.Bind_Int64(blob.Stmt, 1, row);
rc = BlobSeekToRow(blob, row, out err);
} while ((++attempts) < 5 && rc == RC.SCHEMA);
blob_open_out:
if (rc == RC.OK && !ctx.MallocFailed)
blobOut = (Blob)blob;
else
{
if (blob != null && blob.Stmt != null) Vdbe.Finalize(blob.Stmt);
C._tagfree(ctx, ref blob);
}
sqlite3Error(ctx, rc, (err != null ? "%s" : null), err);
C._tagfree(ctx, ref err);
C._scratchfree(ctx, ref parse);
rc = SysEx.ApiExit(ctx, rc);
MutexEx.Leave(ctx.Mutex);
return rc;
}
public RC Blob_Close(Blob blob)
{
Incrblob p = (Incrblob)blob;
if (p != null)
{
Context ctx = p.Ctx;
MutexEx.Enter(ctx.Mutex);
RC rc = Finalize(p.Stmt);
C._tagfree(ctx, ref p);
MutexEx.Free(ctx.Mutex);
return rc;
}
return RC.OK;
}
static RC BlobReadWrite(Blob blob, string z, uint n, uint offset, Func<Btree.BtCursor, uint, uint, string, RC> call)
{
Incrblob p = (Incrblob)blob;
if (p == null) return SysEx.MISUSE_BKPT();
Context ctx = p.Ctx;
MutexEx.Enter(ctx.Mutex);
Vdbe v = (Vdbe)p.Stmt;
RC rc;
if (n < 0 || offset < 0 || (offset + n) > p.Bytes)
{
rc = RC.ERROR; // Request is out of range. Return a transient error.
sqlite3Error(ctx, RC.ERROR, 0);
}
else if (v == null)
rc = RC.ABORT; // If there is no statement handle, then the blob-handle has already been invalidated. Return SQLITE_ABORT in this case.
else
{
Debug.Assert(ctx == v.Ctx);
p.Cursor.EnterCursor();
rc = call(p.Cursor, offset + p.Offset, n, z); // Call either BtreeData() or BtreePutData(). If SQLITE_ABORT is returned, clean-up the statement handle.
p.Cursor.LeaveCursor();
if (rc == RC.ABORT)
{
Finalize(v);
p.Stmt = null;
}
else
{
ctx.ErrCode = rc;
v.RC_ = rc;
}
}
rc = SysEx.ApiExit(ctx, rc);
MutexEx.Leave(ctx.Mutex);
return rc;
}
public int Blob_Read(Blob blob, object z, int n, int offset)
{
return BlobReadWrite(blob, z, n, offset, Btree.Data);
}
public int Blob_Write(Blob blob, string z, int n, int offset)
{
return BlobReadWrite(blob, z, n, offset, Btree.PutData);
}
public int Blob_Bytes(Blob blob)
{
Incrblob p = (Incrblob)blob;
return (p != null ? p.Bytes : 0);
}
#endif
#endregion
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
namespace Microsoft.Build.BuildEngine
{
public partial class BuildItem
{
public BuildItem(string itemName, Microsoft.Build.Framework.ITaskItem taskItem) { }
public BuildItem(string itemName, string itemInclude) { }
public string Condition { get { throw null; } set { } }
public int CustomMetadataCount { get { throw null; } }
public System.Collections.ICollection CustomMetadataNames { get { throw null; } }
public string Exclude { get { throw null; } set { } }
public string FinalItemSpec { get { throw null; } }
public string Include { get { throw null; } set { } }
public bool IsImported { get { throw null; } }
public int MetadataCount { get { throw null; } }
public System.Collections.ICollection MetadataNames { get { throw null; } }
public string Name { get { throw null; } set { } }
public Microsoft.Build.BuildEngine.BuildItem Clone() { throw null; }
public void CopyCustomMetadataTo(Microsoft.Build.BuildEngine.BuildItem destinationItem) { }
public string GetEvaluatedMetadata(string metadataName) { throw null; }
public string GetMetadata(string metadataName) { throw null; }
public bool HasMetadata(string metadataName) { throw null; }
public void RemoveMetadata(string metadataName) { }
public void SetMetadata(string metadataName, string metadataValue) { }
public void SetMetadata(string metadataName, string metadataValue, bool treatMetadataValueAsLiteral) { }
}
public partial class BuildItemGroup : System.Collections.IEnumerable
{
public BuildItemGroup() { }
public string Condition { get { throw null; } set { } }
public int Count { get { throw null; } }
public bool IsImported { get { throw null; } }
public Microsoft.Build.BuildEngine.BuildItem this[int index] { get { throw null; } }
public Microsoft.Build.BuildEngine.BuildItem AddNewItem(string itemName, string itemInclude) { throw null; }
public Microsoft.Build.BuildEngine.BuildItem AddNewItem(string itemName, string itemInclude, bool treatItemIncludeAsLiteral) { throw null; }
public void Clear() { }
public Microsoft.Build.BuildEngine.BuildItemGroup Clone(bool deepClone) { throw null; }
public System.Collections.IEnumerator GetEnumerator() { throw null; }
public void RemoveItem(Microsoft.Build.BuildEngine.BuildItem itemToRemove) { }
public void RemoveItemAt(int index) { }
public Microsoft.Build.BuildEngine.BuildItem[] ToArray() { throw null; }
}
public partial class BuildItemGroupCollection : System.Collections.ICollection, System.Collections.IEnumerable
{
internal BuildItemGroupCollection() { }
public int Count { get { throw null; } }
public bool IsSynchronized { get { throw null; } }
public object SyncRoot { get { throw null; } }
public void CopyTo(System.Array array, int index) { }
public System.Collections.IEnumerator GetEnumerator() { throw null; }
}
public partial class BuildProperty
{
public BuildProperty(string propertyName, string propertyValue) { }
public string Condition { get { throw null; } set { } }
public string FinalValue { get { throw null; } }
public bool IsImported { get { throw null; } }
public string Name { get { throw null; } }
public string Value { get { throw null; } set { } }
public Microsoft.Build.BuildEngine.BuildProperty Clone(bool deepClone) { throw null; }
public static explicit operator string (Microsoft.Build.BuildEngine.BuildProperty propertyToCast) { throw null; }
public override string ToString() { throw null; }
}
public partial class BuildPropertyGroup : System.Collections.IEnumerable
{
public BuildPropertyGroup() { }
public BuildPropertyGroup(Microsoft.Build.BuildEngine.Project parentProject) { }
public string Condition { get { throw null; } set { } }
public int Count { get { throw null; } }
public bool IsImported { get { throw null; } }
public Microsoft.Build.BuildEngine.BuildProperty this[string propertyName] { get { throw null; } set { } }
public Microsoft.Build.BuildEngine.BuildProperty AddNewProperty(string propertyName, string propertyValue) { throw null; }
public Microsoft.Build.BuildEngine.BuildProperty AddNewProperty(string propertyName, string propertyValue, bool treatPropertyValueAsLiteral) { throw null; }
public void Clear() { }
public Microsoft.Build.BuildEngine.BuildPropertyGroup Clone(bool deepClone) { throw null; }
public System.Collections.IEnumerator GetEnumerator() { throw null; }
public void RemoveProperty(Microsoft.Build.BuildEngine.BuildProperty property) { }
public void RemoveProperty(string propertyName) { }
public void SetImportedPropertyGroupCondition(string condition) { }
public void SetProperty(string propertyName, string propertyValue) { }
public void SetProperty(string propertyName, string propertyValue, bool treatPropertyValueAsLiteral) { }
}
public partial class BuildPropertyGroupCollection : System.Collections.ICollection, System.Collections.IEnumerable
{
internal BuildPropertyGroupCollection() { }
public int Count { get { throw null; } }
public bool IsSynchronized { get { throw null; } }
public object SyncRoot { get { throw null; } }
public void CopyTo(System.Array array, int index) { }
public System.Collections.IEnumerator GetEnumerator() { throw null; }
}
[System.FlagsAttribute]
public enum BuildSettings
{
None = 0,
DoNotResetPreviouslyBuiltTargets = 1,
}
public partial class BuildTask
{
internal BuildTask() { }
public string Condition { get { throw null; } set { } }
public bool ContinueOnError { get { throw null; } set { } }
public Microsoft.Build.Framework.ITaskHost HostObject { get { throw null; } set { } }
public string Name { get { throw null; } }
public System.Type Type { get { throw null; } }
public void AddOutputItem(string taskParameter, string itemName) { }
public void AddOutputProperty(string taskParameter, string propertyName) { }
public bool Execute() { throw null; }
public string[] GetParameterNames() { throw null; }
public string GetParameterValue(string attributeName) { throw null; }
public void SetParameterValue(string parameterName, string parameterValue) { }
public void SetParameterValue(string parameterName, string parameterValue, bool treatParameterValueAsLiteral) { }
}
public delegate void ColorResetter();
public delegate void ColorSetter(System.ConsoleColor color);
public partial class ConfigurableForwardingLogger : Microsoft.Build.Framework.IForwardingLogger, Microsoft.Build.Framework.ILogger, Microsoft.Build.Framework.INodeLogger
{
public ConfigurableForwardingLogger() { }
public Microsoft.Build.Framework.IEventRedirector BuildEventRedirector { get { throw null; } set { } }
public int NodeId { get { throw null; } set { } }
public string Parameters { get { throw null; } set { } }
public Microsoft.Build.Framework.LoggerVerbosity Verbosity { get { throw null; } set { } }
protected virtual void ForwardToCentralLogger(Microsoft.Build.Framework.BuildEventArgs e) { }
public virtual void Initialize(Microsoft.Build.Framework.IEventSource eventSource) { }
public void Initialize(Microsoft.Build.Framework.IEventSource eventSource, int nodeCount) { }
public virtual void Shutdown() { }
}
public partial class ConsoleLogger : Microsoft.Build.Framework.ILogger, Microsoft.Build.Framework.INodeLogger
{
public ConsoleLogger() { }
public ConsoleLogger(Microsoft.Build.Framework.LoggerVerbosity verbosity) { }
public ConsoleLogger(Microsoft.Build.Framework.LoggerVerbosity verbosity, Microsoft.Build.BuildEngine.WriteHandler write, Microsoft.Build.BuildEngine.ColorSetter colorSet, Microsoft.Build.BuildEngine.ColorResetter colorReset) { }
public string Parameters { get { throw null; } set { } }
public bool ShowSummary { get { throw null; } set { } }
public bool SkipProjectStartedText { get { throw null; } set { } }
public Microsoft.Build.Framework.LoggerVerbosity Verbosity { get { throw null; } set { } }
protected Microsoft.Build.BuildEngine.WriteHandler WriteHandler { get { throw null; } set { } }
public void ApplyParameter(string parameterName, string parameterValue) { }
public void BuildFinishedHandler(object sender, Microsoft.Build.Framework.BuildFinishedEventArgs e) { }
public void BuildStartedHandler(object sender, Microsoft.Build.Framework.BuildStartedEventArgs e) { }
public void CustomEventHandler(object sender, Microsoft.Build.Framework.CustomBuildEventArgs e) { }
public void ErrorHandler(object sender, Microsoft.Build.Framework.BuildErrorEventArgs e) { }
public virtual void Initialize(Microsoft.Build.Framework.IEventSource eventSource) { }
public virtual void Initialize(Microsoft.Build.Framework.IEventSource eventSource, int nodeCount) { }
public void MessageHandler(object sender, Microsoft.Build.Framework.BuildMessageEventArgs e) { }
public void ProjectFinishedHandler(object sender, Microsoft.Build.Framework.ProjectFinishedEventArgs e) { }
public void ProjectStartedHandler(object sender, Microsoft.Build.Framework.ProjectStartedEventArgs e) { }
public virtual void Shutdown() { }
public void TargetFinishedHandler(object sender, Microsoft.Build.Framework.TargetFinishedEventArgs e) { }
public void TargetStartedHandler(object sender, Microsoft.Build.Framework.TargetStartedEventArgs e) { }
public void TaskFinishedHandler(object sender, Microsoft.Build.Framework.TaskFinishedEventArgs e) { }
public void TaskStartedHandler(object sender, Microsoft.Build.Framework.TaskStartedEventArgs e) { }
public void WarningHandler(object sender, Microsoft.Build.Framework.BuildWarningEventArgs e) { }
}
public partial class DistributedFileLogger : Microsoft.Build.Framework.IForwardingLogger, Microsoft.Build.Framework.ILogger, Microsoft.Build.Framework.INodeLogger
{
public DistributedFileLogger() { }
public Microsoft.Build.Framework.IEventRedirector BuildEventRedirector { get { throw null; } set { } }
public int NodeId { get { throw null; } set { } }
public string Parameters { get { throw null; } set { } }
public Microsoft.Build.Framework.LoggerVerbosity Verbosity { get { throw null; } set { } }
public void Initialize(Microsoft.Build.Framework.IEventSource eventSource) { }
public void Initialize(Microsoft.Build.Framework.IEventSource eventSource, int nodeCount) { }
public void Shutdown() { }
}
[System.ObsoleteAttribute("This class has been deprecated. Please use Microsoft.Build.Evaluation.ProjectCollection from the Microsoft.Build assembly instead.")]
public partial class Engine
{
public Engine() { }
public Engine(Microsoft.Build.BuildEngine.BuildPropertyGroup globalProperties) { }
public Engine(Microsoft.Build.BuildEngine.BuildPropertyGroup globalProperties, Microsoft.Build.BuildEngine.ToolsetDefinitionLocations locations) { }
public Engine(Microsoft.Build.BuildEngine.BuildPropertyGroup globalProperties, Microsoft.Build.BuildEngine.ToolsetDefinitionLocations locations, int numberOfCpus, string localNodeProviderParameters) { }
public Engine(Microsoft.Build.BuildEngine.ToolsetDefinitionLocations locations) { }
[System.ObsoleteAttribute("If you were simply passing in the .NET Framework location as the BinPath, just change to the parameterless Engine() constructor. Otherwise, you can define custom toolsets in the registry or config file, or by adding elements to the Engine's ToolsetCollection. Then use either the Engine() or Engine(ToolsetLocations) constructor instead.")]
public Engine(string binPath) { }
[System.ObsoleteAttribute("Avoid setting BinPath. If you were simply passing in the .NET Framework location as the BinPath, no other action is necessary. Otherwise, define Toolsets instead in the registry or config file, or by adding elements to the Engine's ToolsetCollection, in order to use a custom BinPath.")]
public string BinPath { get { throw null; } set { } }
public bool BuildEnabled { get { throw null; } set { } }
public string DefaultToolsVersion { get { throw null; } set { } }
public static Microsoft.Build.BuildEngine.Engine GlobalEngine { get { throw null; } }
public Microsoft.Build.BuildEngine.BuildPropertyGroup GlobalProperties { get { throw null; } set { } }
public bool IsBuilding { get { throw null; } }
public bool OnlyLogCriticalEvents { get { throw null; } set { } }
public Microsoft.Build.BuildEngine.ToolsetCollection Toolsets { get { throw null; } }
public static System.Version Version { get { throw null; } }
public bool BuildProject(Microsoft.Build.BuildEngine.Project project) { throw null; }
public bool BuildProject(Microsoft.Build.BuildEngine.Project project, string targetName) { throw null; }
public bool BuildProject(Microsoft.Build.BuildEngine.Project project, string[] targetNames) { throw null; }
public bool BuildProject(Microsoft.Build.BuildEngine.Project project, string[] targetNames, System.Collections.IDictionary targetOutputs) { throw null; }
public bool BuildProject(Microsoft.Build.BuildEngine.Project project, string[] targetNames, System.Collections.IDictionary targetOutputs, Microsoft.Build.BuildEngine.BuildSettings buildFlags) { throw null; }
public bool BuildProjectFile(string projectFile) { throw null; }
public bool BuildProjectFile(string projectFile, string targetName) { throw null; }
public bool BuildProjectFile(string projectFile, string[] targetNames) { throw null; }
public bool BuildProjectFile(string projectFile, string[] targetNames, Microsoft.Build.BuildEngine.BuildPropertyGroup globalProperties) { throw null; }
public bool BuildProjectFile(string projectFile, string[] targetNames, Microsoft.Build.BuildEngine.BuildPropertyGroup globalProperties, System.Collections.IDictionary targetOutputs) { throw null; }
public bool BuildProjectFile(string projectFile, string[] targetNames, Microsoft.Build.BuildEngine.BuildPropertyGroup globalProperties, System.Collections.IDictionary targetOutputs, Microsoft.Build.BuildEngine.BuildSettings buildFlags) { throw null; }
public bool BuildProjectFile(string projectFile, string[] targetNames, Microsoft.Build.BuildEngine.BuildPropertyGroup globalProperties, System.Collections.IDictionary targetOutputs, Microsoft.Build.BuildEngine.BuildSettings buildFlags, string toolsVersion) { throw null; }
public bool BuildProjectFiles(string[] projectFiles, string[][] targetNamesPerProject, Microsoft.Build.BuildEngine.BuildPropertyGroup[] globalPropertiesPerProject, System.Collections.IDictionary[] targetOutputsPerProject, Microsoft.Build.BuildEngine.BuildSettings buildFlags, string[] toolsVersions) { throw null; }
public Microsoft.Build.BuildEngine.Project CreateNewProject() { throw null; }
public Microsoft.Build.BuildEngine.Project GetLoadedProject(string projectFullFileName) { throw null; }
public void RegisterDistributedLogger(Microsoft.Build.Framework.ILogger centralLogger, Microsoft.Build.BuildEngine.LoggerDescription forwardingLogger) { }
public void RegisterLogger(Microsoft.Build.Framework.ILogger logger) { }
public void Shutdown() { }
public void UnloadAllProjects() { }
public void UnloadProject(Microsoft.Build.BuildEngine.Project project) { }
public void UnregisterAllLoggers() { }
}
public partial class FileLogger : Microsoft.Build.BuildEngine.ConsoleLogger
{
public FileLogger() { }
public override void Initialize(Microsoft.Build.Framework.IEventSource eventSource) { }
public override void Initialize(Microsoft.Build.Framework.IEventSource eventSource, int nodeCount) { }
public override void Shutdown() { }
}
public partial class Import
{
internal Import() { }
public string Condition { get { throw null; } set { } }
public string EvaluatedProjectPath { get { throw null; } }
public bool IsImported { get { throw null; } }
public string ProjectPath { get { throw null; } set { } }
}
public partial class ImportCollection : System.Collections.ICollection, System.Collections.IEnumerable
{
internal ImportCollection() { }
public int Count { get { throw null; } }
public bool IsSynchronized { get { throw null; } }
public object SyncRoot { get { throw null; } }
public void AddNewImport(string projectFile, string condition) { }
public void CopyTo(Microsoft.Build.BuildEngine.Import[] array, int index) { }
public void CopyTo(System.Array array, int index) { }
public System.Collections.IEnumerator GetEnumerator() { throw null; }
public void RemoveImport(Microsoft.Build.BuildEngine.Import importToRemove) { }
}
public sealed partial class InternalLoggerException : System.Exception
{
public InternalLoggerException() { }
public InternalLoggerException(string message) { }
public InternalLoggerException(string message, System.Exception innerException) { }
public Microsoft.Build.Framework.BuildEventArgs BuildEventArgs { get { throw null; } }
public string ErrorCode { get { throw null; } }
public string HelpKeyword { get { throw null; } }
public bool InitializationException { get { throw null; } }
[System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.Demand, SerializationFormatter=true)]
public override void GetObjectData(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { }
}
public sealed partial class InvalidProjectFileException : System.Exception
{
public InvalidProjectFileException() { }
public InvalidProjectFileException(string message) { }
public InvalidProjectFileException(string message, System.Exception innerException) { }
public InvalidProjectFileException(string projectFile, int lineNumber, int columnNumber, int endLineNumber, int endColumnNumber, string message, string errorSubcategory, string errorCode, string helpKeyword) { }
public InvalidProjectFileException(System.Xml.XmlNode xmlNode, string message, string errorSubcategory, string errorCode, string helpKeyword) { }
public string BaseMessage { get { throw null; } }
public int ColumnNumber { get { throw null; } }
public int EndColumnNumber { get { throw null; } }
public int EndLineNumber { get { throw null; } }
public string ErrorCode { get { throw null; } }
public string ErrorSubcategory { get { throw null; } }
public string HelpKeyword { get { throw null; } }
public int LineNumber { get { throw null; } }
public override string Message { get { throw null; } }
public string ProjectFile { get { throw null; } }
[System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.Demand, SerializationFormatter=true)]
public override void GetObjectData(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { }
}
public partial class InvalidToolsetDefinitionException : System.Exception
{
public InvalidToolsetDefinitionException() { }
protected InvalidToolsetDefinitionException(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { }
public InvalidToolsetDefinitionException(string message) { }
public InvalidToolsetDefinitionException(string message, System.Exception innerException) { }
public InvalidToolsetDefinitionException(string message, string errorCode) { }
public InvalidToolsetDefinitionException(string message, string errorCode, System.Exception innerException) { }
public string ErrorCode { get { throw null; } }
[System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.Demand, SerializationFormatter=true)]
public override void GetObjectData(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { }
}
public partial class LocalNode
{
internal LocalNode() { }
public static void StartLocalNodeServer(int nodeNumber) { }
}
public partial class LoggerDescription
{
public LoggerDescription(string loggerClassName, string loggerAssemblyName, string loggerAssemblyFile, string loggerSwitchParameters, Microsoft.Build.Framework.LoggerVerbosity verbosity) { }
public string LoggerSwitchParameters { get { throw null; } }
public Microsoft.Build.Framework.LoggerVerbosity Verbosity { get { throw null; } }
}
[System.ObsoleteAttribute("This class has been deprecated. Please use Microsoft.Build.Evaluation.Project from the Microsoft.Build assembly instead.")]
public partial class Project
{
public Project() { }
public Project(Microsoft.Build.BuildEngine.Engine engine) { }
public Project(Microsoft.Build.BuildEngine.Engine engine, string toolsVersion) { }
public bool BuildEnabled { get { throw null; } set { } }
public string DefaultTargets { get { throw null; } set { } }
public string DefaultToolsVersion { get { throw null; } set { } }
public System.Text.Encoding Encoding { get { throw null; } }
public Microsoft.Build.BuildEngine.BuildItemGroup EvaluatedItems { get { throw null; } }
public Microsoft.Build.BuildEngine.BuildItemGroup EvaluatedItemsIgnoringCondition { get { throw null; } }
public Microsoft.Build.BuildEngine.BuildPropertyGroup EvaluatedProperties { get { throw null; } }
public string FullFileName { get { throw null; } set { } }
public Microsoft.Build.BuildEngine.BuildPropertyGroup GlobalProperties { get { throw null; } set { } }
public bool HasToolsVersionAttribute { get { throw null; } }
public Microsoft.Build.BuildEngine.ImportCollection Imports { get { throw null; } }
public string InitialTargets { get { throw null; } set { } }
public bool IsDirty { get { throw null; } }
public bool IsValidated { get { throw null; } set { } }
public Microsoft.Build.BuildEngine.BuildItemGroupCollection ItemGroups { get { throw null; } }
public Microsoft.Build.BuildEngine.Engine ParentEngine { get { throw null; } }
public Microsoft.Build.BuildEngine.BuildPropertyGroupCollection PropertyGroups { get { throw null; } }
public string SchemaFile { get { throw null; } set { } }
public Microsoft.Build.BuildEngine.TargetCollection Targets { get { throw null; } }
public System.DateTime TimeOfLastDirty { get { throw null; } }
public string ToolsVersion { get { throw null; } }
public Microsoft.Build.BuildEngine.UsingTaskCollection UsingTasks { get { throw null; } }
public string Xml { get { throw null; } }
public void AddNewImport(string projectFile, string condition) { }
public Microsoft.Build.BuildEngine.BuildItem AddNewItem(string itemName, string itemInclude) { throw null; }
public Microsoft.Build.BuildEngine.BuildItem AddNewItem(string itemName, string itemInclude, bool treatItemIncludeAsLiteral) { throw null; }
public Microsoft.Build.BuildEngine.BuildItemGroup AddNewItemGroup() { throw null; }
public Microsoft.Build.BuildEngine.BuildPropertyGroup AddNewPropertyGroup(bool insertAtEndOfProject) { throw null; }
public void AddNewUsingTaskFromAssemblyFile(string taskName, string assemblyFile) { }
public void AddNewUsingTaskFromAssemblyName(string taskName, string assemblyName) { }
public bool Build() { throw null; }
public bool Build(string targetName) { throw null; }
public bool Build(string[] targetNames) { throw null; }
public bool Build(string[] targetNames, System.Collections.IDictionary targetOutputs) { throw null; }
public bool Build(string[] targetNames, System.Collections.IDictionary targetOutputs, Microsoft.Build.BuildEngine.BuildSettings buildFlags) { throw null; }
public string[] GetConditionedPropertyValues(string propertyName) { throw null; }
public Microsoft.Build.BuildEngine.BuildItemGroup GetEvaluatedItemsByName(string itemName) { throw null; }
public Microsoft.Build.BuildEngine.BuildItemGroup GetEvaluatedItemsByNameIgnoringCondition(string itemName) { throw null; }
public string GetEvaluatedProperty(string propertyName) { throw null; }
public string GetProjectExtensions(string id) { throw null; }
public void Load(System.IO.TextReader textReader) { }
public void Load(System.IO.TextReader textReader, Microsoft.Build.BuildEngine.ProjectLoadSettings projectLoadSettings) { }
public void Load(string projectFileName) { }
public void Load(string projectFileName, Microsoft.Build.BuildEngine.ProjectLoadSettings projectLoadSettings) { }
public void LoadXml(string projectXml) { }
public void LoadXml(string projectXml, Microsoft.Build.BuildEngine.ProjectLoadSettings projectLoadSettings) { }
public void MarkProjectAsDirty() { }
public void RemoveAllItemGroups() { }
public void RemoveAllPropertyGroups() { }
public void RemoveImportedPropertyGroup(Microsoft.Build.BuildEngine.BuildPropertyGroup propertyGroupToRemove) { }
public void RemoveItem(Microsoft.Build.BuildEngine.BuildItem itemToRemove) { }
public void RemoveItemGroup(Microsoft.Build.BuildEngine.BuildItemGroup itemGroupToRemove) { }
public void RemoveItemGroupsWithMatchingCondition(string matchCondition) { }
public void RemoveItemsByName(string itemName) { }
public void RemovePropertyGroup(Microsoft.Build.BuildEngine.BuildPropertyGroup propertyGroupToRemove) { }
public void RemovePropertyGroupsWithMatchingCondition(string matchCondition) { }
public void RemovePropertyGroupsWithMatchingCondition(string matchCondition, bool includeImportedPropertyGroups) { }
public void ResetBuildStatus() { }
public void Save(System.IO.TextWriter textWriter) { }
public void Save(string projectFileName) { }
public void Save(string projectFileName, System.Text.Encoding encoding) { }
public void SetImportedProperty(string propertyName, string propertyValue, string condition, Microsoft.Build.BuildEngine.Project importProject) { }
public void SetImportedProperty(string propertyName, string propertyValue, string condition, Microsoft.Build.BuildEngine.Project importedProject, Microsoft.Build.BuildEngine.PropertyPosition position) { }
public void SetImportedProperty(string propertyName, string propertyValue, string condition, Microsoft.Build.BuildEngine.Project importedProject, Microsoft.Build.BuildEngine.PropertyPosition position, bool treatPropertyValueAsLiteral) { }
public void SetProjectExtensions(string id, string content) { }
public void SetProperty(string propertyName, string propertyValue) { }
public void SetProperty(string propertyName, string propertyValue, string condition) { }
public void SetProperty(string propertyName, string propertyValue, string condition, Microsoft.Build.BuildEngine.PropertyPosition position) { }
public void SetProperty(string propertyName, string propertyValue, string condition, Microsoft.Build.BuildEngine.PropertyPosition position, bool treatPropertyValueAsLiteral) { }
}
[System.FlagsAttribute]
public enum ProjectLoadSettings
{
None = 0,
IgnoreMissingImports = 1,
}
public enum PropertyPosition
{
UseExistingOrCreateAfterLastPropertyGroup = 0,
UseExistingOrCreateAfterLastImport = 1,
}
public sealed partial class RemoteErrorException : System.Exception
{
internal RemoteErrorException() { }
[System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.Demand, SerializationFormatter=true)]
public override void GetObjectData(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { }
}
public static partial class SolutionWrapperProject
{
public static string Generate(string solutionPath, string toolsVersionOverride, Microsoft.Build.Framework.BuildEventContext projectBuildEventContext) { throw null; }
}
public partial class Target : System.Collections.IEnumerable
{
internal Target() { }
public string Condition { get { throw null; } set { } }
public string DependsOnTargets { get { throw null; } set { } }
public string Inputs { get { throw null; } set { } }
public bool IsImported { get { throw null; } }
public string Name { get { throw null; } }
public string Outputs { get { throw null; } set { } }
public Microsoft.Build.BuildEngine.BuildTask AddNewTask(string taskName) { throw null; }
public System.Collections.IEnumerator GetEnumerator() { throw null; }
public void RemoveTask(Microsoft.Build.BuildEngine.BuildTask taskElement) { }
}
public partial class TargetCollection : System.Collections.ICollection, System.Collections.IEnumerable
{
internal TargetCollection() { }
public int Count { get { throw null; } }
public bool IsSynchronized { get { throw null; } }
public Microsoft.Build.BuildEngine.Target this[string index] { get { throw null; } }
public object SyncRoot { get { throw null; } }
public Microsoft.Build.BuildEngine.Target AddNewTarget(string targetName) { throw null; }
public void CopyTo(System.Array array, int index) { }
public bool Exists(string targetName) { throw null; }
public System.Collections.IEnumerator GetEnumerator() { throw null; }
public void RemoveTarget(Microsoft.Build.BuildEngine.Target targetToRemove) { }
}
public partial class Toolset
{
public Toolset(string toolsVersion, string toolsPath) { }
public Toolset(string toolsVersion, string toolsPath, Microsoft.Build.BuildEngine.BuildPropertyGroup buildProperties) { }
public Microsoft.Build.BuildEngine.BuildPropertyGroup BuildProperties { get { throw null; } }
public string ToolsPath { get { throw null; } }
public string ToolsVersion { get { throw null; } }
public Microsoft.Build.BuildEngine.Toolset Clone() { throw null; }
}
public partial class ToolsetCollection : System.Collections.Generic.ICollection<Microsoft.Build.BuildEngine.Toolset>, System.Collections.Generic.IEnumerable<Microsoft.Build.BuildEngine.Toolset>, System.Collections.IEnumerable
{
internal ToolsetCollection() { }
public int Count { get { throw null; } }
public bool IsReadOnly { get { throw null; } }
public Microsoft.Build.BuildEngine.Toolset this[string toolsVersion] { get { throw null; } }
public System.Collections.Generic.IEnumerable<string> ToolsVersions { get { throw null; } }
public void Add(Microsoft.Build.BuildEngine.Toolset item) { }
public void Clear() { }
public bool Contains(Microsoft.Build.BuildEngine.Toolset item) { throw null; }
public bool Contains(string toolsVersion) { throw null; }
public void CopyTo(Microsoft.Build.BuildEngine.Toolset[] array, int arrayIndex) { }
public System.Collections.Generic.IEnumerator<Microsoft.Build.BuildEngine.Toolset> GetEnumerator() { throw null; }
public bool Remove(Microsoft.Build.BuildEngine.Toolset item) { throw null; }
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { throw null; }
}
[System.FlagsAttribute]
public enum ToolsetDefinitionLocations
{
None = 0,
ConfigurationFile = 1,
Registry = 2,
}
public partial class UsingTask
{
internal UsingTask() { }
public string AssemblyFile { get { throw null; } }
public string AssemblyName { get { throw null; } }
public string Condition { get { throw null; } }
public bool IsImported { get { throw null; } }
public string TaskName { get { throw null; } }
}
public partial class UsingTaskCollection : System.Collections.ICollection, System.Collections.IEnumerable
{
internal UsingTaskCollection() { }
public int Count { get { throw null; } }
public bool IsSynchronized { get { throw null; } }
public object SyncRoot { get { throw null; } }
public void CopyTo(Microsoft.Build.BuildEngine.UsingTask[] array, int index) { }
public void CopyTo(System.Array array, int index) { }
public System.Collections.IEnumerator GetEnumerator() { throw null; }
}
public static partial class Utilities
{
public static string Escape(string unescapedExpression) { throw null; }
}
public delegate void WriteHandler(string message);
}
| |
/* ====================================================================
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 System.Diagnostics;
using NPOI.SS.Formula.Atp;
namespace NPOI.SS.Formula
{
using System;
using System.Collections;
using NPOI.SS.Formula;
using NPOI.SS.Formula.Eval;
using NPOI.SS.Util;
using NPOI.SS.Formula.Functions;
using NPOI.SS.Formula.Udf;
using System.Collections.Generic;
using NPOI.SS.UserModel;
using NPOI.SS.Formula.PTG;
using NPOI.Util;
/**
* Evaluates formula cells.<p/>
*
* For performance reasons, this class keeps a cache of all previously calculated intermediate
* cell values. Be sure To call {@link #ClearCache()} if any workbook cells are Changed between
* calls To evaluate~ methods on this class.<br/>
*
* For POI internal use only
*
* @author Josh Micich
*/
public class WorkbookEvaluator
{
private IEvaluationWorkbook _workbook;
private EvaluationCache _cache;
private int _workbookIx;
private IEvaluationListener _evaluationListener;
private Hashtable _sheetIndexesBySheet;
private Dictionary<String, int> _sheetIndexesByName;
private CollaboratingWorkbooksEnvironment _collaboratingWorkbookEnvironment;
private IStabilityClassifier _stabilityClassifier;
private UDFFinder _udfFinder;
private bool _ignoreMissingWorkbooks = false;
public WorkbookEvaluator(IEvaluationWorkbook workbook, IStabilityClassifier stabilityClassifier, UDFFinder udfFinder)
: this(workbook, null, stabilityClassifier, udfFinder)
{
}
public WorkbookEvaluator(IEvaluationWorkbook workbook, IEvaluationListener evaluationListener, IStabilityClassifier stabilityClassifier, UDFFinder udfFinder)
{
_workbook = workbook;
_evaluationListener = evaluationListener;
_cache = new EvaluationCache(evaluationListener);
_sheetIndexesBySheet = new Hashtable();
_sheetIndexesByName = new Dictionary<string, int>();
_collaboratingWorkbookEnvironment = CollaboratingWorkbooksEnvironment.EMPTY;
_workbookIx = 0;
_stabilityClassifier = stabilityClassifier;
AggregatingUDFFinder defaultToolkit = // workbook can be null in unit tests
workbook == null ? null : (AggregatingUDFFinder)workbook.GetUDFFinder();
if (defaultToolkit != null && udfFinder != null)
{
defaultToolkit.Add(udfFinder);
}
_udfFinder = defaultToolkit;
}
/**
* also for debug use. Used in ToString methods
*/
/* package */
public String GetSheetName(int sheetIndex)
{
return _workbook.GetSheetName(sheetIndex);
}
public WorkbookEvaluator GetOtherWorkbookEvaluator(String workbookName)
{
return _collaboratingWorkbookEnvironment.GetWorkbookEvaluator(workbookName);
}
internal IEvaluationWorkbook Workbook
{
get
{
return _workbook;
}
}
internal IEvaluationSheet GetSheet(int sheetIndex)
{
return _workbook.GetSheet(sheetIndex);
}
/* package */
internal IEvaluationName GetName(String name, int sheetIndex)
{
NamePtg namePtg = _workbook.GetName(name, sheetIndex).CreatePtg();
if (namePtg == null)
{
return null;
}
else
{
return _workbook.GetName(namePtg);
}
}
private static bool IsDebugLogEnabled()
{
#if DEBUG
return true;
#else
return false;
#endif
}
private static bool IsInfoLogEnabled()
{
#if TRACE
return true;
#else
return false;
#endif
}
private static void LogDebug(String s)
{
if (IsDebugLogEnabled())
{
Debug.WriteLine(s);
}
}
private static void LogInfo(String s)
{
if (IsInfoLogEnabled())
{
Trace.WriteLine(s);
}
}
/* package */
public void AttachToEnvironment(CollaboratingWorkbooksEnvironment collaboratingWorkbooksEnvironment, EvaluationCache cache, int workbookIx)
{
_collaboratingWorkbookEnvironment = collaboratingWorkbooksEnvironment;
_cache = cache;
_workbookIx = workbookIx;
}
/* package */
public CollaboratingWorkbooksEnvironment GetEnvironment()
{
return _collaboratingWorkbookEnvironment;
}
/* package */
public void DetachFromEnvironment()
{
_collaboratingWorkbookEnvironment = CollaboratingWorkbooksEnvironment.EMPTY;
_cache = new EvaluationCache(_evaluationListener);
_workbookIx = 0;
}
/* package */
public IEvaluationListener GetEvaluationListener()
{
return _evaluationListener;
}
/**
* Should be called whenever there are Changes To input cells in the evaluated workbook.
* Failure To call this method after changing cell values will cause incorrect behaviour
* of the evaluate~ methods of this class
*/
public void ClearAllCachedResultValues()
{
_cache.Clear();
_sheetIndexesBySheet.Clear();
}
/**
* Should be called To tell the cell value cache that the specified (value or formula) cell
* Has Changed.
*/
public void NotifyUpdateCell(IEvaluationCell cell)
{
int sheetIndex = GetSheetIndex(cell.Sheet);
_cache.NotifyUpdateCell(_workbookIx, sheetIndex, cell);
}
/**
* Should be called To tell the cell value cache that the specified cell Has just been
* deleted.
*/
public void NotifyDeleteCell(IEvaluationCell cell)
{
int sheetIndex = GetSheetIndex(cell.Sheet);
_cache.NotifyDeleteCell(_workbookIx, sheetIndex, cell);
}
public int GetSheetIndex(IEvaluationSheet sheet)
{
object result = _sheetIndexesBySheet[sheet];
if (result == null)
{
int sheetIndex = _workbook.GetSheetIndex(sheet);
if (sheetIndex < 0)
{
throw new Exception("Specified sheet from a different book");
}
result = sheetIndex;
_sheetIndexesBySheet[sheet] = result;
}
return (int)result;
}
/* package */
internal int GetSheetIndexByExternIndex(int externSheetIndex)
{
return _workbook.ConvertFromExternSheetIndex(externSheetIndex);
}
/**
* Case-insensitive.
* @return -1 if sheet with specified name does not exist
*/
/* package */
public int GetSheetIndex(String sheetName)
{
int result;
if (_sheetIndexesByName.ContainsKey(sheetName))
{
result = _sheetIndexesByName[sheetName];
}
else
{
int sheetIndex = _workbook.GetSheetIndex(sheetName);
if (sheetIndex < 0)
{
return -1;
}
result = sheetIndex;
_sheetIndexesByName[sheetName] = result;
}
return result;
}
public ValueEval Evaluate(IEvaluationCell srcCell)
{
int sheetIndex = GetSheetIndex(srcCell.Sheet);
return EvaluateAny(srcCell, sheetIndex, srcCell.RowIndex, srcCell.ColumnIndex, new EvaluationTracker(_cache));
}
/**
* @return never <c>null</c>, never {@link BlankEval}
*/
private ValueEval EvaluateAny(IEvaluationCell srcCell, int sheetIndex,
int rowIndex, int columnIndex, EvaluationTracker tracker)
{
bool shouldCellDependencyBeRecorded = _stabilityClassifier == null ? true
: !_stabilityClassifier.IsCellFinal(sheetIndex, rowIndex, columnIndex);
ValueEval result;
if (srcCell == null || srcCell.CellType != CellType.Formula)
{
result = GetValueFromNonFormulaCell(srcCell);
if (shouldCellDependencyBeRecorded)
{
tracker.AcceptPlainValueDependency(_workbookIx, sheetIndex, rowIndex, columnIndex, result);
}
return result;
}
FormulaCellCacheEntry cce = _cache.GetOrCreateFormulaCellEntry(srcCell);
if (shouldCellDependencyBeRecorded || cce.IsInputSensitive)
{
tracker.AcceptFormulaDependency(cce);
}
IEvaluationListener evalListener = _evaluationListener;
if (cce.GetValue() == null)
{
if (!tracker.StartEvaluate(cce))
{
return ErrorEval.CIRCULAR_REF_ERROR;
}
OperationEvaluationContext ec = new OperationEvaluationContext(this, _workbook, sheetIndex, rowIndex, columnIndex, tracker);
try
{
Ptg[] ptgs = _workbook.GetFormulaTokens(srcCell);
if (evalListener == null)
{
result = EvaluateFormula(ec, ptgs);
}
else
{
evalListener.OnStartEvaluate(srcCell, cce);
result = EvaluateFormula(ec, ptgs);
evalListener.OnEndEvaluate(cce, result);
}
tracker.UpdateCacheResult(result);
}
catch (NotImplementedException e)
{
throw AddExceptionInfo(e, sheetIndex, rowIndex, columnIndex);
}
catch (RuntimeException re)
{
if (re.InnerException is WorkbookNotFoundException && _ignoreMissingWorkbooks)
{
LogInfo(re.InnerException.Message + " - Continuing with cached value!");
switch (srcCell.CachedFormulaResultType)
{
case CellType.Numeric:
result = new NumberEval(srcCell.NumericCellValue);
break;
case CellType.String:
result = new StringEval(srcCell.StringCellValue);
break;
case CellType.Blank:
result = BlankEval.instance;
break;
case CellType.Boolean:
result = BoolEval.ValueOf(srcCell.BooleanCellValue);
break;
case CellType.Error:
result = ErrorEval.ValueOf(srcCell.ErrorCellValue);
break;
case CellType.Formula:
default:
throw new RuntimeException("Unexpected cell type '" + srcCell.CellType + "' found!");
}
}
else
{
throw re;
}
}
finally
{
tracker.EndEvaluate(cce);
}
}
else
{
if (evalListener != null)
{
evalListener.OnCacheHit(sheetIndex, rowIndex, columnIndex, cce.GetValue());
}
return cce.GetValue();
}
if (IsDebugLogEnabled())
{
String sheetName = GetSheetName(sheetIndex);
CellReference cr = new CellReference(rowIndex, columnIndex);
LogDebug("Evaluated " + sheetName + "!" + cr.FormatAsString() + " To " + cce.GetValue());
}
// Usually (result === cce.getValue())
// But sometimes: (result==ErrorEval.CIRCULAR_REF_ERROR, cce.getValue()==null)
// When circular references are detected, the cache entry is only updated for
// the top evaluation frame
//return cce.GetValue();
return result;
}
/**
* Adds the current cell reference to the exception for easier debugging.
* Would be nice to get the formula text as well, but that seems to require
* too much digging around and casting to get the FormulaRenderingWorkbook.
*/
private NotImplementedException AddExceptionInfo(NotImplementedException inner, int sheetIndex, int rowIndex, int columnIndex)
{
try
{
String sheetName = _workbook.GetSheetName(sheetIndex);
CellReference cr = new CellReference(sheetName, rowIndex, columnIndex, false, false);
String msg = "Error evaluating cell " + cr.FormatAsString();
return new NotImplementedException(msg, inner);
}
catch (Exception)
{
// avoid bombing out during exception handling
//e.printStackTrace();
return inner; // preserve original exception
}
}
/**
* Gets the value from a non-formula cell.
* @param cell may be <c>null</c>
* @return {@link BlankEval} if cell is <c>null</c> or blank, never <c>null</c>
*/
/* package */
internal static ValueEval GetValueFromNonFormulaCell(IEvaluationCell cell)
{
if (cell == null)
{
return BlankEval.instance;
}
CellType cellType = cell.CellType;
switch (cellType)
{
case CellType.Numeric:
return new NumberEval(cell.NumericCellValue);
case CellType.String:
return new StringEval(cell.StringCellValue);
case CellType.Boolean:
return BoolEval.ValueOf(cell.BooleanCellValue);
case CellType.Blank:
return BlankEval.instance;
case CellType.Error:
return ErrorEval.ValueOf(cell.ErrorCellValue);
}
throw new Exception("Unexpected cell type (" + cellType + ")");
}
/**
* whether print detailed messages about the next formula evaluation
*/
private bool dbgEvaluationOutputForNextEval = false;
// special logger for formula evaluation output (because of possibly very large output)
private POILogger EVAL_LOG = POILogFactory.GetLogger("POI.FormulaEval");
// current indent level for evalution; negative value for no output
private int dbgEvaluationOutputIndent = -1;
// visibility raised for testing
/* package */
public ValueEval EvaluateFormula(OperationEvaluationContext ec, Ptg[] ptgs)
{
String dbgIndentStr = ""; // always init. to non-null just for defensive avoiding NPE
if (dbgEvaluationOutputForNextEval)
{
// first evaluation call when ouput is desired, so iit. this evaluator instance
dbgEvaluationOutputIndent = 1;
dbgEvaluationOutputForNextEval = false;
}
if (dbgEvaluationOutputIndent > 0)
{
// init. indent string to needed spaces (create as substring vom very long space-only string;
// limit indendation for deep recursions)
dbgIndentStr = " ";
dbgIndentStr = dbgIndentStr.Substring(0, Math.Min(dbgIndentStr.Length, dbgEvaluationOutputIndent * 2));
EVAL_LOG.Log(POILogger.WARN, dbgIndentStr
+ "- evaluateFormula('" + ec.GetRefEvaluatorForCurrentSheet().SheetName
+ "'/" + new CellReference(ec.RowIndex, ec.ColumnIndex).FormatAsString()
+ "): " + Arrays.ToString(ptgs).Replace("\\Qorg.apache.poi.ss.formula.ptg.\\E", ""));
dbgEvaluationOutputIndent++;
}
Stack<ValueEval> stack = new Stack<ValueEval>();
for (int i = 0, iSize = ptgs.Length; i < iSize; i++)
{
// since we don't know how To handle these yet :(
Ptg ptg = ptgs[i];
if (dbgEvaluationOutputIndent > 0)
{
EVAL_LOG.Log(POILogger.INFO, dbgIndentStr + " * ptg " + i + ": " + ptg.ToString());
}
if (ptg is AttrPtg)
{
AttrPtg attrPtg = (AttrPtg)ptg;
if (attrPtg.IsSum)
{
// Excel prefers To encode 'SUM()' as a tAttr Token, but this evaluator
// expects the equivalent function Token
//byte nArgs = 1; // tAttrSum always Has 1 parameter
ptg = FuncVarPtg.SUM;//.Create("SUM", nArgs);
}
if (attrPtg.IsOptimizedChoose)
{
ValueEval arg0 = stack.Pop();
int[] jumpTable = attrPtg.JumpTable;
int dist;
int nChoices = jumpTable.Length;
try
{
int switchIndex = Choose.EvaluateFirstArg(arg0, ec.RowIndex, ec.ColumnIndex);
if (switchIndex < 1 || switchIndex > nChoices)
{
stack.Push(ErrorEval.VALUE_INVALID);
dist = attrPtg.ChooseFuncOffset + 4; // +4 for tFuncFar(CHOOSE)
}
else
{
dist = jumpTable[switchIndex - 1];
}
}
catch (EvaluationException e)
{
stack.Push(e.GetErrorEval());
dist = attrPtg.ChooseFuncOffset + 4; // +4 for tFuncFar(CHOOSE)
}
// Encoded dist for tAttrChoose includes size of jump table, but
// countTokensToBeSkipped() does not (it counts whole tokens).
dist -= nChoices * 2 + 2; // subtract jump table size
i += CountTokensToBeSkipped(ptgs, i, dist);
continue;
}
if (attrPtg.IsOptimizedIf)
{
ValueEval arg0 = stack.Pop();
bool evaluatedPredicate;
try
{
evaluatedPredicate = If.EvaluateFirstArg(arg0, ec.RowIndex, ec.ColumnIndex);
}
catch (EvaluationException e)
{
stack.Push(e.GetErrorEval());
int dist = attrPtg.Data;
i += CountTokensToBeSkipped(ptgs, i, dist);
attrPtg = (AttrPtg)ptgs[i];
dist = attrPtg.Data + 1;
i += CountTokensToBeSkipped(ptgs, i, dist);
continue;
}
if (evaluatedPredicate)
{
// nothing to skip - true param folows
}
else
{
int dist = attrPtg.Data;
i += CountTokensToBeSkipped(ptgs, i, dist);
Ptg nextPtg = ptgs[i + 1];
if (ptgs[i] is AttrPtg && nextPtg is FuncVarPtg)
{
// this is an if statement without a false param (as opposed to MissingArgPtg as the false param)
i++;
stack.Push(BoolEval.FALSE);
}
}
continue;
}
if (attrPtg.IsSkip)
{
int dist = attrPtg.Data + 1;
i += CountTokensToBeSkipped(ptgs, i, dist);
if (stack.Peek() == MissingArgEval.instance)
{
stack.Pop();
stack.Push(BlankEval.instance);
}
continue;
}
}
if (ptg is ControlPtg)
{
// skip Parentheses, Attr, etc
continue;
}
if (ptg is MemFuncPtg|| ptg is MemAreaPtg)
{
// can ignore, rest of Tokens for this expression are in OK RPN order
continue;
}
if (ptg is MemErrPtg) { continue; }
ValueEval opResult;
if (ptg is OperationPtg)
{
OperationPtg optg = (OperationPtg)ptg;
if (optg is UnionPtg) { continue; }
int numops = optg.NumberOfOperands;
ValueEval[] ops = new ValueEval[numops];
// storing the ops in reverse order since they are popping
for (int j = numops - 1; j >= 0; j--)
{
ValueEval p = (ValueEval)stack.Pop();
ops[j] = p;
}
// logDebug("Invoke " + operation + " (nAgs=" + numops + ")");
opResult = OperationEvaluatorFactory.Evaluate(optg, ops, ec);
}
else
{
opResult = GetEvalForPtg(ptg, ec);
}
if (opResult == null)
{
throw new Exception("Evaluation result must not be null");
}
// logDebug("push " + opResult);
stack.Push(opResult);
if (dbgEvaluationOutputIndent > 0)
{
EVAL_LOG.Log(POILogger.INFO, dbgIndentStr + " = " + opResult.ToString());
}
}
ValueEval value = ((ValueEval)stack.Pop());
if (stack.Count != 0)
{
throw new InvalidOperationException("evaluation stack not empty");
}
ValueEval result = DereferenceResult(value, ec.RowIndex, ec.ColumnIndex);
if (dbgEvaluationOutputIndent > 0)
{
EVAL_LOG.Log(POILogger.INFO, dbgIndentStr + "finshed eval of "
+ new CellReference(ec.RowIndex, ec.ColumnIndex).FormatAsString()
+ ": " + result.ToString());
dbgEvaluationOutputIndent--;
if (dbgEvaluationOutputIndent == 1)
{
// this evaluation is done, reset indent to stop logging
dbgEvaluationOutputIndent = -1;
}
} // if
return result;
}
/**
* Calculates the number of tokens that the evaluator should skip upon reaching a tAttrSkip.
*
* @return the number of tokens (starting from <c>startIndex+1</c>) that need to be skipped
* to achieve the specified <c>distInBytes</c> skip distance.
*/
private static int CountTokensToBeSkipped(Ptg[] ptgs, int startIndex, int distInBytes)
{
int remBytes = distInBytes;
int index = startIndex;
while (remBytes != 0)
{
index++;
remBytes -= ptgs[index].Size;
if (remBytes < 0)
{
throw new Exception("Bad skip distance (wrong token size calculation).");
}
if (index >= ptgs.Length)
{
throw new Exception("Skip distance too far (ran out of formula tokens).");
}
}
return index - startIndex;
}
/**
* Dereferences a single value from any AreaEval or RefEval evaluation result.
* If the supplied evaluationResult is just a plain value, it is returned as-is.
* @return a <c>NumberEval</c>, <c>StringEval</c>, <c>BoolEval</c>,
* <c>BlankEval</c> or <c>ErrorEval</c>. Never <c>null</c>.
*/
public static ValueEval DereferenceResult(ValueEval evaluationResult, int srcRowNum, int srcColNum)
{
ValueEval value;
try
{
value = OperandResolver.GetSingleValue(evaluationResult, srcRowNum, srcColNum);
}
catch (EvaluationException e)
{
return e.GetErrorEval();
}
if (value == BlankEval.instance)
{
// Note Excel behaviour here. A blank value is converted To zero.
return NumberEval.ZERO;
// Formulas _never_ evaluate To blank. If a formula appears To have evaluated To
// blank, the actual value is empty string. This can be verified with ISBLANK().
}
return value;
}
/**
* returns an appropriate Eval impl instance for the Ptg. The Ptg must be
* one of: Area3DPtg, AreaPtg, ReferencePtg, Ref3DPtg, IntPtg, NumberPtg,
* StringPtg, BoolPtg <br/>special Note: OperationPtg subtypes cannot be
* passed here!
*/
private ValueEval GetEvalForPtg(Ptg ptg, OperationEvaluationContext ec)
{
// consider converting all these (ptg is XxxPtg) expressions To (ptg.GetType() == XxxPtg.class)
if (ptg is NamePtg)
{
// named ranges, macro functions
NamePtg namePtg = (NamePtg)ptg;
IEvaluationName nameRecord = _workbook.GetName(namePtg);
if (nameRecord.IsFunctionName)
{
return new NameEval(nameRecord.NameText);
}
if (nameRecord.HasFormula)
{
return EvaluateNameFormula(nameRecord.NameDefinition, ec);
}
throw new Exception("Don't now how To evalate name '" + nameRecord.NameText + "'");
}
if (ptg is NameXPtg)
{
return ec.GetNameXEval(((NameXPtg)ptg));
}
if (ptg is IntPtg)
{
return new NumberEval(((IntPtg)ptg).Value);
}
if (ptg is NumberPtg)
{
return new NumberEval(((NumberPtg)ptg).Value);
}
if (ptg is StringPtg)
{
return new StringEval(((StringPtg)ptg).Value);
}
if (ptg is BoolPtg)
{
return BoolEval.ValueOf(((BoolPtg)ptg).Value);
}
if (ptg is ErrPtg)
{
return ErrorEval.ValueOf(((ErrPtg)ptg).ErrorCode);
}
if (ptg is MissingArgPtg)
{
return MissingArgEval.instance;
}
if (ptg is AreaErrPtg || ptg is RefErrorPtg
|| ptg is DeletedArea3DPtg || ptg is DeletedRef3DPtg)
{
return ErrorEval.REF_INVALID;
}
if (ptg is Ref3DPtg)
{
Ref3DPtg rptg = (Ref3DPtg)ptg;
return ec.GetRef3DEval(rptg.Row, rptg.Column, rptg.ExternSheetIndex);
}
if (ptg is Area3DPtg)
{
Area3DPtg aptg = (Area3DPtg)ptg;
return ec.GetArea3DEval(aptg.FirstRow, aptg.FirstColumn, aptg.LastRow, aptg.LastColumn, aptg.ExternSheetIndex);
}
if (ptg is RefPtg)
{
RefPtg rptg = (RefPtg)ptg;
return ec.GetRefEval(rptg.Row, rptg.Column);
}
if (ptg is AreaPtg)
{
AreaPtg aptg = (AreaPtg)ptg;
return ec.GetAreaEval(aptg.FirstRow, aptg.FirstColumn, aptg.LastRow, aptg.LastColumn);
}
if (ptg is UnknownPtg)
{
// POI uses UnknownPtg when the encoded Ptg array seems To be corrupted.
// This seems To occur in very rare cases (e.g. unused name formulas in bug 44774, attachment 21790)
// In any case, formulas are re-parsed before execution, so UnknownPtg should not Get here
throw new RuntimeException("UnknownPtg not allowed");
}
if (ptg is ExpPtg)
{
// ExpPtg is used for array formulas and shared formulas.
// it is currently unsupported, and may not even get implemented here
throw new RuntimeException("ExpPtg currently not supported");
}
throw new RuntimeException("Unexpected ptg class (" + ptg.GetType().Name + ")");
}
internal ValueEval EvaluateNameFormula(Ptg[] ptgs, OperationEvaluationContext ec)
{
if (ptgs.Length == 1)
{
return GetEvalForPtg(ptgs[0], ec);
}
return EvaluateFormula(ec, ptgs);
}
/**
* Used by the lazy ref evals whenever they need To Get the value of a contained cell.
*/
/* package */
public ValueEval EvaluateReference(IEvaluationSheet sheet, int sheetIndex, int rowIndex,
int columnIndex, EvaluationTracker tracker)
{
IEvaluationCell cell = sheet.GetCell(rowIndex, columnIndex);
return EvaluateAny(cell, sheetIndex, rowIndex, columnIndex, tracker);
}
public FreeRefFunction FindUserDefinedFunction(String functionName)
{
return _udfFinder.FindFunction(functionName);
}
/**
* Whether to ignore missing references to external workbooks and
* use cached formula results in the main workbook instead.
* <p>
* In some cases exetrnal workbooks referenced by formulas in the main workbook are not avaiable.
* With this method you can control how POI handles such missing references:
* <ul>
* <li>by default ignoreMissingWorkbooks=false and POI throws {@link WorkbookNotFoundException}
* if an external reference cannot be resolved</li>
* <li>if ignoreMissingWorkbooks=true then POI uses cached formula result
* that already exists in the main workbook</li>
* </ul>
*</p>
* @param ignore whether to ignore missing references to external workbooks
* @see <a href="https://issues.apache.org/bugzilla/show_bug.cgi?id=52575">Bug 52575 for details</a>
*/
public bool IgnoreMissingWorkbooks
{
get { return _ignoreMissingWorkbooks; }
set { _ignoreMissingWorkbooks = value; }
}
/**
* Return a collection of functions that POI can evaluate
*
* @return names of functions supported by POI
*/
public static List<String> GetSupportedFunctionNames()
{
List<String> lst = new List<String>();
lst.AddRange(FunctionEval.GetSupportedFunctionNames());
lst.AddRange(AnalysisToolPak.GetSupportedFunctionNames());
return lst;
}
/**
* Return a collection of functions that POI does not support
*
* @return names of functions NOT supported by POI
*/
public static List<String> GetNotSupportedFunctionNames()
{
List<String> lst = new List<String>();
lst.AddRange(FunctionEval.GetNotSupportedFunctionNames());
lst.AddRange(AnalysisToolPak.GetNotSupportedFunctionNames());
return lst;
}
/**
* Register a ATP function in runtime.
*
* @param name the function name
* @param func the functoin to register
* @throws IllegalArgumentException if the function is unknown or already registered.
* @since 3.8 beta6
*/
public static void RegisterFunction(String name, FreeRefFunction func)
{
AnalysisToolPak.RegisterFunction(name, func);
}
/**
* Register a function in runtime.
*
* @param name the function name
* @param func the functoin to register
* @throws IllegalArgumentException if the function is unknown or already registered.
* @since 3.8 beta6
*/
public static void RegisterFunction(String name, Functions.Function func)
{
FunctionEval.RegisterFunction(name, func);
}
public bool DebugEvaluationOutputForNextEval
{
get { return dbgEvaluationOutputForNextEval; }
set { dbgEvaluationOutputForNextEval = 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;
using System.Reflection;
using System.Collections;
using System.Globalization;
using System.Diagnostics;
namespace System.Reflection.Emit
{
internal sealed class TypeBuilderInstantiation : TypeInfo
{
public override bool IsAssignableFrom(System.Reflection.TypeInfo typeInfo)
{
if (typeInfo == null) return false;
return IsAssignableFrom(typeInfo.AsType());
}
#region Static Members
internal static Type MakeGenericType(Type type, Type[] typeArguments)
{
Debug.Assert(type != null, "this is only called from RuntimeType.MakeGenericType and TypeBuilder.MakeGenericType so 'type' cannot be null");
if (!type.IsGenericTypeDefinition)
throw new InvalidOperationException();
if (typeArguments == null)
throw new ArgumentNullException(nameof(typeArguments));
foreach (Type t in typeArguments)
{
if (t == null)
throw new ArgumentNullException(nameof(typeArguments));
}
return new TypeBuilderInstantiation(type, typeArguments);
}
#endregion
#region Private Data Members
private Type m_type;
private Type[] m_inst;
private string m_strFullQualName;
internal Hashtable m_hashtable = new Hashtable();
#endregion
#region Constructor
private TypeBuilderInstantiation(Type type, Type[] inst)
{
m_type = type;
m_inst = inst;
m_hashtable = new Hashtable();
}
#endregion
#region Object Overrides
public override String ToString()
{
return TypeNameBuilder.ToString(this, TypeNameBuilder.Format.ToString);
}
#endregion
#region MemberInfo Overrides
public override Type DeclaringType { get { return m_type.DeclaringType; } }
public override Type ReflectedType { get { return m_type.ReflectedType; } }
public override String Name { get { return m_type.Name; } }
public override Module Module { get { return m_type.Module; } }
#endregion
#region Type Overrides
public override Type MakePointerType()
{
return SymbolType.FormCompoundType("*", this, 0);
}
public override Type MakeByRefType()
{
return SymbolType.FormCompoundType("&", this, 0);
}
public override Type MakeArrayType()
{
return SymbolType.FormCompoundType("[]", this, 0);
}
public override Type MakeArrayType(int rank)
{
if (rank <= 0)
throw new IndexOutOfRangeException();
string comma = "";
for (int i = 1; i < rank; i++)
comma += ",";
string s = String.Format(CultureInfo.InvariantCulture, "[{0}]", comma);
return SymbolType.FormCompoundType(s, this, 0);
}
public override Guid GUID { get { throw new NotSupportedException(); } }
public override Object InvokeMember(String name, BindingFlags invokeAttr, Binder binder, Object target, Object[] args, ParameterModifier[] modifiers, CultureInfo culture, String[] namedParameters) { throw new NotSupportedException(); }
public override Assembly Assembly { get { return m_type.Assembly; } }
public override RuntimeTypeHandle TypeHandle { get { throw new NotSupportedException(); } }
public override String FullName
{
get
{
if (m_strFullQualName == null)
m_strFullQualName = TypeNameBuilder.ToString(this, TypeNameBuilder.Format.FullName);
return m_strFullQualName;
}
}
public override String Namespace { get { return m_type.Namespace; } }
public override String AssemblyQualifiedName { get { return TypeNameBuilder.ToString(this, TypeNameBuilder.Format.AssemblyQualifiedName); } }
private Type Substitute(Type[] substitutes)
{
Type[] inst = GetGenericArguments();
Type[] instSubstituted = new Type[inst.Length];
for (int i = 0; i < instSubstituted.Length; i++)
{
Type t = inst[i];
if (t is TypeBuilderInstantiation)
{
instSubstituted[i] = (t as TypeBuilderInstantiation).Substitute(substitutes);
}
else if (t is GenericTypeParameterBuilder)
{
// Substitute
instSubstituted[i] = substitutes[t.GenericParameterPosition];
}
else
{
instSubstituted[i] = t;
}
}
return GetGenericTypeDefinition().MakeGenericType(instSubstituted);
}
public override Type BaseType
{
// B<A,B,C>
// D<T,S> : B<S,List<T>,char>
// D<string,int> : B<int,List<string>,char>
// D<S,T> : B<T,List<S>,char>
// D<S,string> : B<string,List<S>,char>
get
{
Type typeBldrBase = m_type.BaseType;
if (typeBldrBase == null)
return null;
TypeBuilderInstantiation typeBldrBaseAs = typeBldrBase as TypeBuilderInstantiation;
if (typeBldrBaseAs == null)
return typeBldrBase;
return typeBldrBaseAs.Substitute(GetGenericArguments());
}
}
protected override ConstructorInfo GetConstructorImpl(BindingFlags bindingAttr, Binder binder, CallingConventions callConvention, Type[] types, ParameterModifier[] modifiers) { throw new NotSupportedException(); }
public override ConstructorInfo[] GetConstructors(BindingFlags bindingAttr) { throw new NotSupportedException(); }
protected override MethodInfo GetMethodImpl(String name, BindingFlags bindingAttr, Binder binder, CallingConventions callConvention, Type[] types, ParameterModifier[] modifiers) { throw new NotSupportedException(); }
public override MethodInfo[] GetMethods(BindingFlags bindingAttr) { throw new NotSupportedException(); }
public override FieldInfo GetField(String name, BindingFlags bindingAttr) { throw new NotSupportedException(); }
public override FieldInfo[] GetFields(BindingFlags bindingAttr) { throw new NotSupportedException(); }
public override Type GetInterface(String name, bool ignoreCase) { throw new NotSupportedException(); }
public override Type[] GetInterfaces() { throw new NotSupportedException(); }
public override EventInfo GetEvent(String name, BindingFlags bindingAttr) { throw new NotSupportedException(); }
public override EventInfo[] GetEvents() { throw new NotSupportedException(); }
protected override PropertyInfo GetPropertyImpl(String name, BindingFlags bindingAttr, Binder binder, Type returnType, Type[] types, ParameterModifier[] modifiers) { throw new NotSupportedException(); }
public override PropertyInfo[] GetProperties(BindingFlags bindingAttr) { throw new NotSupportedException(); }
public override Type[] GetNestedTypes(BindingFlags bindingAttr) { throw new NotSupportedException(); }
public override Type GetNestedType(String name, BindingFlags bindingAttr) { throw new NotSupportedException(); }
public override MemberInfo[] GetMember(String name, MemberTypes type, BindingFlags bindingAttr) { throw new NotSupportedException(); }
public override InterfaceMapping GetInterfaceMap(Type interfaceType) { throw new NotSupportedException(); }
public override EventInfo[] GetEvents(BindingFlags bindingAttr) { throw new NotSupportedException(); }
public override MemberInfo[] GetMembers(BindingFlags bindingAttr) { throw new NotSupportedException(); }
protected override TypeAttributes GetAttributeFlagsImpl() { return m_type.Attributes; }
public override bool IsTypeDefinition => false;
public override bool IsSZArray => false;
protected override bool IsArrayImpl() { return false; }
protected override bool IsByRefImpl() { return false; }
protected override bool IsPointerImpl() { return false; }
protected override bool IsPrimitiveImpl() { return false; }
protected override bool IsCOMObjectImpl() { return false; }
public override Type GetElementType() { throw new NotSupportedException(); }
protected override bool HasElementTypeImpl() { return false; }
public override Type UnderlyingSystemType { get { return this; } }
public override Type[] GetGenericArguments() { return m_inst; }
public override bool IsGenericTypeDefinition { get { return false; } }
public override bool IsGenericType { get { return true; } }
public override bool IsConstructedGenericType { get { return true; } }
public override bool IsGenericParameter { get { return false; } }
public override int GenericParameterPosition { get { throw new InvalidOperationException(); } }
protected override bool IsValueTypeImpl() { return m_type.IsValueType; }
public override bool ContainsGenericParameters
{
get
{
for (int i = 0; i < m_inst.Length; i++)
{
if (m_inst[i].ContainsGenericParameters)
return true;
}
return false;
}
}
public override MethodBase DeclaringMethod { get { return null; } }
public override Type GetGenericTypeDefinition() { return m_type; }
public override Type MakeGenericType(params Type[] inst) { throw new InvalidOperationException(SR.Arg_NotGenericTypeDefinition); }
public override bool IsAssignableFrom(Type c) { throw new NotSupportedException(); }
public override bool IsSubclassOf(Type c)
{
throw new NotSupportedException();
}
#endregion
#region ICustomAttributeProvider Implementation
public override Object[] GetCustomAttributes(bool inherit) { throw new NotSupportedException(); }
public override Object[] GetCustomAttributes(Type attributeType, bool inherit) { throw new NotSupportedException(); }
public override bool IsDefined(Type attributeType, bool inherit) { throw new NotSupportedException(); }
#endregion
}
}
| |
// Unity built-in shader source. Copyright (c) 2016 Unity Technologies. MIT license (see license.txt)
using System;
using UnityEngine;
namespace UnityEditor
{
internal class StandardShaderGUIXRay : ShaderGUI
{
private enum WorkflowMode
{
Specular,
Metallic,
Dielectric
}
public enum BlendMode
{
Opaque,
Cutout,
Fade, // Old school alpha-blending mode, fresnel does not affect amount of transparency
Transparent // Physically plausible transparency mode, implemented as alpha pre-multiply
}
public enum SmoothnessMapChannel
{
SpecularMetallicAlpha,
AlbedoAlpha,
}
private static class Styles
{
public static GUIContent uvSetLabel = new GUIContent("UV Set");
public static GUIContent albedoText = new GUIContent("Albedo", "Albedo (RGB) and Transparency (A)");
public static GUIContent alphaCutoffText = new GUIContent("Alpha Cutoff", "Threshold for alpha cutoff");
public static GUIContent specularMapText = new GUIContent("Specular", "Specular (RGB) and Smoothness (A)");
public static GUIContent metallicMapText = new GUIContent("Metallic", "Metallic (R) and Smoothness (A)");
public static GUIContent smoothnessText = new GUIContent("Smoothness", "Smoothness value");
public static GUIContent smoothnessScaleText = new GUIContent("Smoothness", "Smoothness scale factor");
public static GUIContent smoothnessMapChannelText = new GUIContent("Source", "Smoothness texture and channel");
public static GUIContent highlightsText = new GUIContent("Specular Highlights", "Specular Highlights");
public static GUIContent reflectionsText = new GUIContent("Reflections", "Glossy Reflections");
public static GUIContent normalMapText = new GUIContent("Normal Map", "Normal Map");
public static GUIContent heightMapText = new GUIContent("Height Map", "Height Map (G)");
public static GUIContent occlusionText = new GUIContent("Occlusion", "Occlusion (G)");
public static GUIContent emissionText = new GUIContent("Color", "Emission (RGB)");
public static GUIContent detailMaskText = new GUIContent("Detail Mask", "Mask for Secondary Maps (A)");
public static GUIContent detailAlbedoText = new GUIContent("Detail Albedo x2", "Albedo (RGB) multiplied by 2");
public static GUIContent detailNormalMapText = new GUIContent("Normal Map", "Normal Map");
public static string xrayThickness = "XRay Thickness";
public static string xrayIntensity = "XRay Intensity";
public static string xrayColor = "XRay Color";
public static string xrayInverseColor = "XRay Inverse Color";
public static string xrayAlbedoIntensity = "XRay Albedo Intensity";
public static string xrayIntersectionLength = "XRay Intersection Length";
public static string xraysText = "XRay Settings";
public static string primaryMapsText = "Main Maps";
public static string secondaryMapsText = "Secondary Maps";
public static string forwardText = "Forward Rendering Options";
public static string renderingMode = "Rendering Mode";
public static string advancedText = "Advanced Options";
public static GUIContent emissiveWarning = new GUIContent("Emissive value is animated but the material has not been configured to support emissive. Please make sure the material itself has some amount of emissive.");
public static readonly string[] blendNames = Enum.GetNames(typeof(BlendMode));
}
MaterialProperty blendMode = null;
MaterialProperty albedoMap = null;
MaterialProperty albedoColor = null;
MaterialProperty alphaCutoff = null;
MaterialProperty specularMap = null;
MaterialProperty specularColor = null;
MaterialProperty metallicMap = null;
MaterialProperty metallic = null;
MaterialProperty smoothness = null;
MaterialProperty smoothnessScale = null;
MaterialProperty smoothnessMapChannel = null;
MaterialProperty highlights = null;
MaterialProperty reflections = null;
MaterialProperty bumpScale = null;
MaterialProperty bumpMap = null;
MaterialProperty occlusionStrength = null;
MaterialProperty occlusionMap = null;
MaterialProperty heigtMapScale = null;
MaterialProperty heightMap = null;
MaterialProperty emissionColorForRendering = null;
MaterialProperty emissionMap = null;
MaterialProperty detailMask = null;
MaterialProperty detailAlbedoMap = null;
MaterialProperty detailNormalMapScale = null;
MaterialProperty detailNormalMap = null;
MaterialProperty uvSetSecondary = null;
MaterialProperty xrayThickness = null;
MaterialProperty xrayIntensity = null;
MaterialProperty xrayColor = null;
MaterialProperty xrayInverseColor = null;
MaterialProperty xrayAlbedoIntensity = null;
MaterialProperty xrayIntersectionLength = null;
MaterialEditor m_MaterialEditor;
WorkflowMode m_WorkflowMode = WorkflowMode.Specular;
ColorPickerHDRConfig m_ColorPickerHDRConfig = new ColorPickerHDRConfig(0f, 99f, 1 / 99f, 3f);
bool m_FirstTimeApply = true;
public void FindProperties(MaterialProperty[] props)
{
blendMode = FindProperty("_Mode", props);
albedoMap = FindProperty("_MainTex", props);
albedoColor = FindProperty("_Color", props);
alphaCutoff = FindProperty("_Cutoff", props);
specularMap = FindProperty("_SpecGlossMap", props, false);
specularColor = FindProperty("_SpecColor", props, false);
metallicMap = FindProperty("_MetallicGlossMap", props, false);
metallic = FindProperty("_Metallic", props, false);
if (specularMap != null && specularColor != null)
m_WorkflowMode = WorkflowMode.Specular;
else if (metallicMap != null && metallic != null)
m_WorkflowMode = WorkflowMode.Metallic;
else
m_WorkflowMode = WorkflowMode.Dielectric;
smoothness = FindProperty("_Glossiness", props);
smoothnessScale = FindProperty("_GlossMapScale", props, false);
smoothnessMapChannel = FindProperty("_SmoothnessTextureChannel", props, false);
highlights = FindProperty("_SpecularHighlights", props, false);
reflections = FindProperty("_GlossyReflections", props, false);
bumpScale = FindProperty("_BumpScale", props);
bumpMap = FindProperty("_BumpMap", props);
heigtMapScale = FindProperty("_Parallax", props);
heightMap = FindProperty("_ParallaxMap", props);
occlusionStrength = FindProperty("_OcclusionStrength", props);
occlusionMap = FindProperty("_OcclusionMap", props);
emissionColorForRendering = FindProperty("_EmissionColor", props);
emissionMap = FindProperty("_EmissionMap", props);
detailMask = FindProperty("_DetailMask", props);
detailAlbedoMap = FindProperty("_DetailAlbedoMap", props);
detailNormalMapScale = FindProperty("_DetailNormalMapScale", props);
detailNormalMap = FindProperty("_DetailNormalMap", props);
uvSetSecondary = FindProperty("_UVSec", props);
xrayColor = FindProperty("_XrayColor", props);
xrayInverseColor = FindProperty("_XrayInverseColor", props);
xrayThickness = FindProperty("_XRayThickness", props);
xrayIntensity= FindProperty("_XRayIntensity", props);
xrayAlbedoIntensity = FindProperty("_XRayAlbedoIntensity", props);
xrayIntersectionLength = FindProperty("_XRayIntersectionLength", props);
}
public override void OnGUI(MaterialEditor materialEditor, MaterialProperty[] props)
{
//base.OnGUI(materialEditor, props);
FindProperties(props); // MaterialProperties can be animated so we do not cache them but fetch them every event to ensure animated values are updated correctly
m_MaterialEditor = materialEditor;
Material material = materialEditor.target as Material;
// Make sure that needed setup (ie keywords/renderqueue) are set up if we're switching some existing
// material to a standard shader.
// Do this before any GUI code has been issued to prevent layout issues in subsequent GUILayout statements (case 780071)
if (m_FirstTimeApply)
{
MaterialChanged(material, m_WorkflowMode);
m_FirstTimeApply = false;
}
ShaderPropertiesGUI(material);
}
public void ShaderPropertiesGUI(Material material)
{
// Use default labelWidth
EditorGUIUtility.labelWidth = 0f;
// Detect any changes to the material
EditorGUI.BeginChangeCheck();
{
BlendModePopup();
// Primary properties
GUILayout.Label(Styles.primaryMapsText, EditorStyles.boldLabel);
DoAlbedoArea(material);
DoSpecularMetallicArea();
m_MaterialEditor.TexturePropertySingleLine(Styles.normalMapText, bumpMap, bumpMap.textureValue != null ? bumpScale : null);
m_MaterialEditor.TexturePropertySingleLine(Styles.heightMapText, heightMap, heightMap.textureValue != null ? heigtMapScale : null);
m_MaterialEditor.TexturePropertySingleLine(Styles.occlusionText, occlusionMap, occlusionMap.textureValue != null ? occlusionStrength : null);
m_MaterialEditor.TexturePropertySingleLine(Styles.detailMaskText, detailMask);
DoEmissionArea(material);
EditorGUI.BeginChangeCheck();
m_MaterialEditor.TextureScaleOffsetProperty(albedoMap);
if (EditorGUI.EndChangeCheck())
emissionMap.textureScaleAndOffset = albedoMap.textureScaleAndOffset; // Apply the main texture scale and offset to the emission texture as well, for Enlighten's sake
EditorGUILayout.Space();
// Secondary properties
GUILayout.Label(Styles.secondaryMapsText, EditorStyles.boldLabel);
m_MaterialEditor.TexturePropertySingleLine(Styles.detailAlbedoText, detailAlbedoMap);
m_MaterialEditor.TexturePropertySingleLine(Styles.detailNormalMapText, detailNormalMap, detailNormalMapScale);
m_MaterialEditor.TextureScaleOffsetProperty(detailAlbedoMap);
m_MaterialEditor.ShaderProperty(uvSetSecondary, Styles.uvSetLabel.text);
// Third properties
GUILayout.Label(Styles.forwardText, EditorStyles.boldLabel);
if (highlights != null)
m_MaterialEditor.ShaderProperty(highlights, Styles.highlightsText);
if (reflections != null)
m_MaterialEditor.ShaderProperty(reflections, Styles.reflectionsText);
EditorGUILayout.Space();
// xray properties
GUILayout.Label(Styles.xraysText, EditorStyles.boldLabel);
m_MaterialEditor.ShaderProperty(xrayThickness, Styles.xrayThickness);
m_MaterialEditor.ShaderProperty(xrayIntensity, Styles.xrayIntensity);
m_MaterialEditor.ShaderProperty(xrayColor, Styles.xrayColor);
m_MaterialEditor.ShaderProperty(xrayInverseColor, Styles.xrayInverseColor);
m_MaterialEditor.ShaderProperty(xrayAlbedoIntensity, Styles.xrayInverseColor);
m_MaterialEditor.ShaderProperty(xrayIntersectionLength, Styles.xrayIntersectionLength);
}
if (EditorGUI.EndChangeCheck())
{
foreach (var obj in blendMode.targets)
MaterialChanged((Material)obj, m_WorkflowMode);
}
EditorGUILayout.Space();
GUILayout.Label(Styles.advancedText, EditorStyles.boldLabel);
m_MaterialEditor.RenderQueueField();
m_MaterialEditor.EnableInstancingField();
}
internal void DetermineWorkflow(MaterialProperty[] props)
{
if (FindProperty("_SpecGlossMap", props, false) != null && FindProperty("_SpecColor", props, false) != null)
m_WorkflowMode = WorkflowMode.Specular;
else if (FindProperty("_MetallicGlossMap", props, false) != null && FindProperty("_Metallic", props, false) != null)
m_WorkflowMode = WorkflowMode.Metallic;
else
m_WorkflowMode = WorkflowMode.Dielectric;
}
public override void AssignNewShaderToMaterial(Material material, Shader oldShader, Shader newShader)
{
// _Emission property is lost after assigning Standard shader to the material
// thus transfer it before assigning the new shader
if (material.HasProperty("_Emission"))
{
material.SetColor("_EmissionColor", material.GetColor("_Emission"));
}
base.AssignNewShaderToMaterial(material, oldShader, newShader);
if (oldShader == null || !oldShader.name.Contains("Legacy Shaders/"))
{
SetupMaterialWithBlendMode(material, (BlendMode)material.GetFloat("_Mode"));
return;
}
BlendMode blendMode = BlendMode.Opaque;
if (oldShader.name.Contains("/Transparent/Cutout/"))
{
blendMode = BlendMode.Cutout;
}
else if (oldShader.name.Contains("/Transparent/"))
{
// NOTE: legacy shaders did not provide physically based transparency
// therefore Fade mode
blendMode = BlendMode.Fade;
}
material.SetFloat("_Mode", (float)blendMode);
DetermineWorkflow(MaterialEditor.GetMaterialProperties(new Material[] { material }));
MaterialChanged(material, m_WorkflowMode);
}
void BlendModePopup()
{
EditorGUI.showMixedValue = blendMode.hasMixedValue;
var mode = (BlendMode)blendMode.floatValue;
EditorGUI.BeginChangeCheck();
mode = (BlendMode)EditorGUILayout.Popup(Styles.renderingMode, (int)mode, Styles.blendNames);
if (EditorGUI.EndChangeCheck())
{
m_MaterialEditor.RegisterPropertyChangeUndo("Rendering Mode");
blendMode.floatValue = (float)mode;
}
EditorGUI.showMixedValue = false;
}
void DoAlbedoArea(Material material)
{
m_MaterialEditor.TexturePropertySingleLine(Styles.albedoText, albedoMap, albedoColor);
if (((BlendMode)material.GetFloat("_Mode") == BlendMode.Cutout))
{
m_MaterialEditor.ShaderProperty(alphaCutoff, Styles.alphaCutoffText.text, MaterialEditor.kMiniTextureFieldLabelIndentLevel + 1);
}
}
void DoEmissionArea(Material material)
{
// Emission for GI?
if (m_MaterialEditor.EmissionEnabledProperty())
{
bool hadEmissionTexture = emissionMap.textureValue != null;
// Texture and HDR color controls
m_MaterialEditor.TexturePropertyWithHDRColor(Styles.emissionText, emissionMap, emissionColorForRendering, m_ColorPickerHDRConfig, false);
// If texture was assigned and color was black set color to white
float brightness = emissionColorForRendering.colorValue.maxColorComponent;
if (emissionMap.textureValue != null && !hadEmissionTexture && brightness <= 0f)
emissionColorForRendering.colorValue = Color.white;
// change the GI flag and fix it up with emissive as black if necessary
m_MaterialEditor.LightmapEmissionFlagsProperty(MaterialEditor.kMiniTextureFieldLabelIndentLevel, true);
}
}
void DoSpecularMetallicArea()
{
bool hasGlossMap = false;
if (m_WorkflowMode == WorkflowMode.Specular)
{
hasGlossMap = specularMap.textureValue != null;
m_MaterialEditor.TexturePropertySingleLine(Styles.specularMapText, specularMap, hasGlossMap ? null : specularColor);
}
else if (m_WorkflowMode == WorkflowMode.Metallic)
{
hasGlossMap = metallicMap.textureValue != null;
m_MaterialEditor.TexturePropertySingleLine(Styles.metallicMapText, metallicMap, hasGlossMap ? null : metallic);
}
bool showSmoothnessScale = hasGlossMap;
if (smoothnessMapChannel != null)
{
int smoothnessChannel = (int)smoothnessMapChannel.floatValue;
if (smoothnessChannel == (int)SmoothnessMapChannel.AlbedoAlpha)
showSmoothnessScale = true;
}
int indentation = 2; // align with labels of texture properties
m_MaterialEditor.ShaderProperty(showSmoothnessScale ? smoothnessScale : smoothness, showSmoothnessScale ? Styles.smoothnessScaleText : Styles.smoothnessText, indentation);
++indentation;
if (smoothnessMapChannel != null)
m_MaterialEditor.ShaderProperty(smoothnessMapChannel, Styles.smoothnessMapChannelText, indentation);
}
public static void SetupMaterialWithBlendMode(Material material, BlendMode blendMode)
{
switch (blendMode)
{
case BlendMode.Opaque:
material.SetOverrideTag("RenderType", "");
material.SetInt("_SrcBlend", (int)UnityEngine.Rendering.BlendMode.One);
material.SetInt("_DstBlend", (int)UnityEngine.Rendering.BlendMode.Zero);
material.SetInt("_ZWrite", 1);
material.DisableKeyword("_ALPHATEST_ON");
material.DisableKeyword("_ALPHABLEND_ON");
material.DisableKeyword("_ALPHAPREMULTIPLY_ON");
material.renderQueue = -1;
break;
case BlendMode.Cutout:
material.SetOverrideTag("RenderType", "TransparentCutout");
material.SetInt("_SrcBlend", (int)UnityEngine.Rendering.BlendMode.One);
material.SetInt("_DstBlend", (int)UnityEngine.Rendering.BlendMode.Zero);
material.SetInt("_ZWrite", 1);
material.EnableKeyword("_ALPHATEST_ON");
material.DisableKeyword("_ALPHABLEND_ON");
material.DisableKeyword("_ALPHAPREMULTIPLY_ON");
material.renderQueue = (int)UnityEngine.Rendering.RenderQueue.AlphaTest;
break;
case BlendMode.Fade:
material.SetOverrideTag("RenderType", "Transparent");
material.SetInt("_SrcBlend", (int)UnityEngine.Rendering.BlendMode.SrcAlpha);
material.SetInt("_DstBlend", (int)UnityEngine.Rendering.BlendMode.OneMinusSrcAlpha);
material.SetInt("_ZWrite", 0);
material.DisableKeyword("_ALPHATEST_ON");
material.EnableKeyword("_ALPHABLEND_ON");
material.DisableKeyword("_ALPHAPREMULTIPLY_ON");
material.renderQueue = (int)UnityEngine.Rendering.RenderQueue.Transparent;
break;
case BlendMode.Transparent:
material.SetOverrideTag("RenderType", "Transparent");
material.SetInt("_SrcBlend", (int)UnityEngine.Rendering.BlendMode.One);
material.SetInt("_DstBlend", (int)UnityEngine.Rendering.BlendMode.OneMinusSrcAlpha);
material.SetInt("_ZWrite", 0);
material.DisableKeyword("_ALPHATEST_ON");
material.DisableKeyword("_ALPHABLEND_ON");
material.EnableKeyword("_ALPHAPREMULTIPLY_ON");
material.renderQueue = (int)UnityEngine.Rendering.RenderQueue.Transparent;
break;
}
}
static SmoothnessMapChannel GetSmoothnessMapChannel(Material material)
{
int ch = (int)material.GetFloat("_SmoothnessTextureChannel");
if (ch == (int)SmoothnessMapChannel.AlbedoAlpha)
return SmoothnessMapChannel.AlbedoAlpha;
else
return SmoothnessMapChannel.SpecularMetallicAlpha;
}
static void SetMaterialKeywords(Material material, WorkflowMode workflowMode)
{
// Note: keywords must be based on Material value not on MaterialProperty due to multi-edit & material animation
// (MaterialProperty value might come from renderer material property block)
SetKeyword(material, "_NORMALMAP", material.GetTexture("_BumpMap") || material.GetTexture("_DetailNormalMap"));
if (workflowMode == WorkflowMode.Specular)
SetKeyword(material, "_SPECGLOSSMAP", material.GetTexture("_SpecGlossMap"));
else if (workflowMode == WorkflowMode.Metallic)
SetKeyword(material, "_METALLICGLOSSMAP", material.GetTexture("_MetallicGlossMap"));
SetKeyword(material, "_PARALLAXMAP", material.GetTexture("_ParallaxMap"));
SetKeyword(material, "_DETAIL_MULX2", material.GetTexture("_DetailAlbedoMap") || material.GetTexture("_DetailNormalMap"));
// A material's GI flag internally keeps track of whether emission is enabled at all, it's enabled but has no effect
// or is enabled and may be modified at runtime. This state depends on the values of the current flag and emissive color.
// The fixup routine makes sure that the material is in the correct state if/when changes are made to the mode or color.
MaterialEditor.FixupEmissiveFlag(material);
bool shouldEmissionBeEnabled = (material.globalIlluminationFlags & MaterialGlobalIlluminationFlags.EmissiveIsBlack) == 0;
SetKeyword(material, "_EMISSION", shouldEmissionBeEnabled);
if (material.HasProperty("_SmoothnessTextureChannel"))
{
SetKeyword(material, "_SMOOTHNESS_TEXTURE_ALBEDO_CHANNEL_A", GetSmoothnessMapChannel(material) == SmoothnessMapChannel.AlbedoAlpha);
}
}
static void MaterialChanged(Material material, WorkflowMode workflowMode)
{
SetupMaterialWithBlendMode(material, (BlendMode)material.GetFloat("_Mode"));
SetMaterialKeywords(material, workflowMode);
}
static void SetKeyword(Material m, string keyword, bool state)
{
if (state)
m.EnableKeyword(keyword);
else
m.DisableKeyword(keyword);
}
}
} // namespace UnityEditor
| |
// 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.IO;
using System.Xml;
using System.Xml.Linq;
using Microsoft.Test.ModuleCore;
namespace CoreXml.Test.XLinq
{
public partial class FunctionalTests : TestModule
{
public partial class SDMSamplesTests : XLinqTestCase
{
public partial class SDM_LoadSave : XLinqTestCase
{
/// <summary>
/// Test loading a document from an XmlReader.
/// </summary>
/// <param name="context"></param>
/// <returns></returns>
//[Variation(Desc = "DocumentLoadFromXmlReader")]
public void DocumentLoadFromXmlReader()
{
// Null reader not allowed.
try
{
XDocument.Load((XmlReader)null);
Validate.ExpectedThrow(typeof(ArgumentNullException));
}
catch (Exception ex)
{
Validate.Catch(ex, typeof(ArgumentNullException));
}
// Extra content at end of reader.
StringReader stringReader = new StringReader("<x/><y/>");
using (XmlReader xmlReader = XmlReader.Create(stringReader))
{
try
{
XDocument.Load(xmlReader);
Validate.ExpectedThrow(typeof(XmlException));
}
catch (Exception ex)
{
Validate.Catch(ex, typeof(XmlException));
}
}
// Empty content.
stringReader = new StringReader("");
using (XmlReader xmlReader = XmlReader.Create(stringReader))
{
try
{
XDocument.Load(xmlReader);
Validate.ExpectedThrow(typeof(XmlException));
}
catch (Exception ex)
{
Validate.Catch(ex, typeof(XmlException));
}
}
// No root element.
stringReader = new StringReader("<!-- comment -->");
using (XmlReader xmlReader = XmlReader.Create(stringReader))
{
try
{
XDocument.Load(xmlReader);
Validate.ExpectedThrow(typeof(XmlException));
}
catch (Exception ex)
{
Validate.Catch(ex, typeof(XmlException));
}
}
// Reader mispositioned, so not at eof when done
stringReader = new StringReader("<x></x>");
using (XmlReader xmlReader = XmlReader.Create(stringReader))
{
// Position the reader on the end element.
xmlReader.Read();
xmlReader.Read();
try
{
XDocument.Load(xmlReader);
Validate.ExpectedThrow(typeof(InvalidOperationException));
}
catch (Exception ex)
{
Validate.Catch(ex, typeof(InvalidOperationException));
}
}
// Reader mispositioned, so empty root when done
stringReader = new StringReader("<x></x>");
using (XmlReader xmlReader = XmlReader.Create(stringReader))
{
// Position the reader at eof.
xmlReader.Read();
xmlReader.Read();
xmlReader.Read();
try
{
XDocument.Load(xmlReader);
Validate.ExpectedThrow(typeof(InvalidOperationException));
}
catch (Exception ex)
{
Validate.Catch(ex, typeof(InvalidOperationException));
}
}
}
/// <summary>
/// Tests the Save overloads on document, that write to an XmlWriter.
/// </summary>
/// <param name="context"></param>
/// <returns></returns>
//[Variation(Desc = "DocumentSaveToXmlWriter")]
public void DocumentSaveToXmlWriter()
{
XDocument ee = new XDocument();
try
{
ee.Save((XmlWriter)null);
Validate.ExpectedThrow(typeof(ArgumentNullException));
}
catch (Exception ex)
{
Validate.Catch(ex, typeof(ArgumentNullException));
}
}
/// <summary>
/// Tests WriteTo on document.
/// </summary>
/// <param name="context"></param>
/// <returns></returns>
//[Variation(Desc = "DocumentWriteTo")]
public void DocumentWriteTo()
{
XDocument ee = new XDocument();
try
{
ee.WriteTo(null);
Validate.ExpectedThrow(typeof(ArgumentNullException));
}
catch (Exception ex)
{
Validate.Catch(ex, typeof(ArgumentNullException));
}
}
/// <summary>
/// Test loading an element from an XmlReader.
/// </summary>
/// <param name="context"></param>
/// <returns></returns>
//[Variation(Desc = "ElementLoadFromXmlReader")]
public void ElementLoadFromXmlReader()
{
// Null reader not allowed.
try
{
XElement.Load((XmlReader)null);
Validate.ExpectedThrow(typeof(ArgumentNullException));
}
catch (Exception ex)
{
Validate.Catch(ex, typeof(ArgumentNullException));
}
// Extra stuff in xml after the element is not allowed
StringReader reader = new StringReader("<abc><def/></abc>");
XmlReader xmlreader = XmlReader.Create(reader);
xmlreader.Read();
xmlreader.Read(); // position on <def>
try
{
XElement.Load(xmlreader);
Validate.ExpectedThrow(typeof(InvalidOperationException));
}
catch (Exception ex)
{
Validate.Catch(ex, typeof(InvalidOperationException));
}
reader.Dispose();
xmlreader.Dispose();
}
/// <summary>
/// Tests the Save overloads on element, that write to an XmlWriter.
/// </summary>
/// <param name="context"></param>
/// <returns></returns>
//[Variation(Desc = "ElementSaveToXmlWriter")]
public void ElementSaveToXmlWriter()
{
XElement ee = new XElement("x");
try
{
ee.Save((XmlWriter)null);
Validate.ExpectedThrow(typeof(ArgumentNullException));
}
catch (Exception ex)
{
Validate.Catch(ex, typeof(ArgumentNullException));
}
}
/// <summary>
/// Gets the full path of the RuntimeTestXml directory, allowing for the
/// possibility of being run from the VS build (bin\debug, etc).
/// </summary>
/// <returns></returns>
internal string GetTestXmlDirectory()
{
const string TestXmlDirectoryName = "RuntimeTestXml";
string baseDir = Path.Combine(XLinqTestCase.RootPath, @"TestData\XLinq\");
string dir = Path.Combine(baseDir, TestXmlDirectoryName);
return dir;
}
/// <summary>
/// Gets the filenames of all files in the RuntimeTestXml directory.
/// We use all files we find in a directory with a known name and location.
/// </summary>
/// <returns></returns>
internal string[] GetTestXmlFilenames()
{
string[] filenames = new string[] {
GetTestXmlFilename("LoadSave0.xml"),
GetTestXmlFilename("LoadSave1.xml"),
GetTestXmlFilename("LoadSave2.xml"),
GetTestXmlFilename("LoadSave3.xml"),
GetTestXmlFilename("LoadSave4.xml")};
if (filenames.Length == 0)
{
throw new TestFailedException("No files in xml directory for tests");
}
return filenames;
}
/// <summary>
/// Gets the filenames of all files in the RuntimeTestXml directory.
/// We use all files we find in a directory with a known name and location.
/// </summary>
/// <returns></returns>
internal string GetTestXmlFilename(string filename)
{
string directory = GetTestXmlDirectory();
string fullName = Path.Combine(directory, filename);
return fullName;
}
}
}
}
}
| |
// 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.Net.Http.Headers;
using System.Net.Sockets;
using System.Net.Test.Common;
using System.Threading.Tasks;
using Xunit;
using Xunit.Abstractions;
namespace System.Net.Http.Functional.Tests
{
using Configuration = System.Net.Test.Common.Configuration;
public abstract class HttpClientHandlerTest_AutoRedirect : HttpClientHandlerTestBase
{
readonly ITestOutputHelper _output;
private const string ExpectedContent = "Test content";
private const string Username = "testuser";
private const string Password = "password";
private readonly NetworkCredential _credential = new NetworkCredential(Username, Password);
public static readonly object[][] EchoServers = Configuration.Http.EchoServers;
public static readonly object[][] RedirectStatusCodes = {
new object[] { 300 },
new object[] { 301 },
new object[] { 302 },
new object[] { 303 },
new object[] { 307 },
new object[] { 308 }
};
public static readonly object[][] RedirectStatusCodesOldMethodsNewMethods = {
new object[] { 300, "GET", "GET" },
new object[] { 300, "POST", "GET" },
new object[] { 300, "HEAD", "HEAD" },
new object[] { 301, "GET", "GET" },
new object[] { 301, "POST", "GET" },
new object[] { 301, "HEAD", "HEAD" },
new object[] { 302, "GET", "GET" },
new object[] { 302, "POST", "GET" },
new object[] { 302, "HEAD", "HEAD" },
new object[] { 303, "GET", "GET" },
new object[] { 303, "POST", "GET" },
new object[] { 303, "HEAD", "HEAD" },
new object[] { 307, "GET", "GET" },
new object[] { 307, "POST", "POST" },
new object[] { 307, "HEAD", "HEAD" },
new object[] { 308, "GET", "GET" },
new object[] { 308, "POST", "POST" },
new object[] { 308, "HEAD", "HEAD" },
};
public HttpClientHandlerTest_AutoRedirect(ITestOutputHelper output)
{
_output = output;
}
[OuterLoop("Uses external server")]
[Theory, MemberData(nameof(RedirectStatusCodes))]
public async Task GetAsync_AllowAutoRedirectFalse_RedirectFromHttpToHttp_StatusCodeRedirect(int statusCode)
{
if (statusCode == 308 && (PlatformDetection.IsFullFramework || IsWinHttpHandler && PlatformDetection.WindowsVersion < 10))
{
// 308 redirects are not supported on old versions of WinHttp, or on .NET Framework.
return;
}
HttpClientHandler handler = CreateHttpClientHandler();
handler.AllowAutoRedirect = false;
using (var client = new HttpClient(handler))
{
Uri uri = Configuration.Http.RedirectUriForDestinationUri(
secure: false,
statusCode: statusCode,
destinationUri: Configuration.Http.RemoteEchoServer,
hops: 1);
_output.WriteLine("Uri: {0}", uri);
using (HttpResponseMessage response = await client.GetAsync(uri))
{
Assert.Equal(statusCode, (int)response.StatusCode);
Assert.Equal(uri, response.RequestMessage.RequestUri);
}
}
}
[Theory, MemberData(nameof(RedirectStatusCodesOldMethodsNewMethods))]
public async Task AllowAutoRedirect_True_ValidateNewMethodUsedOnRedirection(
int statusCode, string oldMethod, string newMethod)
{
if (IsCurlHandler && statusCode == 300 && oldMethod == "POST")
{
// Known behavior: curl does not change method to "GET"
// https://github.com/dotnet/corefx/issues/26434
newMethod = "POST";
}
if (statusCode == 308 && (PlatformDetection.IsFullFramework || IsWinHttpHandler && PlatformDetection.WindowsVersion < 10))
{
// 308 redirects are not supported on old versions of WinHttp, or on .NET Framework.
return;
}
HttpClientHandler handler = CreateHttpClientHandler();
using (var client = new HttpClient(handler))
{
await LoopbackServer.CreateServerAsync(async (origServer, origUrl) =>
{
var request = new HttpRequestMessage(new HttpMethod(oldMethod), origUrl);
Task<HttpResponseMessage> getResponseTask = client.SendAsync(request);
await LoopbackServer.CreateServerAsync(async (redirServer, redirUrl) =>
{
// Original URL will redirect to a different URL
Task<List<string>> serverTask = origServer.AcceptConnectionSendResponseAndCloseAsync((HttpStatusCode)statusCode, $"Location: {redirUrl}\r\n");
await Task.WhenAny(getResponseTask, serverTask);
Assert.False(getResponseTask.IsCompleted, $"{getResponseTask.Status}: {getResponseTask.Exception}");
await serverTask;
// Redirected URL answers with success
serverTask = redirServer.AcceptConnectionSendResponseAndCloseAsync();
await TestHelper.WhenAllCompletedOrAnyFailed(getResponseTask, serverTask);
List<string> receivedRequest = await serverTask;
string[] statusLineParts = receivedRequest[0].Split(' ');
using (HttpResponseMessage response = await getResponseTask)
{
Assert.Equal(200, (int)response.StatusCode);
Assert.Equal(newMethod, statusLineParts[0]);
}
});
});
}
}
[ActiveIssue(30063, TargetFrameworkMonikers.Uap)] // fails due to TE header
[Theory]
[InlineData(300)]
[InlineData(301)]
[InlineData(302)]
[InlineData(303)]
public async Task AllowAutoRedirect_True_PostToGetDoesNotSendTE(int statusCode)
{
if (IsCurlHandler && statusCode == 300)
{
// ISSUE #26434:
// CurlHandler doesn't change POST to GET for 300 response (see above test).
return;
}
if (IsWinHttpHandler)
{
// ISSUE #27440:
// This test occasionally fails on WinHttpHandler.
// Likely this is due to the way the loopback server is sending the response before reading the entire request.
// We should change the server behavior here.
return;
}
HttpClientHandler handler = CreateHttpClientHandler();
using (var client = new HttpClient(handler))
{
await LoopbackServer.CreateServerAsync(async (origServer, origUrl) =>
{
var request = new HttpRequestMessage(HttpMethod.Post, origUrl);
request.Content = new StringContent(ExpectedContent);
request.Headers.TransferEncodingChunked = true;
Task<HttpResponseMessage> getResponseTask = client.SendAsync(request);
await LoopbackServer.CreateServerAsync(async (redirServer, redirUrl) =>
{
// Original URL will redirect to a different URL
Task serverTask = origServer.AcceptConnectionAsync(async connection =>
{
// Send Connection: close so the client will close connection after request is sent,
// meaning we can just read to the end to get the content
await connection.ReadRequestHeaderAndSendResponseAsync((HttpStatusCode)statusCode, $"Location: {redirUrl}\r\nConnection: close\r\n");
connection.Socket.Shutdown(SocketShutdown.Send);
await connection.Reader.ReadToEndAsync();
});
await Task.WhenAny(getResponseTask, serverTask);
Assert.False(getResponseTask.IsCompleted, $"{getResponseTask.Status}: {getResponseTask.Exception}");
await serverTask;
// Redirected URL answers with success
List<string> receivedRequest = null;
string receivedContent = null;
Task serverTask2 = redirServer.AcceptConnectionAsync(async connection =>
{
// Send Connection: close so the client will close connection after request is sent,
// meaning we can just read to the end to get the content
receivedRequest = await connection.ReadRequestHeaderAndSendResponseAsync(additionalHeaders: "Connection: close\r\n");
connection.Socket.Shutdown(SocketShutdown.Send);
receivedContent = await connection.Reader.ReadToEndAsync();
});
await TestHelper.WhenAllCompletedOrAnyFailed(getResponseTask, serverTask2);
string[] statusLineParts = receivedRequest[0].Split(' ');
Assert.Equal("GET", statusLineParts[0]);
Assert.DoesNotContain(receivedRequest, line => line.StartsWith("Transfer-Encoding"));
Assert.DoesNotContain(receivedRequest, line => line.StartsWith("Content-Length"));
using (HttpResponseMessage response = await getResponseTask)
{
Assert.Equal(200, (int)response.StatusCode);
}
});
});
}
}
[OuterLoop("Uses external server")]
[Theory, MemberData(nameof(RedirectStatusCodes))]
public async Task GetAsync_AllowAutoRedirectTrue_RedirectFromHttpToHttp_StatusCodeOK(int statusCode)
{
if (statusCode == 308 && (PlatformDetection.IsFullFramework || IsWinHttpHandler && PlatformDetection.WindowsVersion < 10))
{
// 308 redirects are not supported on old versions of WinHttp, or on .NET Framework.
return;
}
HttpClientHandler handler = CreateHttpClientHandler();
handler.AllowAutoRedirect = true;
using (var client = new HttpClient(handler))
{
Uri uri = Configuration.Http.RedirectUriForDestinationUri(
secure: false,
statusCode: statusCode,
destinationUri: Configuration.Http.RemoteEchoServer,
hops: 1);
_output.WriteLine("Uri: {0}", uri);
using (HttpResponseMessage response = await client.GetAsync(uri))
{
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
Assert.Equal(Configuration.Http.RemoteEchoServer, response.RequestMessage.RequestUri);
}
}
}
[OuterLoop("Uses external server")]
[Fact]
public async Task GetAsync_AllowAutoRedirectTrue_RedirectFromHttpToHttps_StatusCodeOK()
{
HttpClientHandler handler = CreateHttpClientHandler();
handler.AllowAutoRedirect = true;
using (var client = new HttpClient(handler))
{
Uri uri = Configuration.Http.RedirectUriForDestinationUri(
secure: false,
statusCode: 302,
destinationUri: Configuration.Http.SecureRemoteEchoServer,
hops: 1);
_output.WriteLine("Uri: {0}", uri);
using (HttpResponseMessage response = await client.GetAsync(uri))
{
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
Assert.Equal(Configuration.Http.SecureRemoteEchoServer, response.RequestMessage.RequestUri);
}
}
}
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, ".NET Framework allows HTTPS to HTTP redirection")]
[OuterLoop("Uses external server")]
[Fact]
public async Task GetAsync_AllowAutoRedirectTrue_RedirectFromHttpsToHttp_StatusCodeRedirect()
{
HttpClientHandler handler = CreateHttpClientHandler();
handler.AllowAutoRedirect = true;
using (var client = new HttpClient(handler))
{
Uri uri = Configuration.Http.RedirectUriForDestinationUri(
secure: true,
statusCode: 302,
destinationUri: Configuration.Http.RemoteEchoServer,
hops: 1);
_output.WriteLine("Uri: {0}", uri);
using (HttpResponseMessage response = await client.GetAsync(uri))
{
Assert.Equal(HttpStatusCode.Redirect, response.StatusCode);
Assert.Equal(uri, response.RequestMessage.RequestUri);
}
}
}
[Fact]
public async Task GetAsync_AllowAutoRedirectTrue_RedirectWithoutLocation_ReturnsOriginalResponse()
{
// [ActiveIssue(24819, TestPlatforms.Windows)]
if (PlatformDetection.IsWindows && PlatformDetection.IsNetCore && !UseSocketsHttpHandler)
{
return;
}
HttpClientHandler handler = CreateHttpClientHandler();
handler.AllowAutoRedirect = true;
using (var client = new HttpClient(handler))
{
await LoopbackServer.CreateServerAsync(async (server, url) =>
{
Task<HttpResponseMessage> getTask = client.GetAsync(url);
Task<List<string>> serverTask = server.AcceptConnectionSendResponseAndCloseAsync(HttpStatusCode.Found);
await TestHelper.WhenAllCompletedOrAnyFailed(getTask, serverTask);
using (HttpResponseMessage response = await getTask)
{
Assert.Equal(302, (int)response.StatusCode);
}
});
}
}
[ActiveIssue(32647, TargetFrameworkMonikers.Uap)]
[OuterLoop("Uses external server")]
[Fact]
public async Task GetAsync_AllowAutoRedirectTrue_RedirectToUriWithParams_RequestMsgUriSet()
{
HttpClientHandler handler = CreateHttpClientHandler();
handler.AllowAutoRedirect = true;
Uri targetUri = Configuration.Http.BasicAuthUriForCreds(secure: false, userName: Username, password: Password);
using (var client = new HttpClient(handler))
{
Uri uri = Configuration.Http.RedirectUriForDestinationUri(
secure: false,
statusCode: 302,
destinationUri: targetUri,
hops: 1);
_output.WriteLine("Uri: {0}", uri);
using (HttpResponseMessage response = await client.GetAsync(uri))
{
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
Assert.Equal(targetUri, response.RequestMessage.RequestUri);
}
}
}
[SkipOnTargetFramework(TargetFrameworkMonikers.Uap, "Not currently supported on UAP")]
[OuterLoop("Uses external server")]
[Theory]
[InlineData(3, 2)]
[InlineData(3, 3)]
[InlineData(3, 4)]
public async Task GetAsync_MaxAutomaticRedirectionsNServerHops_ThrowsIfTooMany(int maxHops, int hops)
{
if (IsWinHttpHandler && !PlatformDetection.IsWindows10Version1703OrGreater)
{
// Skip this test if using WinHttpHandler but on a release prior to Windows 10 Creators Update.
_output.WriteLine("Skipping test due to Windows 10 version prior to Version 1703.");
return;
}
else if (PlatformDetection.IsFullFramework)
{
// Skip this test if running on .NET Framework. Exceeding max redirections will not throw
// exception. Instead, it simply returns the 3xx response.
_output.WriteLine("Skipping test on .NET Framework due to behavior difference.");
return;
}
HttpClientHandler handler = CreateHttpClientHandler();
handler.MaxAutomaticRedirections = maxHops;
using (var client = new HttpClient(handler))
{
Task<HttpResponseMessage> t = client.GetAsync(Configuration.Http.RedirectUriForDestinationUri(
secure: false,
statusCode: 302,
destinationUri: Configuration.Http.RemoteEchoServer,
hops: hops));
if (hops <= maxHops)
{
using (HttpResponseMessage response = await t)
{
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
Assert.Equal(Configuration.Http.RemoteEchoServer, response.RequestMessage.RequestUri);
}
}
else
{
if (UseSocketsHttpHandler)
{
using (HttpResponseMessage response = await t)
{
Assert.Equal(HttpStatusCode.Redirect, response.StatusCode);
}
}
else
{
await Assert.ThrowsAsync<HttpRequestException>(() => t);
}
}
}
}
[OuterLoop("Uses external server")]
[Fact]
public async Task GetAsync_AllowAutoRedirectTrue_RedirectWithRelativeLocation()
{
HttpClientHandler handler = CreateHttpClientHandler();
handler.AllowAutoRedirect = true;
using (var client = new HttpClient(handler))
{
Uri uri = Configuration.Http.RedirectUriForDestinationUri(
secure: false,
statusCode: 302,
destinationUri: Configuration.Http.RemoteEchoServer,
hops: 1,
relative: true);
_output.WriteLine("Uri: {0}", uri);
using (HttpResponseMessage response = await client.GetAsync(uri))
{
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
Assert.Equal(Configuration.Http.RemoteEchoServer, response.RequestMessage.RequestUri);
}
}
}
[Theory]
[InlineData(200)]
[InlineData(201)]
[InlineData(400)]
public async Task GetAsync_AllowAutoRedirectTrue_NonRedirectStatusCode_LocationHeader_NoRedirect(int statusCode)
{
HttpClientHandler handler = CreateHttpClientHandler();
handler.AllowAutoRedirect = true;
using (var client = new HttpClient(handler))
{
await LoopbackServer.CreateServerAsync(async (origServer, origUrl) =>
{
await LoopbackServer.CreateServerAsync(async (redirectServer, redirectUrl) =>
{
Task<HttpResponseMessage> getResponseTask = client.GetAsync(origUrl);
Task redirectTask = redirectServer.AcceptConnectionSendResponseAndCloseAsync();
await TestHelper.WhenAllCompletedOrAnyFailed(
getResponseTask,
origServer.AcceptConnectionSendResponseAndCloseAsync((HttpStatusCode)statusCode, $"Location: {redirectUrl}\r\n"));
using (HttpResponseMessage response = await getResponseTask)
{
Assert.Equal(statusCode, (int)response.StatusCode);
Assert.Equal(origUrl, response.RequestMessage.RequestUri);
Assert.False(redirectTask.IsCompleted, "Should not have redirected to Location");
}
});
});
}
}
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "Doesn't handle fragments according to https://tools.ietf.org/html/rfc7231#section-7.1.2")]
[SkipOnTargetFramework(TargetFrameworkMonikers.Uap, "Doesn't handle fragments according to https://tools.ietf.org/html/rfc7231#section-7.1.2")]
[Theory]
[InlineData("#origFragment", "", "#origFragment", false)]
[InlineData("#origFragment", "", "#origFragment", true)]
[InlineData("", "#redirFragment", "#redirFragment", false)]
[InlineData("", "#redirFragment", "#redirFragment", true)]
[InlineData("#origFragment", "#redirFragment", "#redirFragment", false)]
[InlineData("#origFragment", "#redirFragment", "#redirFragment", true)]
public async Task GetAsync_AllowAutoRedirectTrue_RetainsOriginalFragmentIfAppropriate(
string origFragment, string redirFragment, string expectedFragment, bool useRelativeRedirect)
{
if (IsCurlHandler)
{
// libcurl doesn't append fragment component to CURLINFO_EFFECTIVE_URL after redirect
return;
}
if (IsWinHttpHandler)
{
// According to https://tools.ietf.org/html/rfc7231#section-7.1.2,
// "If the Location value provided in a 3xx (Redirection) response does
// not have a fragment component, a user agent MUST process the
// redirection as if the value inherits the fragment component of the
// URI reference used to generate the request target(i.e., the
// redirection inherits the original reference's fragment, if any)."
// WINHTTP is not doing this, and thus neither is WinHttpHandler.
// It also sometimes doesn't include the fragments for redirects
// even in other cases.
return;
}
HttpClientHandler handler = CreateHttpClientHandler();
handler.AllowAutoRedirect = true;
using (var client = new HttpClient(handler))
{
await LoopbackServer.CreateServerAsync(async (origServer, origUrl) =>
{
origUrl = new UriBuilder(origUrl) { Fragment = origFragment }.Uri;
Uri redirectUrl = new UriBuilder(origUrl) { Fragment = redirFragment }.Uri;
if (useRelativeRedirect)
{
redirectUrl = new Uri(redirectUrl.GetComponents(UriComponents.PathAndQuery | UriComponents.Fragment, UriFormat.SafeUnescaped), UriKind.Relative);
}
Uri expectedUrl = new UriBuilder(origUrl) { Fragment = expectedFragment }.Uri;
// Make and receive the first request that'll be redirected.
Task<HttpResponseMessage> getResponse = client.GetAsync(origUrl);
Task firstRequest = origServer.AcceptConnectionSendResponseAndCloseAsync(HttpStatusCode.Found, $"Location: {redirectUrl}\r\n");
Assert.Equal(firstRequest, await Task.WhenAny(firstRequest, getResponse));
// Receive the second request.
Task<List<string>> secondRequest = origServer.AcceptConnectionSendResponseAndCloseAsync();
await TestHelper.WhenAllCompletedOrAnyFailed(secondRequest, getResponse);
// Make sure the server received the second request for the right Uri.
Assert.NotEmpty(secondRequest.Result);
string[] statusLineParts = secondRequest.Result[0].Split(' ');
Assert.Equal(3, statusLineParts.Length);
Assert.Equal(expectedUrl.GetComponents(UriComponents.PathAndQuery, UriFormat.SafeUnescaped), statusLineParts[1]);
// Make sure the request message was updated with the correct redirected location.
using (HttpResponseMessage response = await getResponse)
{
Assert.Equal(200, (int)response.StatusCode);
Assert.Equal(expectedUrl.ToString(), response.RequestMessage.RequestUri.ToString());
}
});
}
}
[ActiveIssue(32647, TargetFrameworkMonikers.Uap)]
[Fact]
[OuterLoop("Uses external server")]
public async Task GetAsync_CredentialIsNetworkCredentialUriRedirect_StatusCodeUnauthorized()
{
HttpClientHandler handler = CreateHttpClientHandler();
handler.Credentials = _credential;
using (var client = new HttpClient(handler))
{
Uri redirectUri = Configuration.Http.RedirectUriForCreds(
secure: false,
statusCode: 302,
userName: Username,
password: Password);
using (HttpResponseMessage unAuthResponse = await client.GetAsync(redirectUri))
{
Assert.Equal(HttpStatusCode.Unauthorized, unAuthResponse.StatusCode);
}
}
}
[ActiveIssue(32647, TargetFrameworkMonikers.Uap)]
[Fact]
[OuterLoop("Uses external server")]
public async Task HttpClientHandler_CredentialIsNotCredentialCacheAfterRedirect_StatusCodeOK()
{
HttpClientHandler handler = CreateHttpClientHandler();
handler.Credentials = _credential;
using (var client = new HttpClient(handler))
{
Uri redirectUri = Configuration.Http.RedirectUriForCreds(
secure: false,
statusCode: 302,
userName: Username,
password: Password);
using (HttpResponseMessage unAuthResponse = await client.GetAsync(redirectUri))
{
Assert.Equal(HttpStatusCode.Unauthorized, unAuthResponse.StatusCode);
}
// Use the same handler to perform get request, authentication should succeed after redirect.
Uri uri = Configuration.Http.BasicAuthUriForCreds(secure: true, userName: Username, password: Password);
using (HttpResponseMessage authResponse = await client.GetAsync(uri))
{
Assert.Equal(HttpStatusCode.OK, authResponse.StatusCode);
}
}
}
[OuterLoop("Uses external server")]
[Theory, MemberData(nameof(RedirectStatusCodes))]
public async Task GetAsync_CredentialIsCredentialCacheUriRedirect_StatusCodeOK(int statusCode)
{
if (statusCode == 308 && (PlatformDetection.IsFullFramework || IsWinHttpHandler && PlatformDetection.WindowsVersion < 10))
{
// 308 redirects are not supported on old versions of WinHttp, or on .NET Framework.
return;
}
Uri uri = Configuration.Http.BasicAuthUriForCreds(secure: false, userName: Username, password: Password);
Uri redirectUri = Configuration.Http.RedirectUriForCreds(
secure: false,
statusCode: statusCode,
userName: Username,
password: Password);
_output.WriteLine(uri.AbsoluteUri);
_output.WriteLine(redirectUri.AbsoluteUri);
var credentialCache = new CredentialCache();
credentialCache.Add(uri, "Basic", _credential);
HttpClientHandler handler = CreateHttpClientHandler();
if (PlatformDetection.IsUap)
{
// UAP does not support CredentialCache for Credentials.
Assert.Throws<PlatformNotSupportedException>(() => handler.Credentials = credentialCache);
}
else
{
handler.Credentials = credentialCache;
using (var client = new HttpClient(handler))
{
using (HttpResponseMessage response = await client.GetAsync(redirectUri))
{
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
Assert.Equal(uri, response.RequestMessage.RequestUri);
}
}
}
}
[ActiveIssue(29802, TargetFrameworkMonikers.Uap)]
[OuterLoop("Uses external server")]
[Theory, MemberData(nameof(RedirectStatusCodes))]
public async Task DefaultHeaders_SetCredentials_ClearedOnRedirect(int statusCode)
{
if (statusCode == 308 && (PlatformDetection.IsFullFramework || IsWinHttpHandler && PlatformDetection.WindowsVersion < 10))
{
// 308 redirects are not supported on old versions of WinHttp, or on .NET Framework.
return;
}
HttpClientHandler handler = CreateHttpClientHandler();
using (var client = new HttpClient(handler))
{
string credentialString = _credential.UserName + ":" + _credential.Password;
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", credentialString);
Uri uri = Configuration.Http.RedirectUriForDestinationUri(
secure: false,
statusCode: statusCode,
destinationUri: Configuration.Http.RemoteEchoServer,
hops: 1);
_output.WriteLine("Uri: {0}", uri);
using (HttpResponseMessage response = await client.GetAsync(uri))
{
string responseText = await response.Content.ReadAsStringAsync();
_output.WriteLine(responseText);
Assert.False(TestHelper.JsonMessageContainsKey(responseText, "Authorization"));
}
}
}
}
}
| |
// 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 OLEDB.Test.ModuleCore;
using Xunit;
namespace System.Xml.Tests
{
public partial class XmlWriterTestModule : CTestModule
{
private static void RunTestCase(Func<CTestBase> testCaseGenerator)
{
var module = new XmlWriterTestModule();
module.Init(null);
module.AddChild(testCaseGenerator());
module.Execute();
Assert.Equal(0, module.FailCount);
}
private static void RunTest(Func<CTestBase> testCaseGenerator)
{
CModInfo.CommandLine = "/WriterType UnicodeWriter";
RunTestCase(testCaseGenerator);
CModInfo.CommandLine = "/WriterType UnicodeWriter /Async true";
RunTestCase(testCaseGenerator);
CModInfo.CommandLine = "/WriterType UTF8Writer";
RunTestCase(testCaseGenerator);
CModInfo.CommandLine = "/WriterType UTF8Writer /Async true";
RunTestCase(testCaseGenerator);
}
[Fact]
[OuterLoop]
static public void TCErrorState()
{
RunTest(() => new TCErrorState() { Attribute = new TestCase() { Name = "Invalid State Combinations" } });
}
[Fact]
[OuterLoop]
static public void TCAutoComplete()
{
RunTest(() => new TCAutoComplete() { Attribute = new TestCase() { Name = "Auto-completion of tokens" } });
}
[Fact]
[OuterLoop]
static public void TCDocument()
{
RunTest(() => new TCDocument() { Attribute = new TestCase() { Name = "WriteStart/EndDocument" } });
}
[Fact]
[OuterLoop]
static public void TCDocType()
{
RunTest(() => new TCDocType() { Attribute = new TestCase() { Name = "WriteDocType" } });
}
[Fact]
[OuterLoop]
static public void TCElement()
{
RunTest(() => new TCElement() { Attribute = new TestCase() { Name = "WriteStart/EndElement" } });
}
[Fact]
[OuterLoop]
static public void TCAttribute()
{
RunTest(() => new TCAttribute() { Attribute = new TestCase() { Name = "WriteStart/EndAttribute" } });
}
[Fact]
[OuterLoop]
static public void TCWriteAttributes()
{
RunTest(() => new TCWriteAttributes() { Attribute = new TestCase() { Name = "WriteAttributes(CoreReader)", Param = "COREREADER" } });
}
[Fact]
[OuterLoop]
static public void TCWriteNode_XmlReader()
{
RunTest(() => new TCWriteNode_XmlReader() { Attribute = new TestCase() { Name = "WriteNode(CoreReader)", Param = "COREREADER" } });
}
[Fact]
[OuterLoop]
static public void TCWriteNode_With_ReadValueChunk()
{
RunTest(() => new TCWriteNode_With_ReadValueChunk() { Attribute = new TestCase() { Name = "WriteNode with streaming API ReadValueChunk - COREREADER", Param = "COREREADER" } });
}
[Fact]
[OuterLoop]
[ActiveIssue(1491)]
static public void TCFullEndElement()
{
RunTest(() => new TCFullEndElement() { Attribute = new TestCase() { Name = "WriteFullEndElement" } });
}
[Fact]
[OuterLoop]
[ActiveIssue(6331)]
static public void TCEOFHandling()
{
RunTest(() => new TCEOFHandling() { Attribute = new TestCase() { Name = "XmlWriterSettings: NewLineHandling" } });
}
[Fact]
[OuterLoop]
static public void TCErrorConditionWriter()
{
RunTest(() => new TCErrorConditionWriter() { Attribute = new TestCase() { Name = "ErrorCondition" } });
}
[Fact]
[OuterLoop]
static public void TCNamespaceHandling()
{
RunTest(() => new TCNamespaceHandling() { Attribute = new TestCase() { Name = "XmlWriterSettings: NamespaceHandling" } });
}
[Fact]
[OuterLoop]
static public void TCDefaultWriterSettings()
{
RunTest(() => new TCDefaultWriterSettings() { Attribute = new TestCase() { Name = "XmlWriterSettings: Default Values" } });
}
[Fact]
[OuterLoop]
static public void TCWriterSettingsMisc()
{
RunTest(() => new TCWriterSettingsMisc() { Attribute = new TestCase() { Name = "XmlWriterSettings: Reset/Clone" } });
}
[Fact]
[OuterLoop]
static public void TCOmitXmlDecl()
{
RunTest(() => new TCOmitXmlDecl() { Attribute = new TestCase() { Name = "XmlWriterSettings: OmitXmlDeclaration" } });
}
[Fact]
[OuterLoop]
static public void TCCheckChars()
{
RunTest(() => new TCCheckChars() { Attribute = new TestCase() { Name = "XmlWriterSettings: CheckCharacters" } });
}
[Fact]
[OuterLoop]
static public void TCNewLineHandling()
{
RunTest(() => new TCNewLineHandling() { Attribute = new TestCase() { Name = "XmlWriterSettings: NewLineHandling" } });
}
[Fact]
[OuterLoop]
static public void TCNewLineChars()
{
RunTest(() => new TCNewLineChars() { Attribute = new TestCase() { Name = "XmlWriterSettings: NewLineChars" } });
}
[Fact]
[OuterLoop]
static public void TCIndent()
{
RunTest(() => new TCIndent() { Attribute = new TestCase() { Name = "XmlWriterSettings: Indent" } });
}
[Fact]
[OuterLoop]
static public void TCIndentChars()
{
RunTest(() => new TCIndentChars() { Attribute = new TestCase() { Name = "XmlWriterSettings: IndentChars" } });
}
[Fact]
[OuterLoop]
static public void TCNewLineOnAttributes()
{
RunTest(() => new TCNewLineOnAttributes() { Attribute = new TestCase() { Name = "XmlWriterSettings: NewLineOnAttributes" } });
}
[Fact]
[OuterLoop]
static public void TCStandAlone()
{
RunTest(() => new TCStandAlone() { Attribute = new TestCase() { Name = "Standalone" } });
}
[Fact]
[OuterLoop]
static public void TCCloseOutput()
{
RunTest(() => new TCCloseOutput() { Attribute = new TestCase() { Name = "XmlWriterSettings: CloseOutput" } });
}
[Fact]
[OuterLoop]
static public void TCFragmentCL()
{
RunTest(() => new TCFragmentCL() { Attribute = new TestCase() { Name = "CL = Fragment Tests" } });
}
[Fact]
[OuterLoop]
static public void TCAutoCL()
{
RunTest(() => new TCAutoCL() { Attribute = new TestCase() { Name = "CL = Auto Tests" } });
}
[Fact]
[OuterLoop]
static public void TCFlushClose()
{
RunTest(() => new TCFlushClose() { Attribute = new TestCase() { Name = "Close()/Flush()" } });
}
[Fact]
[OuterLoop]
static public void TCWriterWithMemoryStream()
{
RunTest(() => new TCWriterWithMemoryStream() { Attribute = new TestCase() { Name = "XmlWriter with MemoryStream" } });
}
[Fact]
[OuterLoop]
static public void TCWriteEndDocumentOnCloseTest()
{
RunTest(() => new TCWriteEndDocumentOnCloseTest() { Attribute = new TestCase() { Name = "XmlWriterSettings: WriteEndDocumentOnClose" } });
}
}
}
| |
/*
* 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.Linq;
using QuantConnect.Data;
using QuantConnect.Data.UniverseSelection;
using QuantConnect.Interfaces;
namespace QuantConnect.Algorithm.CSharp
{
/// <summary>
/// In this algortihm we show how you can easily use the universe selection feature to fetch symbols
/// to be traded using the BaseData custom data system in combination with the AddUniverse{T} method.
/// AddUniverse{T} requires a function that will return the symbols to be traded.
/// </summary>
/// <meta name="tag" content="using data" />
/// <meta name="tag" content="universes" />
/// <meta name="tag" content="custom universes" />
public class DropboxBaseDataUniverseSelectionAlgorithm : QCAlgorithm, IRegressionAlgorithmDefinition
{
// the changes from the previous universe selection
private SecurityChanges _changes = SecurityChanges.None;
/// <summary>
/// Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.
/// </summary>
/// <seealso cref="QCAlgorithm.SetStartDate(System.DateTime)"/>
/// <seealso cref="QCAlgorithm.SetEndDate(System.DateTime)"/>
/// <seealso cref="QCAlgorithm.SetCash(decimal)"/>
public override void Initialize()
{
UniverseSettings.Resolution = Resolution.Daily;
// Order margin value has to have a minimum of 0.5% of Portfolio value, allows filtering out small trades and reduce fees.
// Commented so regression algorithm is more sensitive
//Settings.MinimumOrderMarginPortfolioPercentage = 0.005m;
SetStartDate(2017, 07, 04);
SetEndDate(2018, 07, 04);
AddUniverse<StockDataSource>("my-stock-data-source", stockDataSource =>
{
return stockDataSource.SelectMany(x => x.Symbols);
});
}
/// <summary>
/// Event - v3.0 DATA EVENT HANDLER: (Pattern) Basic template for user to override for receiving all subscription data in a single event
/// </summary>
/// <code>
/// TradeBars bars = slice.Bars;
/// Ticks ticks = slice.Ticks;
/// TradeBar spy = slice["SPY"];
/// List{Tick} aaplTicks = slice["AAPL"]
/// Quandl oil = slice["OIL"]
/// dynamic anySymbol = slice[symbol];
/// DataDictionary{Quandl} allQuandlData = slice.Get{Quand}
/// Quandl oil = slice.Get{Quandl}("OIL")
/// </code>
/// <param name="slice">The current slice of data keyed by symbol string</param>
public override void OnData(Slice slice)
{
if (slice.Bars.Count == 0) return;
if (_changes == SecurityChanges.None) return;
// start fresh
Liquidate();
var percentage = 1m / slice.Bars.Count;
foreach (var tradeBar in slice.Bars.Values)
{
SetHoldings(tradeBar.Symbol, percentage);
}
// reset changes
_changes = SecurityChanges.None;
}
/// <summary>
/// Event fired each time the we add/remove securities from the data feed
/// </summary>
/// <param name="changes"></param>
public override void OnSecuritiesChanged(SecurityChanges changes)
{
// each time our securities change we'll be notified here
_changes = changes;
}
/// <summary>
/// Our custom data type that defines where to get and how to read our backtest and live data.
/// </summary>
class StockDataSource : BaseData
{
private const string LiveUrl = @"https://www.dropbox.com/s/2l73mu97gcehmh7/daily-stock-picker-live.csv?dl=1";
private const string BacktestUrl = @"https://www.dropbox.com/s/ae1couew5ir3z9y/daily-stock-picker-backtest.csv?dl=1";
/// <summary>
/// The symbols to be selected
/// </summary>
public List<string> Symbols { get; set; }
/// <summary>
/// Required default constructor
/// </summary>
public StockDataSource()
{
// initialize our list to empty
Symbols = new List<string>();
}
/// <summary>
/// Return the URL string source of the file. This will be converted to a stream
/// </summary>
/// <param name="config">Configuration object</param>
/// <param name="date">Date of this source file</param>
/// <param name="isLiveMode">true if we're in live mode, false for backtesting mode</param>
/// <returns>String URL of source file.</returns>
public override SubscriptionDataSource GetSource(SubscriptionDataConfig config, DateTime date, bool isLiveMode)
{
var url = isLiveMode ? LiveUrl : BacktestUrl;
return new SubscriptionDataSource(url, SubscriptionTransportMedium.RemoteFile);
}
/// <summary>
/// Reader converts each line of the data source into BaseData objects. Each data type creates its own factory method, and returns a new instance of the object
/// each time it is called. The returned object is assumed to be time stamped in the config.ExchangeTimeZone.
/// </summary>
/// <param name="config">Subscription data config setup object</param>
/// <param name="line">Line of the source document</param>
/// <param name="date">Date of the requested data</param>
/// <param name="isLiveMode">true if we're in live mode, false for backtesting mode</param>
/// <returns>Instance of the T:BaseData object generated by this line of the CSV</returns>
public override BaseData Reader(SubscriptionDataConfig config, string line, DateTime date, bool isLiveMode)
{
try
{
// create a new StockDataSource and set the symbol using config.Symbol
var stocks = new StockDataSource {Symbol = config.Symbol};
// break our line into csv pieces
var csv = line.ToCsv();
if (isLiveMode)
{
// our live mode format does not have a date in the first column, so use date parameter
stocks.Time = date;
stocks.Symbols.AddRange(csv);
}
else
{
// our backtest mode format has the first column as date, parse it
stocks.Time = DateTime.ParseExact(csv[0], "yyyyMMdd", null);
// any following comma separated values are symbols, save them off
stocks.Symbols.AddRange(csv.Skip(1));
}
return stocks;
}
// return null if we encounter any errors
catch { return null; }
}
}
/// <summary>
/// This is used by the regression test system to indicate if the open source Lean repository has the required data to run this algorithm.
/// </summary>
public bool CanRunLocally { get; } = true;
/// <summary>
/// This is used by the regression test system to indicate which languages this algorithm is written in.
/// </summary>
public Language[] Languages { get; } = { Language.CSharp, Language.Python };
/// <summary>
/// This is used by the regression test system to indicate what the expected statistics are from running the algorithm
/// </summary>
public Dictionary<string, string> ExpectedStatistics => new Dictionary<string, string>
{
{"Total Trades", "6441"},
{"Average Win", "0.07%"},
{"Average Loss", "-0.07%"},
{"Compounding Annual Return", "14.802%"},
{"Drawdown", "10.400%"},
{"Expectancy", "0.068"},
{"Net Profit", "14.802%"},
{"Sharpe Ratio", "1.077"},
{"Probabilistic Sharpe Ratio", "50.578%"},
{"Loss Rate", "46%"},
{"Win Rate", "54%"},
{"Profit-Loss Ratio", "0.97"},
{"Alpha", "0.137"},
{"Beta", "-0.069"},
{"Annual Standard Deviation", "0.119"},
{"Annual Variance", "0.014"},
{"Information Ratio", "0.046"},
{"Tracking Error", "0.169"},
{"Treynor Ratio", "-1.869"},
{"Total Fees", "$7495.19"},
{"Estimated Strategy Capacity", "$320000.00"},
{"Lowest Capacity Asset", "BNO UN3IMQ2JU1YD"},
{"Fitness Score", "0.695"},
{"Kelly Criterion Estimate", "0"},
{"Kelly Criterion Probability Value", "0"},
{"Sortino Ratio", "1.269"},
{"Return Over Maximum Drawdown", "1.424"},
{"Portfolio Turnover", "1.613"},
{"Total Insights Generated", "0"},
{"Total Insights Closed", "0"},
{"Total Insights Analysis Completed", "0"},
{"Long Insight Count", "0"},
{"Short Insight Count", "0"},
{"Long/Short Ratio", "100%"},
{"Estimated Monthly Alpha Value", "$0"},
{"Total Accumulated Estimated Alpha Value", "$0"},
{"Mean Population Estimated Insight Value", "$0"},
{"Mean Population Direction", "0%"},
{"Mean Population Magnitude", "0%"},
{"Rolling Averaged Population Direction", "0%"},
{"Rolling Averaged Population Magnitude", "0%"},
{"OrderListHash", "df66ec72bb4332b14bbe31ec9bea7ffc"}
};
}
}
| |
/*
* Naiad ver. 0.5
* Copyright (c) Microsoft Corporation
* 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
*
* THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT
* LIMITATION ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR
* A PARTICULAR PURPOSE, MERCHANTABLITY OR NON-INFRINGEMENT.
*
* See the Apache Version 2.0 License for specific language governing
* permissions and limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using Microsoft.Research.Naiad.Dataflow.Channels;
using Microsoft.Research.Naiad.Runtime.Controlling;
using Microsoft.Research.Naiad.Scheduling;
using Microsoft.Research.Naiad.Dataflow;
using Microsoft.Research.Naiad.Dataflow.StandardVertices;
namespace Microsoft.Research.Naiad
{
/// <summary>
/// Represents an observable "output" of a Naiad computation, and provides a means
/// of synchronizing with the computation.
/// </summary>
public interface Subscription : IDisposable
{
/// <summary>
/// Blocks the caller until this subscription has processed all inputs up to and
/// including the given epoch.
/// </summary>
/// <param name="time">The epoch.</param>
/// <remarks>
/// To synchronize on all subscriptions in a computation at a particular epoch, use the <see cref="Computation.Sync"/> method.
/// To block until the entire computation has terminated, use the <see cref="Computation.Join"/> method.
/// </remarks>
/// <seealso cref="Computation.Sync"/>
/// <seealso cref="Computation.Join"/>
void Sync(int time);
}
/// <summary>
/// Extension methods
/// </summary>
public static class SubscribeExtensionMethods
{
/// <summary>
/// Subscribes to a stream with no callback.
/// </summary>
/// <typeparam name="R">record type</typeparam>
/// <param name="stream">input stream</param>
/// <returns>subscription for synchronization</returns>
public static Subscription Subscribe<R>(this Stream<R, Epoch> stream)
{
return stream.Subscribe(x => { });
}
/// <summary>
/// Subscribes to a stream with a per-epoch callback applied by one worker.
/// </summary>
/// <typeparam name="R">record type</typeparam>
/// <param name="stream">input stream</param>
/// <param name="action">callback</param>
/// <returns>subscription for synchronization</returns>
public static Subscription Subscribe<R>(this Stream<R, Epoch> stream, Action<IEnumerable<R>> action)
{
return new Subscription<R>(stream, new Placement.SingleVertex(0, 0), stream.Context, (j, t, l) => action(l));
}
/// <summary>
/// Subscribes to a stream with a per-epoch callback applied at each worker.
/// </summary>
/// <typeparam name="R">record type</typeparam>
/// <param name="stream">input stream</param>
/// <param name="action">callback on worker id and records</param>
/// <returns>subscription for synchronization</returns>
public static Subscription Subscribe<R>(this Stream<R, Epoch> stream, Action<int, IEnumerable<R>> action)
{
return stream.Subscribe((j, t, l) => action(j, l));
}
/// <summary>
/// Subscribes to a stream with a callback parameterized by worker id, epoch, and records.
/// </summary>
/// <typeparam name="R">record type</typeparam>
/// <param name="stream">input stream</param>
/// <param name="action">callback on worker id, epoch id, and records</param>
/// <returns>subscription for synchronization</returns>
public static Subscription Subscribe<R>(this Stream<R, Epoch> stream, Action<int, int, IEnumerable<R>> action)
{
return new Subscription<R>(stream, stream.ForStage.Placement, stream.Context, action);
}
/// <summary>
/// Subscribes to a stream with callbacks for record receipt, epoch completion notification, and stream completion notification.
/// </summary>
/// <typeparam name="R">record type</typeparam>
/// <param name="stream">input stream</param>
/// <param name="onRecv">receipt callback</param>
/// <param name="onNotify">notification callback</param>
/// <param name="onComplete">completion callback</param>
/// <returns>subscription for synchronization</returns>
public static Subscription Subscribe<R>(this Stream<R, Epoch> stream, Action<Message<R, Epoch>, int> onRecv, Action<Epoch, int> onNotify, Action<int> onComplete)
{
return new Subscription<R>(stream, stream.ForStage.Placement, stream.Context, onRecv, onNotify, onComplete);
}
}
}
namespace Microsoft.Research.Naiad.Dataflow
{
/// <summary>
/// Manages several subscribe vertices, and allows another thread to block until all have completed a specified epoch
/// </summary>
internal class Subscription<R> : IDisposable, Subscription
{
private readonly Dictionary<int, CountdownEvent> Countdowns;
private int LocalVertexCount;
private int CompleteThrough;
private bool disposed = false;
internal bool Disposed { get { return this.disposed; } }
public void Dispose()
{
disposed = true;
}
internal readonly InputStage[] SourceInputs;
/// <summary>
/// Called by vertices, indicates the receipt of an OnNotify(time)
/// </summary>
/// <param name="time">Time that has completed for the vertex</param>
internal void Signal(Epoch time)
{
lock (this.Countdowns)
{
// if this is the first mention of time.t, create a new countdown
if (!this.Countdowns.ContainsKey(time.epoch))
this.Countdowns[time.epoch] = new CountdownEvent(this.LocalVertexCount);
if (this.Countdowns[time.epoch].CurrentCount > 0)
this.Countdowns[time.epoch].Signal();
else
Console.Error.WriteLine("Too many Signal({0})", time.epoch);
// if the last signal, clean up a bit
if (this.Countdowns[time.epoch].CurrentCount == 0)
{
this.CompleteThrough = time.epoch; // bump completethrough int
this.Countdowns.Remove(time.epoch); // remove countdown object
}
}
}
/// <summary>
/// Blocks the caller until this subscription has completed the given epoch.
/// </summary>
/// <param name="epoch">Time to wait until locally complete</param>
public void Sync(int epoch)
{
CountdownEvent countdown;
lock (this.Countdowns)
{
// if we have already completed it, don't wait
if (epoch <= this.CompleteThrough)
return;
// if we haven't heard about it, create a new countdown
if (!this.Countdowns.ContainsKey(epoch))
this.Countdowns[epoch] = new CountdownEvent(this.LocalVertexCount);
countdown = this.Countdowns[epoch];
}
// having released the lock, wait.
countdown.Wait();
}
internal Subscription(Stream<R, Epoch> input, Placement placement, TimeContext<Epoch> context, Action<Message<R, Epoch>, int> onRecv, Action<Epoch, int> onNotify, Action<int> onComplete)
{
foreach (var entry in placement)
if (entry.ProcessId == context.Context.Manager.InternalComputation.Controller.Configuration.ProcessID)
this.LocalVertexCount++;
var stage = new Stage<SubscribeStreamingVertex<R>, Epoch>(placement, context, Stage.OperatorType.Default, (i, v) => new SubscribeStreamingVertex<R>(i, v, this, onRecv, onNotify, onComplete), "Subscribe");
stage.NewInput(input, (message, vertex) => vertex.OnReceive(message), null);
this.Countdowns = new Dictionary<int, CountdownEvent>();
this.CompleteThrough = -1;
// important for reachability to be defined for the next test
stage.InternalComputation.Reachability.UpdateReachabilityPartialOrder(stage.InternalComputation);
// should only schedule next epoch if at least one input who can reach this stage will have data for this.
this.SourceInputs = stage.InternalComputation.Inputs.Where(i => stage.InternalComputation.Reachability.ComparisonDepth[i.InputId][stage.StageId] != 0).ToArray();
// add this subscription to the list of outputs.
stage.InternalComputation.Register(this);
}
internal Subscription(Stream<R, Epoch> input, Placement placement, TimeContext<Epoch> context, Action<int, int, IEnumerable<R>> action)
{
foreach (var entry in placement)
if (entry.ProcessId == context.Context.Manager.InternalComputation.Controller.Configuration.ProcessID)
this.LocalVertexCount++;
var stage = new Stage<SubscribeBufferingVertex<R>, Epoch>(placement, context, Stage.OperatorType.Default, (i, v) => new SubscribeBufferingVertex<R>(i, v, this, action), "Subscribe");
stage.NewInput(input, (message, vertex) => vertex.OnReceive(message), null);
this.Countdowns = new Dictionary<int, CountdownEvent>();
this.CompleteThrough = -1;
// important for reachability to be defined for the next test
stage.InternalComputation.Reachability.UpdateReachabilityPartialOrder(stage.InternalComputation);
// should only schedule next epoch if at least one input who can reach this stage will have data for this.
this.SourceInputs = stage.InternalComputation.Inputs.Where(i => stage.InternalComputation.Reachability.ComparisonDepth[i.InputId][stage.StageId] != 0).ToArray();
// add this subscription to the list of outputs.
stage.InternalComputation.Register(this);
}
}
/// <summary>
/// Individual subscription vertex, invokes actions and notifies parent stage.
/// </summary>
/// <typeparam name="R">Record type</typeparam>
internal class SubscribeStreamingVertex<R> : SinkVertex<R, Epoch>
{
Action<Message<R, Epoch>, int> OnRecv;
Action<Epoch, int> OnNotifyAction;
Action<int> OnCompleted;
Subscription<R> Parent;
protected override void OnShutdown()
{
this.OnCompleted(this.Scheduler.Index);
base.OnShutdown();
}
public override void OnReceive(Message<R, Epoch> record)
{
this.OnRecv(record, this.Scheduler.Index);
this.NotifyAt(record.time);
}
/// <summary>
/// When a time completes, invokes an action on received data, signals parent stage, and schedules OnNotify for next expoch.
/// </summary>
/// <param name="time"></param>
public override void OnNotify(Epoch time)
{
// test to see if inputs supplied data for this epoch, or terminated instead
var validEpoch = false;
for (int i = 0; i < this.Parent.SourceInputs.Length; i++)
if (this.Parent.SourceInputs[i].MaximumValidEpoch >= time.epoch)
validEpoch = true;
if (validEpoch)
this.OnNotifyAction(time, this.Scheduler.Index);
this.Parent.Signal(time);
if (!this.Parent.Disposed && validEpoch)
this.NotifyAt(new Epoch(time.epoch + 1));
}
public SubscribeStreamingVertex(int index, Stage<Epoch> stage, Subscription<R> parent, Action<Message<R, Epoch>, int> onrecv, Action<Epoch, int> onnotify, Action<int> oncomplete)
: base(index, stage)
{
this.Parent = parent;
this.OnRecv = onrecv;
this.OnNotifyAction = onnotify;
this.OnCompleted = oncomplete;
this.NotifyAt(new Epoch(0));
}
}
/// <summary>
/// Individual subscription vertex, invokes actions and notifies parent stage.
/// </summary>
/// <typeparam name="R">Record type</typeparam>
internal class SubscribeBufferingVertex<R> : SinkBufferingVertex<R, Epoch>
{
Action<int, int, IEnumerable<R>> Action; // (vertexid, epoch, data) => ()
Subscription<R> Parent;
/// <summary>
/// When a time completes, invokes an action on received data, signals parent stage, and schedules OnNotify for next expoch.
/// </summary>
/// <param name="time"></param>
public override void OnNotify(Epoch time)
{
var validEpoch = false;
for (int i = 0; i < this.Parent.SourceInputs.Length; i++)
if (this.Parent.SourceInputs[i].MaximumValidEpoch >= time.epoch)
validEpoch = true;
if (validEpoch)
Action(this.VertexId, time.epoch, Input.GetRecordsAt(time));
this.Parent.Signal(time);
if (!this.Parent.Disposed && validEpoch)
this.NotifyAt(new Epoch(time.epoch + 1));
}
public SubscribeBufferingVertex(int index, Stage<Epoch> stage, Subscription<R> parent, Action<int, int, IEnumerable<R>> action)
: base(index, stage, null)
{
this.Parent = parent;
this.Action = action;
this.Input = new VertexInputBuffer<R, Epoch>(this);
this.NotifyAt(new Epoch(0));
}
}
}
| |
// <copyright file="VectorTests.Arithmetic.cs" company="Math.NET">
// Math.NET Numerics, part of the Math.NET Project
// http://numerics.mathdotnet.com
// http://github.com/mathnet/mathnet-numerics
//
// Copyright (c) 2009-2016 Math.NET
//
// 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>
using MathNet.Numerics.LinearAlgebra;
using NUnit.Framework;
using System;
namespace MathNet.Numerics.UnitTests.LinearAlgebraTests.Double
{
/// <summary>
/// Abstract class with the common arithmetic set of vector tests.
/// </summary>
public abstract partial class VectorTests
{
/// <summary>
/// Can call unary "+" operator.
/// </summary>
[Test]
public void CanCallUnaryPlusOperator()
{
var vector = CreateVector(Data);
var other = +vector;
CollectionAssert.AreEqual(vector, other);
}
/// <summary>
/// Can add a scalar to a vector.
/// </summary>
[Test]
public void CanAddScalarToVector()
{
var copy = CreateVector(Data);
var vector = copy.Add(2.0);
for (var i = 0; i < Data.Length; i++)
{
Assert.AreEqual(Data[i] + 2.0, vector[i]);
}
vector.Add(0.0);
for (var i = 0; i < Data.Length; i++)
{
Assert.AreEqual(Data[i] + 2.0, vector[i]);
}
}
/// <summary>
/// Can add a scalar to a vector using result vector.
/// </summary>
[Test]
public void CanAddScalarToVectorIntoResultVector()
{
var vector = CreateVector(Data);
var result = CreateVector(Data.Length);
vector.Add(2.0, result);
CollectionAssert.AreEqual(Data, vector, "Making sure the original vector wasn't modified.");
for (var i = 0; i < Data.Length; i++)
{
Assert.AreEqual(Data[i] + 2.0, result[i]);
}
vector.Add(0.0, result);
CollectionAssert.AreEqual(Data, result);
}
/// <summary>
/// Adding scalar to a vector using result vector with wrong size throws an exception.
/// </summary>
[Test]
public void AddingScalarWithWrongSizeResultVectorThrowsArgumentException()
{
var vector = CreateVector(Data.Length);
var result = CreateVector(Data.Length + 1);
Assert.That(() => vector.Add(0.0, result), Throws.ArgumentException);
}
/// <summary>
/// Adding two vectors of different size throws an exception.
/// </summary>
[Test]
public void AddingTwoVectorsOfDifferentSizeThrowsArgumentException()
{
var vector = CreateVector(Data.Length);
var other = CreateVector(Data.Length + 1);
Assert.That(() => vector.Add(other), Throws.ArgumentException);
}
/// <summary>
/// Adding two vectors when a result vector is different size throws an exception.
/// </summary>
[Test]
public void AddingTwoVectorsAndResultIsDifferentSizeThrowsArgumentException()
{
var vector = CreateVector(Data.Length);
var other = CreateVector(Data.Length);
var result = CreateVector(Data.Length + 1);
Assert.That(() => vector.Add(other, result), Throws.ArgumentException);
}
/// <summary>
/// Addition operator throws <c>ArgumentException</c> if vectors are different size.
/// </summary>
[Test]
public void AdditionOperatorIfVectorsAreDifferentSizeThrowsArgumentException()
{
var a = CreateVector(Data.Length);
var b = CreateVector(Data.Length + 1);
Assert.That(() => a += b, Throws.ArgumentException);
}
/// <summary>
/// Can add two vectors.
/// </summary>
[Test]
public void CanAddTwoVectors()
{
var copy = CreateVector(Data);
var other = CreateVector(Data);
var vector = copy.Add(other);
for (var i = 0; i < Data.Length; i++)
{
Assert.AreEqual(Data[i] * 2.0, vector[i]);
}
}
/// <summary>
/// Can add two vectors using a result vector.
/// </summary>
[Test]
public void CanAddTwoVectorsIntoResultVector()
{
var vector = CreateVector(Data);
var other = CreateVector(Data);
var result = CreateVector(Data.Length);
vector.Add(other, result);
CollectionAssert.AreEqual(Data, vector, "Making sure the original vector wasn't modified.");
CollectionAssert.AreEqual(Data, other, "Making sure the original vector wasn't modified.");
for (var i = 0; i < Data.Length; i++)
{
Assert.AreEqual(Data[i] * 2.0, result[i]);
}
}
/// <summary>
/// Can add two vectors using "+" operator.
/// </summary>
[Test]
public void CanAddTwoVectorsUsingOperator()
{
var vector = CreateVector(Data);
var other = CreateVector(Data);
var result = vector + other;
CollectionAssert.AreEqual(Data, vector, "Making sure the original vector wasn't modified.");
CollectionAssert.AreEqual(Data, other, "Making sure the original vector wasn't modified.");
for (var i = 0; i < Data.Length; i++)
{
Assert.AreEqual(Data[i] * 2.0, result[i]);
}
}
/// <summary>
/// Can add a vector to itself.
/// </summary>
[Test]
public void CanAddVectorToItself()
{
var copy = CreateVector(Data);
var vector = copy.Add(copy);
for (var i = 0; i < Data.Length; i++)
{
Assert.AreEqual(Data[i] * 2.0, vector[i]);
}
}
/// <summary>
/// Can add a vector to itself using a result vector.
/// </summary>
[Test]
public void CanAddVectorToItselfIntoResultVector()
{
var vector = CreateVector(Data);
var result = CreateVector(Data.Length);
vector.Add(vector, result);
CollectionAssert.AreEqual(Data, vector, "Making sure the original vector wasn't modified.");
for (var i = 0; i < Data.Length; i++)
{
Assert.AreEqual(Data[i] * 2.0, result[i]);
}
}
/// <summary>
/// Can add a vector to itself as result vector.
/// </summary>
[Test]
public void CanAddTwoVectorsUsingItselfAsResultVector()
{
var vector = CreateVector(Data);
var other = CreateVector(Data);
vector.Add(other, vector);
CollectionAssert.AreEqual(Data, other, "Making sure the original vector wasn't modified.");
for (var i = 0; i < Data.Length; i++)
{
Assert.AreEqual(Data[i] * 2.0, vector[i]);
}
}
/// <summary>
/// Can negate a vector.
/// </summary>
[Test]
public void CanCallNegate()
{
var vector = CreateVector(Data);
var other = vector.Negate();
for (var i = 0; i < Data.Length; i++)
{
Assert.AreEqual(-Data[i], other[i]);
}
}
/// <summary>
/// Can call unary negation operator.
/// </summary>
[Test]
public void CanCallUnaryNegationOperator()
{
var vector = CreateVector(Data);
var other = -vector;
for (var i = 0; i < Data.Length; i++)
{
Assert.AreEqual(-Data[i], other[i]);
}
}
/// <summary>
/// Can subtract a scalar from a vector.
/// </summary>
[Test]
public void CanSubtractScalarFromVector()
{
var copy = CreateVector(Data);
var vector = copy.Subtract(2.0);
for (var i = 0; i < Data.Length; i++)
{
Assert.AreEqual(Data[i] - 2.0, vector[i]);
}
vector.Subtract(0.0);
for (var i = 0; i < Data.Length; i++)
{
Assert.AreEqual(Data[i] - 2.0, vector[i]);
}
}
/// <summary>
/// Can subtract a scalar from a vector using a result vector.
/// </summary>
[Test]
public void CanSubtractScalarFromVectorIntoResultVector()
{
var vector = CreateVector(Data);
var result = CreateVector(Data.Length);
vector.Subtract(2.0, result);
CollectionAssert.AreEqual(Data, vector, "Making sure the original vector wasn't modified.");
for (var i = 0; i < Data.Length; i++)
{
Assert.AreEqual(Data[i], vector[i], "Making sure the original vector wasn't modified.");
Assert.AreEqual(Data[i] - 2.0, result[i]);
}
vector.Subtract(0.0, result);
for (var i = 0; i < Data.Length; i++)
{
Assert.AreEqual(Data[i], result[i]);
}
}
/// <summary>
/// Subtracting a scalar with wrong size result vector throws <c>ArgumentException</c>.
/// </summary>
[Test]
public void SubtractingScalarWithWrongSizeResultVectorThrowsArgumentException()
{
var vector = CreateVector(Data.Length);
var result = CreateVector(Data.Length + 1);
Assert.That(() => vector.Subtract(0.0, result), Throws.ArgumentException);
}
/// <summary>
/// Subtracting two vectors of differing size throws <c>ArgumentException</c>.
/// </summary>
[Test]
public void SubtractingTwoVectorsOfDifferingSizeThrowsArgumentException()
{
var vector = CreateVector(Data.Length);
var other = CreateVector(Data.Length + 1);
Assert.That(() => vector.Subtract(other), Throws.ArgumentException);
}
/// <summary>
/// Subtracting two vectors when a result vector is different size throws <c>ArgumentException</c>.
/// </summary>
[Test]
public void SubtractingTwoVectorsAndResultIsDifferentSizeThrowsArgumentException()
{
var vector = CreateVector(Data.Length);
var other = CreateVector(Data.Length);
var result = CreateVector(Data.Length + 1);
Assert.That(() => vector.Subtract(other, result), Throws.ArgumentException);
}
/// <summary>
/// Subtraction operator throws <c>ArgumentException</c> if vectors are different size.
/// </summary>
[Test]
public void SubtractionOperatorIfVectorsAreDifferentSizeThrowsArgumentException()
{
var a = CreateVector(Data.Length);
var b = CreateVector(Data.Length + 1);
Assert.That(() => a -= b, Throws.ArgumentException);
}
/// <summary>
/// Can subtract two vectors.
/// </summary>
[Test]
public void CanSubtractTwoVectors()
{
var copy = CreateVector(Data);
var other = CreateVector(Data);
var vector = copy.Subtract(other);
for (var i = 0; i < Data.Length; i++)
{
Assert.AreEqual(0.0, vector[i]);
}
}
/// <summary>
/// Can subtract two vectors using a result vector.
/// </summary>
[Test]
public void CanSubtractTwoVectorsIntoResultVector()
{
var vector = CreateVector(Data);
var other = CreateVector(Data);
var result = CreateVector(Data.Length);
vector.Subtract(other, result);
CollectionAssert.AreEqual(Data, vector, "Making sure the original vector wasn't modified.");
CollectionAssert.AreEqual(Data, other, "Making sure the original vector wasn't modified.");
for (var i = 0; i < Data.Length; i++)
{
Assert.AreEqual(0.0, result[i]);
}
}
/// <summary>
/// Can subtract two vectors using "-" operator.
/// </summary>
[Test]
public void CanSubtractTwoVectorsUsingOperator()
{
var vector = CreateVector(Data);
var other = CreateVector(Data);
var result = vector - other;
CollectionAssert.AreEqual(Data, vector, "Making sure the original vector wasn't modified.");
CollectionAssert.AreEqual(Data, other, "Making sure the original vector wasn't modified.");
for (var i = 0; i < Data.Length; i++)
{
Assert.AreEqual(0.0, result[i]);
}
}
/// <summary>
/// Can subtract a vector from itself.
/// </summary>
[Test]
public void CanSubtractVectorFromItself()
{
var copy = CreateVector(Data);
var vector = copy.Subtract(copy);
for (var i = 0; i < Data.Length; i++)
{
Assert.AreEqual(0.0, vector[i]);
}
}
/// <summary>
/// Can subtract a vector from itself using a result vector.
/// </summary>
[Test]
public void CanSubtractVectorFromItselfIntoResultVector()
{
var vector = CreateVector(Data);
var result = CreateVector(Data.Length);
vector.Subtract(vector, result);
CollectionAssert.AreEqual(Data, vector, "Making sure the original vector wasn't modified.");
for (var i = 0; i < Data.Length; i++)
{
Assert.AreEqual(0.0, result[i]);
}
}
/// <summary>
/// Can subtract two vectors using itself as result vector.
/// </summary>
[Test]
public void CanSubtractTwoVectorsUsingItselfAsResultVector()
{
var vector = CreateVector(Data);
var other = CreateVector(Data);
vector.Subtract(other, vector);
CollectionAssert.AreEqual(Data, other, "Making sure the original vector wasn't modified.");
for (var i = 0; i < Data.Length; i++)
{
Assert.AreEqual(0.0, vector[i]);
}
}
/// <summary>
/// Can divide a vector by a scalar.
/// </summary>
[Test]
public void CanDivideVectorByScalar()
{
var copy = CreateVector(Data);
var vector = copy.Divide(2.0);
for (var i = 0; i < Data.Length; i++)
{
Assert.AreEqual(Data[i] / 2.0, vector[i]);
}
vector.Divide(1.0);
for (var i = 0; i < Data.Length; i++)
{
Assert.AreEqual(Data[i] / 2.0, vector[i]);
}
}
/// <summary>
/// Can divide a vector by a scalar using a result vector.
/// </summary>
[Test]
public void CanDivideVectorByScalarIntoResultVector()
{
var vector = CreateVector(Data);
var result = CreateVector(Data.Length);
vector.Divide(2.0, result);
CollectionAssert.AreEqual(Data, vector, "Making sure the original vector wasn't modified.");
for (var i = 0; i < Data.Length; i++)
{
Assert.AreEqual(Data[i] / 2.0, result[i]);
}
vector.Divide(1.0, result);
for (var i = 0; i < Data.Length; i++)
{
Assert.AreEqual(Data[i], result[i]);
}
}
/// <summary>
/// Can multiply a vector by a scalar.
/// </summary>
[Test]
public void CanMultiplyVectorByScalar()
{
var copy = CreateVector(Data);
var vector = copy.Multiply(2.0);
for (var i = 0; i < Data.Length; i++)
{
Assert.AreEqual(Data[i] * 2.0, vector[i]);
}
vector.Multiply(1.0);
for (var i = 0; i < Data.Length; i++)
{
Assert.AreEqual(Data[i] * 2.0, vector[i]);
}
}
/// <summary>
/// Can multiply a vector by a scalar using a result vector.
/// </summary>
[Test]
public void CanMultiplyVectorByScalarIntoResultVector()
{
var vector = CreateVector(Data);
var result = CreateVector(Data.Length);
vector.Multiply(2.0, result);
for (var i = 0; i < Data.Length; i++)
{
Assert.AreEqual(Data[i], vector[i], "Making sure the original vector wasn't modified.");
Assert.AreEqual(Data[i] * 2.0, result[i]);
}
vector.Multiply(1.0, result);
for (var i = 0; i < Data.Length; i++)
{
Assert.AreEqual(Data[i], result[i]);
}
}
/// <summary>
/// Multiplying by scalar with wrong result vector size throws <c>ArgumentException</c>.
/// </summary>
[Test]
public void MultiplyingScalarWithWrongSizeResultVectorThrowsArgumentException()
{
var vector = CreateVector(Data.Length);
var result = CreateVector(Data.Length + 1);
Assert.That(() => vector.Multiply(0.0, result), Throws.ArgumentException);
}
/// <summary>
/// Dividing by scalar with wrong result vector size throws <c>ArgumentException</c>.
/// </summary>
[Test]
public void DividingScalarWithWrongSizeResultVectorThrowsArgumentException()
{
var vector = CreateVector(Data.Length);
var result = CreateVector(Data.Length + 1);
Assert.That(() => vector.Divide(0.0, result), Throws.ArgumentException);
}
/// <summary>
/// Can multiply a vector by scalar using operators.
/// </summary>
[Test]
public void CanMultiplyVectorByScalarUsingOperators()
{
var vector = CreateVector(Data);
vector = vector * 2.0;
for (var i = 0; i < Data.Length; i++)
{
Assert.AreEqual(Data[i] * 2.0, vector[i]);
}
vector = vector * 1.0;
for (var i = 0; i < Data.Length; i++)
{
Assert.AreEqual(Data[i] * 2.0, vector[i]);
}
vector = CreateVector(Data);
vector = 2.0 * vector;
for (var i = 0; i < Data.Length; i++)
{
Assert.AreEqual(Data[i] * 2.0, vector[i]);
}
vector = 1.0 * vector;
for (var i = 0; i < Data.Length; i++)
{
Assert.AreEqual(Data[i] * 2.0, vector[i]);
}
}
/// <summary>
/// Can divide a vector by scalar using operators.
/// </summary>
[Test]
public void CanDivideVectorByScalarUsingOperators()
{
var vector = CreateVector(Data);
vector = vector / 2.0;
for (var i = 0; i < Data.Length; i++)
{
Assert.AreEqual(Data[i] / 2.0, vector[i]);
}
vector = vector / 1.0;
for (var i = 0; i < Data.Length; i++)
{
Assert.AreEqual(Data[i] / 2.0, vector[i]);
}
}
/// <summary>
/// Can calculate the dot product
/// </summary>
[Test]
public void CanDotProduct()
{
var dataA = CreateVector(Data);
var dataB = CreateVector(Data);
Assert.AreEqual(55.0, dataA.DotProduct(dataB));
}
/// <summary>
/// Dot product throws <c>ArgumentException</c> when an argument has different size
/// </summary>
[Test]
public void DotProductWhenDifferentSizeThrowsArgumentException()
{
var dataA = CreateVector(Data);
var dataB = CreateVector(new double[] { 1, 2, 3, 4, 5, 6 });
Assert.That(() => dataA.DotProduct(dataB), Throws.ArgumentException);
}
/// <summary>
/// Can calculate the dot product using "*" operator.
/// </summary>
[Test]
public void CanDotProductUsingOperator()
{
var dataA = CreateVector(Data);
var dataB = CreateVector(Data);
Assert.AreEqual(55.0, dataA * dataB);
}
/// <summary>
/// Operator "*" throws <c>ArgumentException</c> when the argument has different size.
/// </summary>
[Test]
public void OperatorDotProductWhenDifferentSizeThrowsArgumentException()
{
var dataA = CreateVector(Data);
var dataB = CreateVector(new double[] { 1, 2, 3, 4, 5, 6 });
Assert.Throws<ArgumentException>(() => { var d = dataA * dataB; });
}
/// <summary>
/// Can pointwise multiply two vectors.
/// </summary>
[Test]
public void CanPointwiseMultiply()
{
var vector1 = CreateVector(Data);
var vector2 = vector1.Clone();
var result = vector1.PointwiseMultiply(vector2);
for (var i = 0; i < vector1.Count; i++)
{
Assert.AreEqual(Data[i] * Data[i], result[i]);
}
}
/// <summary>
/// Can pointwise multiply two vectors using a result vector.
/// </summary>
[Test]
public void CanPointwiseMultiplyIntoResultVector()
{
var vector1 = CreateVector(Data);
var vector2 = vector1.Clone();
var result = CreateVector(vector1.Count);
vector1.PointwiseMultiply(vector2, result);
for (var i = 0; i < vector1.Count; i++)
{
Assert.AreEqual(Data[i] * Data[i], result[i]);
}
}
/// <summary>
/// Pointwise multiply with a result vector wrong size throws <c>ArgumentException</c>.
/// </summary>
[Test]
public void PointwiseMultiplyWithInvalidResultLengthThrowsArgumentException()
{
var vector1 = CreateVector(Data);
var vector2 = vector1.Clone();
var result = CreateVector(vector1.Count + 1);
Assert.That(() => vector1.PointwiseMultiply(vector2, result), Throws.ArgumentException);
}
/// <summary>
/// Can pointwise divide two vectors using a result vector.
/// </summary>
[Test]
public void CanPointWiseDivide()
{
var vector1 = CreateVector(Data);
var vector2 = vector1.Clone();
var result = vector1.PointwiseDivide(vector2);
for (var i = 0; i < vector1.Count; i++)
{
Assert.AreEqual(Data[i] / Data[i], result[i]);
}
}
/// <summary>
/// Can pointwise divide two vectors using a result vector.
/// </summary>
[Test]
public void CanPointWiseDivideIntoResultVector()
{
var vector1 = CreateVector(Data);
var vector2 = vector1.Clone();
var result = CreateVector(vector1.Count);
vector1.PointwiseDivide(vector2, result);
for (var i = 0; i < vector1.Count; i++)
{
Assert.AreEqual(Data[i] / Data[i], result[i]);
}
}
/// <summary>
/// Pointwise divide with a result vector wrong size throws <c>ArgumentException</c>.
/// </summary>
[Test]
public void PointwiseDivideWithInvalidResultLengthThrowsArgumentException()
{
var vector1 = CreateVector(Data);
var vector2 = vector1.Clone();
var result = CreateVector(vector1.Count + 1);
Assert.That(() => vector1.PointwiseDivide(vector2, result), Throws.ArgumentException);
}
/// <summary>
/// Can calculate the outer product of two vectors.
/// </summary>
[Test]
public void CanCalculateOuterProduct()
{
var vector1 = CreateVector(Data);
var vector2 = CreateVector(Data);
var m = Vector<double>.OuterProduct(vector1, vector2);
for (var i = 0; i < vector1.Count; i++)
{
for (var j = 0; j < vector2.Count; j++)
{
Assert.AreEqual(m[i, j], vector1[i] * vector2[j]);
}
}
}
/// <summary>
/// Can calculate the tensor multiply.
/// </summary>
[Test]
public void CanCalculateTensorMultiply()
{
var vector1 = CreateVector(Data);
var vector2 = CreateVector(Data);
var m = vector1.OuterProduct(vector2);
for (var i = 0; i < vector1.Count; i++)
{
for (var j = 0; j < vector2.Count; j++)
{
Assert.AreEqual(m[i, j], vector1[i] * vector2[j]);
}
}
}
[Test]
public void CanComputeRemainderUsingOperator()
{
var vector = CreateVector(Data);
var mod = vector % (-4.5);
for (var index = 0; index < Data.Length; index++)
{
AssertHelpers.AlmostEqualRelative(Euclid.Remainder(Data[index], -4.5), mod[index], 14);
}
}
[Test]
public void CanComputeRemainder()
{
var vector = CreateVector(Data);
var mod = vector.Remainder(-3.2);
for (var index = 0; index < Data.Length; index++)
{
AssertHelpers.AlmostEqualRelative(Euclid.Remainder(Data[index], -3.2), mod[index], 14);
}
}
[Test]
public void CanComputeRemainderUsingResultVector()
{
var vector = CreateVector(Data);
var mod = CreateVector(vector.Count);
vector.Remainder(-3.2, mod);
for (var index = 0; index < Data.Length; index++)
{
AssertHelpers.AlmostEqualRelative(Euclid.Remainder(Data[index], -3.2), mod[index], 14);
}
}
[Test]
public void CanComputeRemainderUsingSameResultVector()
{
var vector = CreateVector(Data);
vector.Remainder(-3.2, vector);
for (var index = 0; index < Data.Length; index++)
{
AssertHelpers.AlmostEqualRelative(Euclid.Remainder(Data[index], -3.2), vector[index], 14);
}
}
[Test]
public void CanComputeModulus()
{
var vector = CreateVector(Data);
var mod = vector.Modulus(-3.2);
for (var index = 0; index < Data.Length; index++)
{
AssertHelpers.AlmostEqualRelative(Euclid.Modulus(Data[index], -3.2), mod[index], 14);
}
}
[Test]
public void CanComputeModulusUsingResultVector()
{
var vector = CreateVector(Data);
var mod = CreateVector(vector.Count);
vector.Modulus(-3.2, mod);
for (var index = 0; index < Data.Length; index++)
{
AssertHelpers.AlmostEqualRelative(Euclid.Modulus(Data[index], -3.2), mod[index], 14);
}
}
[Test]
public void CanComputeModulusUsingSameResultVector()
{
var vector = CreateVector(Data);
vector.Modulus(-3.2, vector);
for (var index = 0; index < Data.Length; index++)
{
AssertHelpers.AlmostEqualRelative(Euclid.Modulus(Data[index], -3.2), vector[index], 14);
}
}
}
}
| |
// Copyright (c) 2007, Clarius Consulting, Manas Technology Solutions, InSTEDD, and Contributors.
// All rights reserved. Licensed under the BSD 3-Clause License; see License.txt.
using System;
using System.Linq;
using Xunit;
namespace Moq.Tests
{
public class ItIsAnyTypeFixture
{
[Fact]
public void Setup_without_It_IsAnyType()
{
var mock = new Mock<IX>();
mock.Setup(x => x.Method<object>());
mock.Setup(x => x.Method<bool>());
mock.Setup(x => x.Method<int>());
mock.Setup(x => x.Method<string>());
mock.Object.Method<bool>();
mock.Object.Method<int>();
mock.Object.Method<object>();
mock.Object.Method<string>();
mock.VerifyAll();
}
[Fact]
public void Setup_with_It_IsAnyType()
{
var invocationCount = 0;
var mock = new Mock<IX>();
mock.Setup(x => x.Method<It.IsAnyType>()).Callback(() => invocationCount++);
mock.Object.Method<bool>();
mock.Object.Method<int>();
mock.Object.Method<object>();
mock.Object.Method<string>();
Assert.Equal(4, invocationCount);
}
[Fact]
public void Verify_with_It_IsAnyType()
{
var mock = new Mock<IX>();
mock.Object.Method<bool>();
mock.Object.Method<int>();
mock.Object.Method<object>();
mock.Object.Method<string>();
mock.Verify(x => x.Method<It.IsAnyType>(), Times.Exactly(4));
}
[Fact]
public void Setup_with_It_IsAnyType_and_Callback()
{
object received = null;
var mock = new Mock<IY>();
mock.Setup(m => m.Method<It.IsAnyType>((It.IsAnyType)It.IsAny<object>()))
.Callback((object arg) => received = arg);
_ = mock.Object.Method<int>(42);
Assert.Equal(42, received);
}
[Fact]
public void Setup_with_It_IsAnyType_and_Returns()
{
var mock = new Mock<IY>();
mock.Setup(m => m.Method<It.IsAnyType>((It.IsAnyType)It.IsAny<object>()))
.Returns(new Func<object, object>(arg => arg));
Assert.Equal(42, mock.Object.Method<int>(42));
Assert.Equal("42", mock.Object.Method<string>("42"));
}
[Fact]
public void Setup_with_It_IsAnyType_default_return_value()
{
var mock = new Mock<IY>() { DefaultValue = DefaultValue.Empty };
mock.Setup(m => m.Method<It.IsAnyType>((It.IsAnyType)It.IsAny<object>()));
var result = mock.Object.Method<int[]>(null);
// Let's make sure that default value providers don't suddenly start producing `It.IsAnyType` instances:
Assert.IsNotType<It.IsAnyType>(result);
// Rather, we expect the usual behavior:
Assert.NotNull(result);
Assert.IsType<int[]>(result);
Assert.Empty((int[])result);
}
[Fact]
public void Type_arguments_can_be_discovered_in_Callback_through_a_InvocationAction_callback()
{
Type typeArgument = null;
var mock = new Mock<IZ>();
mock.Setup(z => z.Method<It.IsAnyType>()).Callback(new InvocationAction(invocation =>
{
typeArgument = invocation.Method.GetGenericArguments()[0];
}));
_ = mock.Object.Method<string>();
Assert.Equal(typeof(string), typeArgument);
}
[Fact]
public void Type_arguments_can_be_discovered_in_Returns_through_a_InvocationFunc_callback()
{
var mock = new Mock<IZ>();
mock.Setup(z => z.Method<It.IsAnyType>()).Returns(new InvocationFunc(invocation =>
{
var typeArgument = invocation.Method.GetGenericArguments()[0];
return Activator.CreateInstance(typeArgument);
}));
var result = mock.Object.Method<DateTime>();
Assert.IsType<DateTime>(result);
Assert.Equal(default(DateTime), result);
}
[Fact]
public void Setup_with_It_IsAny_It_IsAnyType()
{
object received = null;
var mock = new Mock<IY>();
mock.Setup(m => m.Method(It.IsAny<It.IsAnyType>()))
.Callback((object arg) => received = arg);
_ = mock.Object.Method<int>(42);
Assert.Equal(42, received);
_ = mock.Object.Method<string>("42");
Assert.Equal("42", received);
}
[Fact]
public void Setup_with_It_IsNotNull_It_IsAnyType()
{
var invocationCount = 0;
var mock = new Mock<IY>();
mock.Setup(m => m.Method(It.IsNotNull<It.IsAnyType>()))
.Callback((object arg) => invocationCount++);
_ = mock.Object.Method<string>("42");
Assert.Equal(1, invocationCount);
_ = mock.Object.Method<string>(null);
Assert.Equal(1, invocationCount);
_ = mock.Object.Method<int>(42);
Assert.Equal(2, invocationCount);
_ = mock.Object.Method<int?>(42);
Assert.Equal(3, invocationCount);
_ = mock.Object.Method<int?>(null);
Assert.Equal(3, invocationCount);
}
[Fact]
public void Setup_with_It_Is_It_IsAnyType()
{
var acceptableArgs = new object[] { 42, "42" };
var invocationCount = 0;
var mock = new Mock<IY>();
mock.Setup(m => m.Method(It.Is<It.IsAnyType>((x, _) => acceptableArgs.Contains(x))))
.Callback((object arg) => invocationCount++);
_ = mock.Object.Method<string>("42");
Assert.Equal(1, invocationCount);
_ = mock.Object.Method<string>("7");
Assert.Equal(1, invocationCount);
_ = mock.Object.Method<int>(42);
Assert.Equal(2, invocationCount);
_ = mock.Object.Method<int>(7);
Assert.Equal(2, invocationCount);
}
[Fact]
public void It_Is_It_IsAnyType_will_throw_when_predicate_uninvokable()
{
Action useMatcher = () => _ = It.Is<It.IsAnyType>(arg => true);
// ^^^
// When used like this, the predicate will have static type `It.IsAnyType`,
// and no *actual* argument will ever be of that type; therefore, we expect
// Moq to mark this as illegal use.
Assert.Throws<ArgumentException>(useMatcher);
}
[Fact]
public void Setup_with_It_Ref_It_IsAnyType_IsAny()
{
object received = null;
var mock = new Mock<IY>();
mock.Setup(m => m.ByRefMethod(ref It.Ref<It.IsAnyType>.IsAny))
.Callback(new ByRefMethodCallback<object>((ref object arg) => received = arg));
var i = 42;
_ = mock.Object.ByRefMethod<int>(ref i);
Assert.Equal(42, received);
var s = "42";
_ = mock.Object.ByRefMethod<string>(ref s);
Assert.Equal("42", received);
}
public interface IX
{
void Method<T>();
}
public interface IY
{
T Method<T>(T arg);
T ByRefMethod<T>(ref T arg);
}
public delegate void ByRefMethodCallback<T>(ref T arg);
public interface IZ
{
T Method<T>();
}
}
}
| |
using System;
using System.Reflection;
using System.Linq;
using NServiceKit.Text;
namespace NServiceKit.Common.Reflection
{
#if MONOTOUCH || SILVERLIGHT
public static class StaticAccessors
{
}
#else
using System.Linq.Expressions;
/// <summary>A static accessors.</summary>
public static class StaticAccessors
{
/// <summary>Gets value getter.</summary>
///
/// <exception cref="ArgumentException">Thrown when one or more arguments have unsupported or illegal values.</exception>
///
/// <param name="type"> The type.</param>
/// <param name="propertyInfo">The propertyInfo to act on.</param>
///
/// <returns>The value getter.</returns>
public static Func<object, object> GetValueGetter(Type type, PropertyInfo propertyInfo)
{
if (type != propertyInfo.DeclaringType)
{
throw new ArgumentException();
}
var instance = Expression.Parameter(typeof(object), "i");
var convertInstance = Expression.TypeAs(instance, propertyInfo.DeclaringType);
var property = Expression.Property(convertInstance, propertyInfo);
var convertProperty = Expression.TypeAs(property, typeof(object));
return Expression.Lambda<Func<object, object>>(convertProperty, instance).Compile();
}
/// <summary>A PropertyInfo extension method that gets value getter.</summary>
///
/// <exception cref="ArgumentException">Thrown when one or more arguments have unsupported or illegal values.</exception>
///
/// <typeparam name="T">Generic type parameter.</typeparam>
/// <param name="propertyInfo">The propertyInfo to act on.</param>
///
/// <returns>The value getter.</returns>
public static Func<T, object> GetValueGetter<T>(this PropertyInfo propertyInfo)
{
if (typeof(T) != propertyInfo.DeclaringType)
{
throw new ArgumentException();
}
var instance = Expression.Parameter(propertyInfo.DeclaringType, "i");
var property = Expression.Property(instance, propertyInfo);
var convert = Expression.TypeAs(property, typeof(object));
return Expression.Lambda<Func<T, object>>(convert, instance).Compile();
}
/// <summary>A PropertyInfo extension method that gets value setter.</summary>
///
/// <exception cref="ArgumentException">Thrown when one or more arguments have unsupported or illegal values.</exception>
///
/// <typeparam name="T">Generic type parameter.</typeparam>
/// <param name="propertyInfo">The propertyInfo to act on.</param>
///
/// <returns>The value setter.</returns>
public static Action<T, object> GetValueSetter<T>(this PropertyInfo propertyInfo)
{
if (typeof(T) != propertyInfo.DeclaringType)
{
throw new ArgumentException();
}
var instance = Expression.Parameter(propertyInfo.DeclaringType, "i");
var argument = Expression.Parameter(typeof(object), "a");
var setterCall = Expression.Call(
instance,
propertyInfo.GetSetMethod(),
Expression.Convert(argument, propertyInfo.PropertyType));
return Expression.Lambda<Action<T, object>>
(
setterCall, instance, argument
).Compile();
}
}
#endif
/// <summary>A static accessors.</summary>
/// <typeparam name="TEntity">Type of the entity.</typeparam>
public static class StaticAccessors<TEntity>
{
/// <summary>
/// Func to get the Strongly-typed field
/// </summary>
public static Func<TEntity, TId> TypedGetPropertyFn<TId>(PropertyInfo pi)
{
var mi = pi.GetMethodInfo();
return (Func<TEntity, TId>)mi.MakeDelegate(typeof(Func<TEntity, TId>));
}
/// <summary>
/// Required to cast the return ValueType to an object for caching
/// </summary>
public static Func<TEntity, object> ValueUnTypedGetPropertyFn<TId>(PropertyInfo pi)
{
var typedPropertyFn = TypedGetPropertyFn<TId>(pi);
return x => typedPropertyFn(x);
}
/// <summary>Value un typed get property type function.</summary>
///
/// <param name="pi">The pi.</param>
///
/// <returns>A Func<TEntity,object></returns>
public static Func<TEntity, object> ValueUnTypedGetPropertyTypeFn(PropertyInfo pi)
{
var mi = typeof(StaticAccessors<TEntity>).GetMethodInfo("TypedGetPropertyFn");
var genericMi = mi.MakeGenericMethod(pi.PropertyType);
var typedGetPropertyFn = (Delegate)genericMi.Invoke(null, new[] { pi });
#if MONOTOUCH || SILVERLIGHT || NETFX_CORE
return x => typedGetPropertyFn.InvokeMethod(x);
#else
var typedMi = typedGetPropertyFn.Method;
var paramFunc = Expression.Parameter(typeof(object), "oFunc");
var expr = Expression.Lambda<Func<TEntity, object>>(
Expression.Convert(
Expression.Call(
Expression.Convert(paramFunc, typedMi.DeclaringType),
typedMi
),
typeof(object)
),
paramFunc
);
return expr.Compile();
#endif
}
/// <summary>Un typed get property function.</summary>
///
/// <typeparam name="TId">Type of the identifier.</typeparam>
/// <param name="pi">The pi.</param>
///
/// <returns>A Func<object,object></returns>
public static Func<object, object> UnTypedGetPropertyFn<TId>(PropertyInfo pi)
{
var typedPropertyFn = TypedGetPropertyFn<TId>(pi);
return x => typedPropertyFn((TEntity)x);
}
/// <summary>
/// Func to set the Strongly-typed field
/// </summary>
public static Action<TEntity, TId> TypedSetPropertyFn<TId>(PropertyInfo pi)
{
var mi = pi.SetMethod();
return (Action<TEntity, TId>)mi.MakeDelegate(typeof(Action<TEntity, TId>));
}
/// <summary>
/// Required to cast the ValueType to an object for caching
/// </summary>
public static Action<TEntity, object> ValueUnTypedSetPropertyFn<TId>(PropertyInfo pi)
{
var typedPropertyFn = TypedSetPropertyFn<TId>(pi);
return (x, y) => typedPropertyFn(x, (TId)y);
}
/// <summary>Value un typed set property type function.</summary>
///
/// <param name="pi">The pi.</param>
///
/// <returns>An Action<TEntity,object></returns>
public static Action<TEntity, object> ValueUnTypedSetPropertyTypeFn(PropertyInfo pi)
{
var mi = typeof(StaticAccessors<TEntity>).GetMethodInfo("TypedSetPropertyFn");
var genericMi = mi.MakeGenericMethod(pi.PropertyType);
var typedSetPropertyFn = (Delegate)genericMi.Invoke(null, new[] { pi });
#if MONOTOUCH || SILVERLIGHT || NETFX_CORE
return (x, y) => typedSetPropertyFn.InvokeMethod(x, new[] { y });
#else
var typedMi = typedSetPropertyFn.Method;
var paramFunc = Expression.Parameter(typeof(object), "oFunc");
var paramValue = Expression.Parameter(typeof(object), "oValue");
var expr = Expression.Lambda<Action<TEntity, object>>(
Expression.Call(
Expression.Convert(paramFunc, typedMi.DeclaringType),
typedMi,
Expression.Convert(paramValue, pi.PropertyType)
),
paramFunc,
paramValue
);
return expr.Compile();
#endif
}
/// <summary>
/// Required to cast the ValueType to an object for caching
/// </summary>
public static Action<object, object> UnTypedSetPropertyFn<TId>(PropertyInfo pi)
{
var typedPropertyFn = TypedSetPropertyFn<TId>(pi);
return (x, y) => typedPropertyFn((TEntity)x, (TId)y);
}
}
}
| |
// 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 0.16.0.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Management.Network
{
using System;
using System.Collections;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Models;
/// <summary>
/// Extension methods for RouteTablesOperations.
/// </summary>
public static partial class RouteTablesOperationsExtensions
{
/// <summary>
/// The Delete RouteTable operation deletes the specified Route Table
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='routeTableName'>
/// The name of the route table.
/// </param>
public static void Delete(this IRouteTablesOperations operations, string resourceGroupName, string routeTableName)
{
Task.Factory.StartNew(s => ((IRouteTablesOperations)s).DeleteAsync(resourceGroupName, routeTableName), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// The Delete RouteTable operation deletes the specified Route Table
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='routeTableName'>
/// The name of the route table.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task DeleteAsync(this IRouteTablesOperations operations, string resourceGroupName, string routeTableName, CancellationToken cancellationToken = default(CancellationToken))
{
await operations.DeleteWithHttpMessagesAsync(resourceGroupName, routeTableName, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// The Delete RouteTable operation deletes the specified Route Table
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='routeTableName'>
/// The name of the route table.
/// </param>
public static void BeginDelete(this IRouteTablesOperations operations, string resourceGroupName, string routeTableName)
{
Task.Factory.StartNew(s => ((IRouteTablesOperations)s).BeginDeleteAsync(resourceGroupName, routeTableName), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// The Delete RouteTable operation deletes the specified Route Table
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='routeTableName'>
/// The name of the route table.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task BeginDeleteAsync(this IRouteTablesOperations operations, string resourceGroupName, string routeTableName, CancellationToken cancellationToken = default(CancellationToken))
{
await operations.BeginDeleteWithHttpMessagesAsync(resourceGroupName, routeTableName, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// The Get RouteTables operation retrieves information about the specified
/// route table.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='routeTableName'>
/// The name of the route table.
/// </param>
/// <param name='expand'>
/// expand references resources.
/// </param>
public static RouteTable Get(this IRouteTablesOperations operations, string resourceGroupName, string routeTableName, string expand = default(string))
{
return Task.Factory.StartNew(s => ((IRouteTablesOperations)s).GetAsync(resourceGroupName, routeTableName, expand), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// The Get RouteTables operation retrieves information about the specified
/// route table.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='routeTableName'>
/// The name of the route table.
/// </param>
/// <param name='expand'>
/// expand references resources.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<RouteTable> GetAsync(this IRouteTablesOperations operations, string resourceGroupName, string routeTableName, string expand = default(string), CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetWithHttpMessagesAsync(resourceGroupName, routeTableName, expand, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// The Put RouteTable operation creates/updates a route table in the
/// specified resource group.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='routeTableName'>
/// The name of the route table.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to the create/update Route Table operation
/// </param>
public static RouteTable CreateOrUpdate(this IRouteTablesOperations operations, string resourceGroupName, string routeTableName, RouteTable parameters)
{
return Task.Factory.StartNew(s => ((IRouteTablesOperations)s).CreateOrUpdateAsync(resourceGroupName, routeTableName, parameters), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// The Put RouteTable operation creates/updates a route table in the
/// specified resource group.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='routeTableName'>
/// The name of the route table.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to the create/update Route Table operation
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<RouteTable> CreateOrUpdateAsync(this IRouteTablesOperations operations, string resourceGroupName, string routeTableName, RouteTable parameters, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.CreateOrUpdateWithHttpMessagesAsync(resourceGroupName, routeTableName, parameters, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// The Put RouteTable operation creates/updates a route table in the
/// specified resource group.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='routeTableName'>
/// The name of the route table.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to the create/update Route Table operation
/// </param>
public static RouteTable BeginCreateOrUpdate(this IRouteTablesOperations operations, string resourceGroupName, string routeTableName, RouteTable parameters)
{
return Task.Factory.StartNew(s => ((IRouteTablesOperations)s).BeginCreateOrUpdateAsync(resourceGroupName, routeTableName, parameters), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// The Put RouteTable operation creates/updates a route table in the
/// specified resource group.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='routeTableName'>
/// The name of the route table.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to the create/update Route Table operation
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<RouteTable> BeginCreateOrUpdateAsync(this IRouteTablesOperations operations, string resourceGroupName, string routeTableName, RouteTable parameters, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.BeginCreateOrUpdateWithHttpMessagesAsync(resourceGroupName, routeTableName, parameters, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// The list RouteTables returns all route tables in a resource group
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
public static IPage<RouteTable> List(this IRouteTablesOperations operations, string resourceGroupName)
{
return Task.Factory.StartNew(s => ((IRouteTablesOperations)s).ListAsync(resourceGroupName), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// The list RouteTables returns all route tables in a resource group
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<RouteTable>> ListAsync(this IRouteTablesOperations operations, string resourceGroupName, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListWithHttpMessagesAsync(resourceGroupName, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// The list RouteTables returns all route tables in a subscription
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
public static IPage<RouteTable> ListAll(this IRouteTablesOperations operations)
{
return Task.Factory.StartNew(s => ((IRouteTablesOperations)s).ListAllAsync(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// The list RouteTables returns all route tables in a subscription
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<RouteTable>> ListAllAsync(this IRouteTablesOperations operations, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListAllWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// The list RouteTables returns all route tables in a resource group
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
public static IPage<RouteTable> ListNext(this IRouteTablesOperations operations, string nextPageLink)
{
return Task.Factory.StartNew(s => ((IRouteTablesOperations)s).ListNextAsync(nextPageLink), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// The list RouteTables returns all route tables in a resource group
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<RouteTable>> ListNextAsync(this IRouteTablesOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// The list RouteTables returns all route tables in a subscription
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
public static IPage<RouteTable> ListAllNext(this IRouteTablesOperations operations, string nextPageLink)
{
return Task.Factory.StartNew(s => ((IRouteTablesOperations)s).ListAllNextAsync(nextPageLink), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// The list RouteTables returns all route tables in a subscription
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<RouteTable>> ListAllNextAsync(this IRouteTablesOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListAllNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
}
}
| |
// Copyright (c) 2021 Alachisoft
//
// 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.Runtime.InteropServices;
using System.Text;
namespace Alachisoft.NCache.Common
{
/// <summary>
/// Helper class to encrypt and decrypt connection string info
/// </summary>
public class Protector
{
public static string DecryptString(string txtString)
{
// If the variable is blank, return the input
if (txtString.Equals(string.Empty))
{
return txtString;
}
// Create an instance of the encryption API
// We assume the key has been encrypted on this machine and not by a user
DataProtector dp = new DataProtector(Store.Machine);
// Use the API to decrypt the connection string
// API works with bytes so we need to convert to and from byte arrays
byte[] decryptedData = dp.Decrypt(Convert.FromBase64String(txtString), null);
// Return the decyrpted data to the string
return Encoding.ASCII.GetString(decryptedData);
}
public static string EncryptString(string encryptedString)
{
// Create an instance of the encryption API
// We assume the key has been encrypted on this machine and not by a user
DataProtector dp = new DataProtector(Store.Machine);
// Use the API to encrypt the connection string
// API works with bytes so we need to convert to and from byte arrays
byte[] dataBytes = Encoding.ASCII.GetBytes(encryptedString);
byte[] encryptedBytes = dp.Encrypt(dataBytes, null);
// Return the encyrpted data to the string
return Convert.ToBase64String(encryptedBytes);
}
private enum Store { Machine = 1, User };
/// <summary>
/// The DSAPI wrapper
/// To be released as part of the Microsoft Configuration Building Block
/// </summary>
private class DataProtector
{
#region Constants
static private IntPtr NullPtr = ((IntPtr)((int)(0)));
private const int CRYPTPROTECT_UI_FORBIDDEN = 0x1;
private const int CRYPTPROTECT_LOCAL_MACHINE = 0x4;
private Store store;
#endregion
#region P/Invoke structures
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
internal struct DATA_BLOB
{
public int cbData;
public IntPtr pbData;
}
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
internal struct CRYPTPROTECT_PROMPTSTRUCT
{
public int cbSize;
public int dwPromptFlags;
public IntPtr hwndApp;
public String szPrompt;
}
#endregion
#region External methods
[DllImport("Crypt32.dll", SetLastError = true, CharSet = CharSet.Auto)]
private static extern bool CryptProtectData(
ref DATA_BLOB pDataIn,
String szDataDescr,
ref DATA_BLOB pOptionalEntropy,
IntPtr pvReserved,
ref CRYPTPROTECT_PROMPTSTRUCT
pPromptStruct,
int dwFlags,
ref DATA_BLOB pDataOut);
[DllImport("Crypt32.dll", SetLastError = true, CharSet = CharSet.Auto)]
private static extern bool CryptUnprotectData(
ref DATA_BLOB pDataIn,
String szDataDescr,
ref DATA_BLOB pOptionalEntropy,
IntPtr pvReserved,
ref CRYPTPROTECT_PROMPTSTRUCT
pPromptStruct,
int dwFlags,
ref DATA_BLOB pDataOut);
[DllImport("kernel32.dll", CharSet = CharSet.Auto)]
private unsafe static extern int FormatMessage(int dwFlags,
ref IntPtr lpSource,
int dwMessageId,
int dwLanguageId,
ref String lpBuffer,
int nSize,
IntPtr* Arguments);
#endregion
#region Constructor
public DataProtector(Store tempStore)
{
store = tempStore;
}
#endregion
#region Public methods
public byte[] Encrypt(byte[] plainText, byte[] optionalEntropy)
{
bool retVal = false;
DATA_BLOB plainTextBlob = new DATA_BLOB();
DATA_BLOB cipherTextBlob = new DATA_BLOB();
DATA_BLOB entropyBlob = new DATA_BLOB();
CRYPTPROTECT_PROMPTSTRUCT prompt = new CRYPTPROTECT_PROMPTSTRUCT();
InitPromptstruct(ref prompt);
int dwFlags;
try
{
try
{
int bytesSize = plainText.Length;
plainTextBlob.pbData = Marshal.AllocHGlobal(bytesSize);
if (IntPtr.Zero == plainTextBlob.pbData)
{
throw new Exception("Unable to allocate plaintext buffer.");
}
plainTextBlob.cbData = bytesSize;
Marshal.Copy(plainText, 0, plainTextBlob.pbData, bytesSize);
}
catch (Exception ex)
{
throw new Exception("Exception marshalling data. " + ex.Message);
}
if (Store.Machine == store)
{
//Using the machine store, should be providing entropy.
dwFlags = CRYPTPROTECT_LOCAL_MACHINE | CRYPTPROTECT_UI_FORBIDDEN;
//Check to see if the entropy is null
if (null == optionalEntropy)
{
//Allocate something
optionalEntropy = new byte[0];
}
try
{
int bytesSize = optionalEntropy.Length;
entropyBlob.pbData = Marshal.AllocHGlobal(optionalEntropy.Length);
if (IntPtr.Zero == entropyBlob.pbData)
{
throw new Exception("Unable to allocate entropy data buffer.");
}
Marshal.Copy(optionalEntropy, 0, entropyBlob.pbData, bytesSize);
entropyBlob.cbData = bytesSize;
}
catch (Exception ex)
{
throw new Exception("Exception entropy marshalling data. " + ex.Message);
}
}
else
{
//Using the user store
dwFlags = CRYPTPROTECT_UI_FORBIDDEN;
}
retVal = CryptProtectData(ref plainTextBlob, "", ref entropyBlob,
IntPtr.Zero, ref prompt, dwFlags, ref cipherTextBlob);
if (false == retVal)
{
throw new Exception("Encryption failed. " + GetErrorMessage(Marshal.GetLastWin32Error()));
}
}
catch (Exception ex)
{
throw new Exception("Exception encrypting. " + ex.Message);
}
byte[] cipherText = new byte[cipherTextBlob.cbData];
Marshal.Copy(cipherTextBlob.pbData, cipherText, 0, cipherTextBlob.cbData);
return cipherText;
}
public byte[] Decrypt(byte[] cipherText, byte[] optionalEntropy)
{
bool retVal = false;
DATA_BLOB plainTextBlob = new DATA_BLOB();
DATA_BLOB cipherBlob = new DATA_BLOB();
CRYPTPROTECT_PROMPTSTRUCT prompt = new CRYPTPROTECT_PROMPTSTRUCT();
InitPromptstruct(ref prompt);
try
{
try
{
int cipherTextSize = cipherText.Length;
cipherBlob.pbData = Marshal.AllocHGlobal(cipherTextSize);
if (IntPtr.Zero == cipherBlob.pbData)
{
throw new Exception("Unable to allocate cipherText buffer.");
}
cipherBlob.cbData = cipherTextSize;
Marshal.Copy(cipherText, 0, cipherBlob.pbData, cipherBlob.cbData);
}
catch (Exception ex)
{
throw new Exception("Exception marshalling data. " + ex.Message);
}
DATA_BLOB entropyBlob = new DATA_BLOB();
int dwFlags;
if (Store.Machine == store)
{
//Using the machine store, should be providing entropy.
dwFlags = CRYPTPROTECT_LOCAL_MACHINE | CRYPTPROTECT_UI_FORBIDDEN;
//Check to see if the entropy is null
if (null == optionalEntropy)
{
//Allocate something
optionalEntropy = new byte[0];
}
try
{
int bytesSize = optionalEntropy.Length;
entropyBlob.pbData = Marshal.AllocHGlobal(bytesSize);
if (IntPtr.Zero == entropyBlob.pbData)
{
throw new Exception("Unable to allocate entropy buffer.");
}
entropyBlob.cbData = bytesSize;
Marshal.Copy(optionalEntropy, 0, entropyBlob.pbData, bytesSize);
}
catch (Exception ex)
{
throw new Exception("Exception entropy marshalling data. " + ex.Message);
}
}
else
{
//Using the user store
dwFlags = CRYPTPROTECT_UI_FORBIDDEN;
}
retVal = CryptUnprotectData(ref cipherBlob, null, ref
entropyBlob,
IntPtr.Zero, ref prompt, dwFlags,
ref plainTextBlob);
if (false == retVal)
{
throw new Exception("Decryption failed. " + GetErrorMessage(Marshal.GetLastWin32Error()));
}
//Free the blob and entropy.
if (IntPtr.Zero != cipherBlob.pbData)
{
Marshal.FreeHGlobal(cipherBlob.pbData);
}
if (IntPtr.Zero != entropyBlob.pbData)
{
Marshal.FreeHGlobal(entropyBlob.pbData);
}
}
catch (Exception ex)
{
throw new Exception("Exception decrypting. " + ex.Message);
}
byte[] plainText = new byte[plainTextBlob.cbData];
Marshal.Copy(plainTextBlob.pbData, plainText, 0, plainTextBlob.cbData);
return plainText;
}
#endregion
#region Private methods
private void InitPromptstruct(ref CRYPTPROTECT_PROMPTSTRUCT ps)
{
ps.cbSize = Marshal.SizeOf(typeof(CRYPTPROTECT_PROMPTSTRUCT));
ps.dwPromptFlags = 0;
ps.hwndApp = NullPtr;
ps.szPrompt = null;
}
private unsafe static String GetErrorMessage(int errorCode)
{
int FORMAT_MESSAGE_ALLOCATE_BUFFER = 0x00000100;
int FORMAT_MESSAGE_IGNORE_INSERTS = 0x00000200;
int FORMAT_MESSAGE_FROM_SYSTEM = 0x00001000;
int messageSize = 255;
String lpMsgBuf = "";
int dwFlags = FORMAT_MESSAGE_ALLOCATE_BUFFER |
FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS;
IntPtr ptrlpSource = new IntPtr();
IntPtr prtArguments = new IntPtr();
int retVal = FormatMessage(dwFlags, ref ptrlpSource, errorCode, 0,
ref lpMsgBuf, messageSize, &prtArguments);
if (0 == retVal)
{
throw new Exception("Failed to format message for error code " + errorCode + ". ");
}
return lpMsgBuf;
}
#endregion
}
}
}
| |
// 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 gagr = Google.Api.Gax.ResourceNames;
using gcev = Google.Cloud.EssentialContacts.V1;
using sys = System;
namespace Google.Cloud.EssentialContacts.V1
{
/// <summary>Resource name for the <c>Contact</c> resource.</summary>
public sealed partial class ContactName : gax::IResourceName, sys::IEquatable<ContactName>
{
/// <summary>The possible contents of <see cref="ContactName"/>.</summary>
public enum ResourceNameType
{
/// <summary>An unparsed resource name.</summary>
Unparsed = 0,
/// <summary>A resource name with pattern <c>projects/{project}/contacts/{contact}</c>.</summary>
ProjectContact = 1,
/// <summary>A resource name with pattern <c>folders/{folder}/contacts/{contact}</c>.</summary>
FolderContact = 2,
/// <summary>A resource name with pattern <c>organizations/{organization}/contacts/{contact}</c>.</summary>
OrganizationContact = 3,
}
private static gax::PathTemplate s_projectContact = new gax::PathTemplate("projects/{project}/contacts/{contact}");
private static gax::PathTemplate s_folderContact = new gax::PathTemplate("folders/{folder}/contacts/{contact}");
private static gax::PathTemplate s_organizationContact = new gax::PathTemplate("organizations/{organization}/contacts/{contact}");
/// <summary>Creates a <see cref="ContactName"/> 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="ContactName"/> containing the provided <paramref name="unparsedResourceName"/>.
/// </returns>
public static ContactName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) =>
new ContactName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName)));
/// <summary>
/// Creates a <see cref="ContactName"/> with the pattern <c>projects/{project}/contacts/{contact}</c>.
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="contactId">The <c>Contact</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>A new instance of <see cref="ContactName"/> constructed from the provided ids.</returns>
public static ContactName FromProjectContact(string projectId, string contactId) =>
new ContactName(ResourceNameType.ProjectContact, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), contactId: gax::GaxPreconditions.CheckNotNullOrEmpty(contactId, nameof(contactId)));
/// <summary>
/// Creates a <see cref="ContactName"/> with the pattern <c>folders/{folder}/contacts/{contact}</c>.
/// </summary>
/// <param name="folderId">The <c>Folder</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="contactId">The <c>Contact</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>A new instance of <see cref="ContactName"/> constructed from the provided ids.</returns>
public static ContactName FromFolderContact(string folderId, string contactId) =>
new ContactName(ResourceNameType.FolderContact, folderId: gax::GaxPreconditions.CheckNotNullOrEmpty(folderId, nameof(folderId)), contactId: gax::GaxPreconditions.CheckNotNullOrEmpty(contactId, nameof(contactId)));
/// <summary>
/// Creates a <see cref="ContactName"/> with the pattern <c>organizations/{organization}/contacts/{contact}</c>.
/// </summary>
/// <param name="organizationId">The <c>Organization</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="contactId">The <c>Contact</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>A new instance of <see cref="ContactName"/> constructed from the provided ids.</returns>
public static ContactName FromOrganizationContact(string organizationId, string contactId) =>
new ContactName(ResourceNameType.OrganizationContact, organizationId: gax::GaxPreconditions.CheckNotNullOrEmpty(organizationId, nameof(organizationId)), contactId: gax::GaxPreconditions.CheckNotNullOrEmpty(contactId, nameof(contactId)));
/// <summary>
/// Formats the IDs into the string representation of this <see cref="ContactName"/> with pattern
/// <c>projects/{project}/contacts/{contact}</c>.
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="contactId">The <c>Contact</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="ContactName"/> with pattern
/// <c>projects/{project}/contacts/{contact}</c>.
/// </returns>
public static string Format(string projectId, string contactId) => FormatProjectContact(projectId, contactId);
/// <summary>
/// Formats the IDs into the string representation of this <see cref="ContactName"/> with pattern
/// <c>projects/{project}/contacts/{contact}</c>.
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="contactId">The <c>Contact</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="ContactName"/> with pattern
/// <c>projects/{project}/contacts/{contact}</c>.
/// </returns>
public static string FormatProjectContact(string projectId, string contactId) =>
s_projectContact.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), gax::GaxPreconditions.CheckNotNullOrEmpty(contactId, nameof(contactId)));
/// <summary>
/// Formats the IDs into the string representation of this <see cref="ContactName"/> with pattern
/// <c>folders/{folder}/contacts/{contact}</c>.
/// </summary>
/// <param name="folderId">The <c>Folder</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="contactId">The <c>Contact</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="ContactName"/> with pattern
/// <c>folders/{folder}/contacts/{contact}</c>.
/// </returns>
public static string FormatFolderContact(string folderId, string contactId) =>
s_folderContact.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(folderId, nameof(folderId)), gax::GaxPreconditions.CheckNotNullOrEmpty(contactId, nameof(contactId)));
/// <summary>
/// Formats the IDs into the string representation of this <see cref="ContactName"/> with pattern
/// <c>organizations/{organization}/contacts/{contact}</c>.
/// </summary>
/// <param name="organizationId">The <c>Organization</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="contactId">The <c>Contact</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="ContactName"/> with pattern
/// <c>organizations/{organization}/contacts/{contact}</c>.
/// </returns>
public static string FormatOrganizationContact(string organizationId, string contactId) =>
s_organizationContact.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(organizationId, nameof(organizationId)), gax::GaxPreconditions.CheckNotNullOrEmpty(contactId, nameof(contactId)));
/// <summary>Parses the given resource name string into a new <see cref="ContactName"/> 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}/contacts/{contact}</c></description></item>
/// <item><description><c>folders/{folder}/contacts/{contact}</c></description></item>
/// <item><description><c>organizations/{organization}/contacts/{contact}</c></description></item>
/// </list>
/// </remarks>
/// <param name="contactName">The resource name in string form. Must not be <c>null</c>.</param>
/// <returns>The parsed <see cref="ContactName"/> if successful.</returns>
public static ContactName Parse(string contactName) => Parse(contactName, false);
/// <summary>
/// Parses the given resource name string into a new <see cref="ContactName"/> 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}/contacts/{contact}</c></description></item>
/// <item><description><c>folders/{folder}/contacts/{contact}</c></description></item>
/// <item><description><c>organizations/{organization}/contacts/{contact}</c></description></item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="contactName">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="ContactName"/> if successful.</returns>
public static ContactName Parse(string contactName, bool allowUnparsed) =>
TryParse(contactName, allowUnparsed, out ContactName 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="ContactName"/> 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}/contacts/{contact}</c></description></item>
/// <item><description><c>folders/{folder}/contacts/{contact}</c></description></item>
/// <item><description><c>organizations/{organization}/contacts/{contact}</c></description></item>
/// </list>
/// </remarks>
/// <param name="contactName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="result">
/// When this method returns, the parsed <see cref="ContactName"/>, 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 contactName, out ContactName result) => TryParse(contactName, false, out result);
/// <summary>
/// Tries to parse the given resource name string into a new <see cref="ContactName"/> 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}/contacts/{contact}</c></description></item>
/// <item><description><c>folders/{folder}/contacts/{contact}</c></description></item>
/// <item><description><c>organizations/{organization}/contacts/{contact}</c></description></item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="contactName">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="ContactName"/>, 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 contactName, bool allowUnparsed, out ContactName result)
{
gax::GaxPreconditions.CheckNotNull(contactName, nameof(contactName));
gax::TemplatedResourceName resourceName;
if (s_projectContact.TryParseName(contactName, out resourceName))
{
result = FromProjectContact(resourceName[0], resourceName[1]);
return true;
}
if (s_folderContact.TryParseName(contactName, out resourceName))
{
result = FromFolderContact(resourceName[0], resourceName[1]);
return true;
}
if (s_organizationContact.TryParseName(contactName, out resourceName))
{
result = FromOrganizationContact(resourceName[0], resourceName[1]);
return true;
}
if (allowUnparsed)
{
if (gax::UnparsedResourceName.TryParse(contactName, out gax::UnparsedResourceName unparsedResourceName))
{
result = FromUnparsed(unparsedResourceName);
return true;
}
}
result = null;
return false;
}
private ContactName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string contactId = null, string folderId = null, string organizationId = null, string projectId = null)
{
Type = type;
UnparsedResource = unparsedResourceName;
ContactId = contactId;
FolderId = folderId;
OrganizationId = organizationId;
ProjectId = projectId;
}
/// <summary>
/// Constructs a new instance of a <see cref="ContactName"/> class from the component parts of pattern
/// <c>projects/{project}/contacts/{contact}</c>
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="contactId">The <c>Contact</c> ID. Must not be <c>null</c> or empty.</param>
public ContactName(string projectId, string contactId) : this(ResourceNameType.ProjectContact, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), contactId: gax::GaxPreconditions.CheckNotNullOrEmpty(contactId, nameof(contactId)))
{
}
/// <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>Contact</c> ID. May be <c>null</c>, depending on which resource name is contained by this instance.
/// </summary>
public string ContactId { get; }
/// <summary>
/// The <c>Folder</c> ID. May be <c>null</c>, depending on which resource name is contained by this instance.
/// </summary>
public string FolderId { get; }
/// <summary>
/// The <c>Organization</c> ID. May be <c>null</c>, depending on which resource name is contained by this
/// instance.
/// </summary>
public string OrganizationId { get; }
/// <summary>
/// The <c>Project</c> ID. May be <c>null</c>, depending on which resource name is contained by this instance.
/// </summary>
public string ProjectId { 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.ProjectContact: return s_projectContact.Expand(ProjectId, ContactId);
case ResourceNameType.FolderContact: return s_folderContact.Expand(FolderId, ContactId);
case ResourceNameType.OrganizationContact: return s_organizationContact.Expand(OrganizationId, ContactId);
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 ContactName);
/// <inheritdoc/>
public bool Equals(ContactName other) => ToString() == other?.ToString();
/// <inheritdoc/>
public static bool operator ==(ContactName a, ContactName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false);
/// <inheritdoc/>
public static bool operator !=(ContactName a, ContactName b) => !(a == b);
}
public partial class Contact
{
/// <summary>
/// <see cref="gcev::ContactName"/>-typed view over the <see cref="Name"/> resource name property.
/// </summary>
public gcev::ContactName ContactName
{
get => string.IsNullOrEmpty(Name) ? null : gcev::ContactName.Parse(Name, allowUnparsed: true);
set => Name = value?.ToString() ?? "";
}
}
public partial class ListContactsRequest
{
/// <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() ?? "";
}
/// <summary>
/// <see cref="gagr::FolderName"/>-typed view over the <see cref="Parent"/> resource name property.
/// </summary>
public gagr::FolderName ParentAsFolderName
{
get => string.IsNullOrEmpty(Parent) ? null : gagr::FolderName.Parse(Parent, allowUnparsed: true);
set => Parent = value?.ToString() ?? "";
}
/// <summary>
/// <see cref="gagr::OrganizationName"/>-typed view over the <see cref="Parent"/> resource name property.
/// </summary>
public gagr::OrganizationName ParentAsOrganizationName
{
get => string.IsNullOrEmpty(Parent) ? null : gagr::OrganizationName.Parse(Parent, allowUnparsed: true);
set => Parent = value?.ToString() ?? "";
}
/// <summary>
/// <see cref="gax::IResourceName"/>-typed view over the <see cref="Parent"/> resource name property.
/// </summary>
public gax::IResourceName ParentAsResourceName
{
get
{
if (string.IsNullOrEmpty(Parent))
{
return null;
}
if (gagr::ProjectName.TryParse(Parent, out gagr::ProjectName project))
{
return project;
}
if (gagr::FolderName.TryParse(Parent, out gagr::FolderName folder))
{
return folder;
}
if (gagr::OrganizationName.TryParse(Parent, out gagr::OrganizationName organization))
{
return organization;
}
return gax::UnparsedResourceName.Parse(Parent);
}
set => Parent = value?.ToString() ?? "";
}
}
public partial class GetContactRequest
{
/// <summary>
/// <see cref="gcev::ContactName"/>-typed view over the <see cref="Name"/> resource name property.
/// </summary>
public gcev::ContactName ContactName
{
get => string.IsNullOrEmpty(Name) ? null : gcev::ContactName.Parse(Name, allowUnparsed: true);
set => Name = value?.ToString() ?? "";
}
}
public partial class DeleteContactRequest
{
/// <summary>
/// <see cref="gcev::ContactName"/>-typed view over the <see cref="Name"/> resource name property.
/// </summary>
public gcev::ContactName ContactName
{
get => string.IsNullOrEmpty(Name) ? null : gcev::ContactName.Parse(Name, allowUnparsed: true);
set => Name = value?.ToString() ?? "";
}
}
public partial class CreateContactRequest
{
/// <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() ?? "";
}
/// <summary>
/// <see cref="gagr::FolderName"/>-typed view over the <see cref="Parent"/> resource name property.
/// </summary>
public gagr::FolderName ParentAsFolderName
{
get => string.IsNullOrEmpty(Parent) ? null : gagr::FolderName.Parse(Parent, allowUnparsed: true);
set => Parent = value?.ToString() ?? "";
}
/// <summary>
/// <see cref="gagr::OrganizationName"/>-typed view over the <see cref="Parent"/> resource name property.
/// </summary>
public gagr::OrganizationName ParentAsOrganizationName
{
get => string.IsNullOrEmpty(Parent) ? null : gagr::OrganizationName.Parse(Parent, allowUnparsed: true);
set => Parent = value?.ToString() ?? "";
}
/// <summary>
/// <see cref="gax::IResourceName"/>-typed view over the <see cref="Parent"/> resource name property.
/// </summary>
public gax::IResourceName ParentAsResourceName
{
get
{
if (string.IsNullOrEmpty(Parent))
{
return null;
}
if (gagr::ProjectName.TryParse(Parent, out gagr::ProjectName project))
{
return project;
}
if (gagr::FolderName.TryParse(Parent, out gagr::FolderName folder))
{
return folder;
}
if (gagr::OrganizationName.TryParse(Parent, out gagr::OrganizationName organization))
{
return organization;
}
return gax::UnparsedResourceName.Parse(Parent);
}
set => Parent = value?.ToString() ?? "";
}
}
public partial class ComputeContactsRequest
{
/// <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() ?? "";
}
/// <summary>
/// <see cref="gagr::FolderName"/>-typed view over the <see cref="Parent"/> resource name property.
/// </summary>
public gagr::FolderName ParentAsFolderName
{
get => string.IsNullOrEmpty(Parent) ? null : gagr::FolderName.Parse(Parent, allowUnparsed: true);
set => Parent = value?.ToString() ?? "";
}
/// <summary>
/// <see cref="gagr::OrganizationName"/>-typed view over the <see cref="Parent"/> resource name property.
/// </summary>
public gagr::OrganizationName ParentAsOrganizationName
{
get => string.IsNullOrEmpty(Parent) ? null : gagr::OrganizationName.Parse(Parent, allowUnparsed: true);
set => Parent = value?.ToString() ?? "";
}
/// <summary>
/// <see cref="gax::IResourceName"/>-typed view over the <see cref="Parent"/> resource name property.
/// </summary>
public gax::IResourceName ParentAsResourceName
{
get
{
if (string.IsNullOrEmpty(Parent))
{
return null;
}
if (gagr::ProjectName.TryParse(Parent, out gagr::ProjectName project))
{
return project;
}
if (gagr::FolderName.TryParse(Parent, out gagr::FolderName folder))
{
return folder;
}
if (gagr::OrganizationName.TryParse(Parent, out gagr::OrganizationName organization))
{
return organization;
}
return gax::UnparsedResourceName.Parse(Parent);
}
set => Parent = value?.ToString() ?? "";
}
}
public partial class SendTestMessageRequest
{
/// <summary>
/// <see cref="ContactName"/>-typed view over the <see cref="Contacts"/> resource name property.
/// </summary>
public gax::ResourceNameList<ContactName> ContactsAsContactNames
{
get => new gax::ResourceNameList<ContactName>(Contacts, s => string.IsNullOrEmpty(s) ? null : ContactName.Parse(s, allowUnparsed: true));
}
/// <summary>
/// <see cref="gagr::ProjectName"/>-typed view over the <see cref="Resource"/> resource name property.
/// </summary>
public gagr::ProjectName ResourceAsProjectName
{
get => string.IsNullOrEmpty(Resource) ? null : gagr::ProjectName.Parse(Resource, allowUnparsed: true);
set => Resource = value?.ToString() ?? "";
}
/// <summary>
/// <see cref="gagr::FolderName"/>-typed view over the <see cref="Resource"/> resource name property.
/// </summary>
public gagr::FolderName ResourceAsFolderName
{
get => string.IsNullOrEmpty(Resource) ? null : gagr::FolderName.Parse(Resource, allowUnparsed: true);
set => Resource = value?.ToString() ?? "";
}
/// <summary>
/// <see cref="gagr::OrganizationName"/>-typed view over the <see cref="Resource"/> resource name property.
/// </summary>
public gagr::OrganizationName ResourceAsOrganizationName
{
get => string.IsNullOrEmpty(Resource) ? null : gagr::OrganizationName.Parse(Resource, allowUnparsed: true);
set => Resource = value?.ToString() ?? "";
}
/// <summary>
/// <see cref="gax::IResourceName"/>-typed view over the <see cref="Resource"/> resource name property.
/// </summary>
public gax::IResourceName ResourceAsResourceName
{
get
{
if (string.IsNullOrEmpty(Resource))
{
return null;
}
if (gagr::ProjectName.TryParse(Resource, out gagr::ProjectName project))
{
return project;
}
if (gagr::FolderName.TryParse(Resource, out gagr::FolderName folder))
{
return folder;
}
if (gagr::OrganizationName.TryParse(Resource, out gagr::OrganizationName organization))
{
return organization;
}
return gax::UnparsedResourceName.Parse(Resource);
}
set => Resource = value?.ToString() ?? "";
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
namespace Microsoft.Azure.Management.ContainerInstance.Fluent
{
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Azure.Management.ContainerInstance.Fluent.Models;
using Microsoft.Azure.Management.ContainerInstance.Fluent.ContainerGroup.Definition;
using Microsoft.Azure.Management.ContainerInstance.Fluent.ContainerGroup.Update;
using Microsoft.Azure.Management.ResourceManager.Fluent;
using Microsoft.Azure.Management.ResourceManager.Fluent.Core;
using Microsoft.Azure.Management.ResourceManager.Fluent.Core.ResourceActions;
using Microsoft.Azure.Management.Storage.Fluent;
using Microsoft.WindowsAzure.Storage;
using Microsoft.WindowsAzure.Storage.File;
using System.Linq;
/// <summary>
/// Implementation for ContainerGroup and its create interfaces.
/// </summary>
///GENTHASH:Y29tLm1pY3Jvc29mdC5henVyZS5tYW5hZ2VtZW50LmNvbnRhaW5lcmluc3RhbmNlLmltcGxlbWVudGF0aW9uLkNvbnRhaW5lckdyb3VwSW1wbA==
internal partial class ContainerGroupImpl :
GroupableResource<
Microsoft.Azure.Management.ContainerInstance.Fluent.IContainerGroup,
Models.ContainerGroupInner,
Microsoft.Azure.Management.ContainerInstance.Fluent.ContainerGroupImpl,
Microsoft.Azure.Management.ContainerInstance.Fluent.IContainerInstanceManager,
IWithGroup,
IWithOsType,
IWithCreate,
IUpdate>,
IContainerGroup,
IDefinition,
IUpdate
{
private IStorageManager storageManager;
private string creatableStorageAccountKey;
private Dictionary<string, string> newFileShares;
private Dictionary<string, Models.Container> containers;
private Dictionary<string, Models.Volume> volumes;
private IList<string> imageRegistryServers;
private int[] externalTcpPorts;
private int[] externalUdpPorts;
///GENMHASH:9C262E34A24F538EA2B9CCF05B5DDC31:B1054C7ABC568976F407B3F83CBEF497
public int[] ExternalTcpPorts()
{
return this.externalTcpPorts;
}
///GENMHASH:EE87A5D4CD5A141684404A7DCC098A5E:69C48C874380FD258ED24236ECFF7545
public bool IsIPAddressPublic()
{
return this.Inner.IpAddress != null && IpAddress.Type.Equals("Public");
}
///GENMHASH:AEE17FD09F624712647F5EBCEC141EA5:99ECDF2C7D842BA7D2742AC2953EDA92
public string State()
{
return this.Inner.InstanceView != null ? this.Inner.InstanceView.State : null;
}
///GENMHASH:59B08BD03F2496BDEFB0CB87748CB717:75DE4FE44AED6C1A4FA25A3E81685E01
public IReadOnlyCollection<string> ImageRegistryServers()
{
return new ReadOnlyCollection<string>(imageRegistryServers);
}
///GENMHASH:48C59AE949E12C01A6C61142D3D2B6C5:213253B61921C0106B8B07DBB056405B
public IReadOnlyCollection<Models.Port> ExternalPorts()
{
return new ReadOnlyCollection<Port>(this.Inner.IpAddress != null && this.Inner.IpAddress.Ports != null ?
this.Inner.IpAddress.Ports : new List<Port>());
}
///GENMHASH:AB09C46CE8F9CA6FA0F625131031E74D:1631EAB8864F459FF3F0235822E771D5
public IReadOnlyDictionary<string, Models.Volume> Volumes()
{
return new ReadOnlyDictionary<string, Models.Volume>(this.volumes);
}
///GENMHASH:568B36CDA0227A7F3A32B87E92E09B4D:C12E94C76D9C55968CE90919BD8CF60E
public IReadOnlyDictionary<string, Models.Container> Containers()
{
return new ReadOnlyDictionary<string, Models.Container>(this.containers);
}
///GENMHASH:EB9638E8F65D17F5F594E27D773A247D:9A9A38EC01C4A2143FD55250B964F335
public string IPAddress()
{
return this.Inner.IpAddress != null ? this.Inner.IpAddress.Ip : null;
}
///GENMHASH:B7B94C51823E8E9590CFB5D3B4497C02:0FB59B85F29ED94C51DB36094BBDE1A8
public int[] ExternalUdpPorts()
{
return this.externalUdpPorts;
}
///GENMHASH:99D5BF64EA8AA0E287C9B6F77AAD6FC4:023E92B4527E4CFAE96195535BADEFE2
public string ProvisioningState()
{
return this.Inner.ProvisioningState;
}
public OSTypeName OSType()
{
return Fluent.OSTypeName.Parse(this.Inner.OsType);
}
///GENMHASH:72D8F838766D2FA789A06DBB8ACE4C8C:6688B3D6EDBA6430DBE60C201714B737
public ContainerGroupRestartPolicy RestartPolicy()
{
return ContainerGroupRestartPolicy.Parse(this.Inner.RestartPolicy);
}
public void Restart()
{
Extensions.Synchronize(() => this.RestartAsync());
}
public async Task RestartAsync(CancellationToken cancellationToken = default(CancellationToken))
{
await this.Manager.Inner.ContainerGroups.RestartAsync(this.ResourceGroupName, this.Name, cancellationToken);
}
public void Stop()
{
Extensions.Synchronize(() => this.StopAsync());
}
public async Task StopAsync(CancellationToken cancellationToken = default(CancellationToken))
{
await this.Manager.Inner.ContainerGroups.StopAsync(this.ResourceGroupName, this.Name, cancellationToken);
}
///GENMHASH:43FFE67ED1E08092A08C7E35A3244CB2:E6719DA498FFBEA871EB1D1A559ABB37
public IReadOnlyCollection<Models.EventModel> Events()
{
return new ReadOnlyCollection<Models.EventModel>(this.Inner.InstanceView != null && this.Inner.InstanceView.Events != null ?
this.Inner.InstanceView.Events : new List<Models.EventModel>());
}
///GENMHASH:C4B69D63304D818F517794AA4D07AAC6:C2773B13EB9D03F0091114E1241E51EB
internal ContainerGroupImpl(string name, ContainerGroupInner innerObject, IContainerInstanceManager manager, IStorageManager storageManager)
: base(name, innerObject, manager)
{
this.storageManager = storageManager;
if (innerObject != null)
{
this.InitializeChildrenFromInner();
}
}
///GENMHASH:6D9F740D6D73C56877B02D9F1C96F6E7:40DC8096FB53D9EA447C99B67637E40C
protected void InitializeChildrenFromInner()
{
this.newFileShares = null;
this.creatableStorageAccountKey = null;
this.containers = new Dictionary<string, Container>();
this.volumes = new Dictionary<string, Volume>();
this.imageRegistryServers = new List<string>();
// Getting the container instances
if (this.Inner.Containers != null && this.Inner.Containers.Count > 0)
{
foreach (var containerInstance in this.Inner.Containers)
{
this.containers.Add(containerInstance.Name, containerInstance);
}
}
// Getting the volumes
if (this.Inner.Volumes != null && this.Inner.Volumes.Count > 0)
{
foreach (var volume in this.Inner.Volumes)
{
this.volumes.Add(volume.Name, volume);
}
}
// Getting the private image registry servers
if (this.Inner.ImageRegistryCredentials != null && this.Inner.ImageRegistryCredentials.Count > 0)
{
foreach (var imageRegistry in this.Inner.ImageRegistryCredentials)
{
this.imageRegistryServers.Add(imageRegistry.Server);
}
}
// Splitting ports between TCP and UDP ports
if (this.Inner.IpAddress != null && this.Inner.IpAddress.Ports != null && this.Inner.IpAddress.Ports.Count > 0)
{
this.externalTcpPorts = this.Inner.IpAddress.Ports.Where(p => ContainerGroupNetworkProtocol.TCP.Equals(p.Protocol)).Select(p => p.PortProperty).ToArray();
this.externalUdpPorts = this.Inner.IpAddress.Ports.Where(p => ContainerGroupNetworkProtocol.UDP.Equals(p.Protocol)).Select(p => p.PortProperty).ToArray();
}
else
{
this.externalTcpPorts = new int[0];
this.externalUdpPorts = new int[0];
}
}
///GENMHASH:5A2D79502EDA81E37A36694062AEDC65:30511FD503549EDC455B6D09D542DB93
public async override Task<Microsoft.Azure.Management.ContainerInstance.Fluent.IContainerGroup> RefreshAsync(CancellationToken cancellationToken = default(CancellationToken))
{
await base.RefreshAsync(cancellationToken);
this.InitializeChildrenFromInner();
return this;
}
public async override Task<IContainerGroup> CreateResourceAsync(CancellationToken cancellationToken)
{
ContainerGroupImpl self = this;
if (IsInCreateMode)
{
if (this.creatableStorageAccountKey != null && this.newFileShares != null && this.newFileShares.Count > 0)
{
// Creates the new Azure file shares
var storageAccount = this.CreatedResource(this.creatableStorageAccountKey) as IStorageAccount;
if (this.Inner.Volumes == null)
{
this.Inner.Volumes = new List<Volume>();
}
var storageAccountKey = (await storageAccount.GetKeysAsync())[0].Value;
var sas = $"DefaultEndpointsProtocol=https;AccountName={storageAccount.Name};AccountKey={storageAccountKey};EndpointSuffix=core.Windows.Net";
var cloudFileClient = CloudStorageAccount.Parse(sas).CreateCloudFileClient();
foreach (var fileShare in this.newFileShares)
{
CloudFileShare cloudFileShare = cloudFileClient.GetShareReference(fileShare.Value);
await cloudFileShare.CreateIfNotExistsAsync();
this.Inner.Volumes.Add(new Volume
{
Name = fileShare.Key,
AzureFile = new AzureFileVolume
{
ShareName = fileShare.Value,
ReadOnlyProperty = false,
StorageAccountName = storageAccount.Name,
StorageAccountKey = storageAccountKey
}
});
}
}
var inner = await this.Manager.Inner.ContainerGroups.CreateOrUpdateAsync(this.ResourceGroupName, this.Name, this.Inner, cancellationToken);
SetInner(inner);
this.InitializeChildrenFromInner();
return this;
}
else
{
var resourceInner = new ResourceInner();
resourceInner.Location = this.RegionName;
resourceInner.Tags = this.Inner.Tags;
var updatedInner = await this.Manager.Inner.ContainerGroups.UpdateAsync(this.ResourceGroupName, this.Name, resourceInner, cancellationToken: cancellationToken);
// TODO: this will go away after service fixes the update bug
updatedInner = await this.GetInnerAsync(cancellationToken);
SetInner(updatedInner);
this.InitializeChildrenFromInner();
return this;
}
}
protected override Task<ContainerGroupInner> GetInnerAsync(CancellationToken cancellationToken)
{
return this.Manager.Inner.ContainerGroups.GetAsync(this.ResourceGroupName, this.Name, cancellationToken);
}
///GENMHASH:002B9FED6878745A10FBEF2FDB77458A:4C268D270623A9FCE0E849411F7DACB8
public ContainerGroupImpl WithLinux()
{
this.Inner.OsType = OperatingSystemTypes.Linux;
return this;
}
///GENMHASH:21843F6A42DA7655078B0AAA573930DC:1BB4AF60868C4D62F669F7DFFC20EE87
public ContainerGroupImpl WithWindows()
{
this.Inner.OsType = OperatingSystemTypes.Windows;
return this;
}
///GENMHASH:81CB563AFF6AD26FDBD5ADDFA8E9807A:29FFF0E66BE4B91F688014D063FC58D9
public ContainerGroupImpl WithPrivateImageRegistry(string server, string username, string password)
{
if (this.Inner.ImageRegistryCredentials == null)
{
this.Inner.ImageRegistryCredentials = new List<ImageRegistryCredential>();
}
this.Inner.ImageRegistryCredentials.Add(new ImageRegistryCredential
{
Server = server,
Username = username,
Password = password
});
return this;
}
///GENMHASH:2CB4C248C39610BBCDFA3C7C13950F51:345DD81D2BBDE0DAE630775246270473
public ContainerGroupImpl WithPublicImageRegistryOnly()
{
this.Inner.ImageRegistryCredentials = null;
return this;
}
///GENMHASH:F0C4F6A7F84296DE6B5B22E9CD83088B:3AA393F2B1A370FDC3C77E87951AD500
public ContainerGroupImpl WithoutVolume()
{
this.Inner.Volumes = null;
return this;
}
///GENMHASH:948C3D8A111E9F3CE85191C15BCEEBFF:E4410CA2195639D89F98489D4A24F153
public ContainerGroupImpl WithEmptyDirectoryVolume(string volumeName)
{
if (this.Inner.Volumes == null)
{
this.Inner.Volumes = new List<Volume>();
}
this.Inner.Volumes.Add(new Volume()
{
Name = volumeName,
EmptyDir = new Object()
});
return this;
}
///GENMHASH:DFC2593B74D1E01275625E2EE80CC9AD:D22668247339DCCC31D9166C946C6AA8
public ContainerGroupImpl WithNewAzureFileShareVolume(string volumeName, string shareName)
{
if (this.newFileShares == null || this.creatableStorageAccountKey == null)
{
Storage.Fluent.StorageAccount.Definition.IWithGroup definitionWithGroup = this.storageManager
.StorageAccounts
.Define(SdkContext.RandomResourceName("fs", 24))
.WithRegion(this.RegionName);
Storage.Fluent.StorageAccount.Definition.IWithCreate creatable;
if (this.newGroup != null)
{
creatable = definitionWithGroup.WithNewResourceGroup(this.newGroup);
}
else
{
creatable = definitionWithGroup.WithExistingResourceGroup(this.ResourceGroupName);
}
this.creatableStorageAccountKey = creatable.Key;
this.AddCreatableDependency(creatable as IResourceCreator<IHasId>);
this.newFileShares = new Dictionary<string, string>();
}
this.newFileShares.Add(volumeName, shareName);
return this;
}
///GENMHASH:C518B06C0BBC9766A09F6FD2432A9CD4:FDC33FB248B626868B54320954852A00
public VolumeImpl DefineVolume(string name)
{
return new VolumeImpl(this, name);
}
///GENMHASH:7094AF382C96EC7FD1063D04C15909E0:176B8A1880E543242F8EA2343BF2B436
public ContainerImpl DefineContainerInstance(string name)
{
return new ContainerImpl(this, name);
}
///GENMHASH:A56B900EF7111F72F47E8873EAB80EC5:D0617CA076D9D9042A7EB6FB9E67995F
public ContainerGroupImpl WithContainerInstance(string imageName)
{
return this.DefineContainerInstance(this.Name)
.WithImage(imageName)
.WithoutPorts()
.WithCpuCoreCount(1)
.WithMemorySizeInGB(1.5)
.Attach();
}
///GENMHASH:95D94B5131D92BA7AF72C28CE506404B:B731C6B2B19E78D26B13FB71FBD36ECF
public ContainerGroupImpl WithContainerInstance(string imageName, int port)
{
return this.DefineContainerInstance(this.Name)
.WithImage(imageName)
.WithExternalTcpPort(port)
.WithCpuCoreCount(1)
.WithMemorySizeInGB(1.5)
.Attach();
}
///GENMHASH:1C73260E17F72F996B485F399B1A7E02:93461D0A597F2906607068C9C6F891F6
public ContainerGroupImpl WithRestartPolicy(ContainerGroupRestartPolicy restartPolicy)
{
this.Inner.RestartPolicy = restartPolicy.Value;
return this;
}
///GENMHASH:5539452FF37A2039D171B77EAB519674:F662BD68539B03381406F317464C0B00
public string GetLogContent(string containerName)
{
return Extensions.Synchronize(() => this.GetLogContentAsync(containerName));
}
///GENMHASH:E56134B3DD31D67F07D4B5EDC1D24FD7:137080B7ED8C37E287C17CC77224DECA
public string GetLogContent(string containerName, int tailLineCount)
{
return Extensions.Synchronize(() => this.GetLogContentAsync(containerName, tailLineCount));
}
///GENMHASH:68FA359B278647E097B20441389A58FC:3119C16FFA0F521767097C339920EE47
public async Task<string> GetLogContentAsync(string containerName, CancellationToken cancellationToken = default(CancellationToken))
{
var log = await this.Manager.Inner.Container.ListLogsAsync(this.ResourceGroupName, this.Name, containerName, cancellationToken: cancellationToken);
return (log != null) ? log.Content : "";
}
///GENMHASH:FF17FE4F8B9A7B52DB8052C65778E9B1:62A00FD4D8AED790BA6A5B89296698FF
public async Task<string> GetLogContentAsync(string containerName, int tailLineCount, CancellationToken cancellationToken = default(CancellationToken))
{
var log = await this.Manager.Inner.Container.ListLogsAsync(this.ResourceGroupName, this.Name, containerName, tailLineCount, cancellationToken);
return (log != null) ? log.Content : "";
}
///GENMHASH:8642FC9B9C8DC7375DEE3CC5736F8853:D8E9D98F2E55B91C74B8A9CCC0D57DFB
public ContainerGroupImpl WithDnsPrefix(string dnsPrefix)
{
if (this.Inner.IpAddress == null)
{
this.Inner.IpAddress = new IpAddress();
}
this.Inner.IpAddress.DnsNameLabel = dnsPrefix;
return this;
}
///GENMHASH:59348A25FD515049ECD26A6290F76B85:E61328CEA9774DAE97931A8E3F5BA1FA
public string DnsPrefix()
{
return (this.Inner.IpAddress != null) ? this.Inner.IpAddress.DnsNameLabel : null;
}
///GENMHASH:577F8437932AEC6E08E1A137969BDB4A:6EE2F2474752814D061D517DDCF91010
public string Fqdn()
{
return (this.Inner.IpAddress != null) ? this.Inner.IpAddress.Fqdn : null;
}
///GENMHASH:F4416221E7E4EB6A087BCA399AE5E9F6:A0E77E1086B086D8F0F97954516DA583
public IContainerExecResponse ExecuteCommand(string containerName, string command, int row, int column)
{
return Extensions.Synchronize(() => this.ExecuteCommandAsync(containerName, command, row, column));
}
///GENMHASH:5D1452C0A2F0D2A020CBCC369E41D1F2:67CC4D00B6C73394256E4765E8876BE5
public async Task<Microsoft.Azure.Management.ContainerInstance.Fluent.IContainerExecResponse> ExecuteCommandAsync(string containerName, string command, int row, int column, CancellationToken cancellationToken = default(CancellationToken))
{
var containerExecRequestTerminalSize = new ContainerExecRequestTerminalSize() { Rows = row, Cols = column };
var containerExecRequestInner = new Models.ContainerExecRequestInner() { Command = command, TerminalSize = containerExecRequestTerminalSize };
var containerExecResponseInner = await this.Manager.Inner.Container
.ExecuteCommandAsync(this.ResourceGroupName, this.Name, containerName, containerExecRequestInner, cancellationToken);
return new ContainerExecResponseImpl(containerExecResponseInner);
}
}
}
| |
// <copyright company="Simply Code Ltd.">
// Copyright (c) Simply Code Ltd. All rights reserved.
// Licensed under the MIT License.
// See LICENSE file in the project root for full license information.
// </copyright>
namespace PackIt.DTO.DtoPack
{
using PackIt.Helpers.Enums;
/// <summary> A dto limit. </summary>
public class DtoLimit
{
/// <summary> Gets or sets the identifier of the Pack that owns this item. </summary>
///
/// <value> The identifier of the Pack. </value>
public string PackId { get; set; }
/// <summary> Gets or sets the stage level. </summary>
///
/// <value> The stage level. </value>
public StageLevel StageLevel { get; set; }
/// <summary> Gets or sets the zero-based index of this Limit. </summary>
///
/// <value> The Limit index. </value>
public long LimitIndex { get; set; }
/// <summary> Gets or sets a value indicating whether the design. </summary>
///
/// <value> True if design, false if not. </value>
public bool Design { get; set; }
/// <summary> Gets or sets the type of the material. </summary>
///
/// <value> The type of the material. </value>
public MaterialType MaterialType { get; set; }
/// <summary> Gets or sets the material code. </summary>
///
/// <value> The material code. </value>
public string MaterialCode { get; set; }
/// <summary> Gets or sets the material code minimum. </summary>
///
/// <value> The material code minimum. </value>
public string MaterialCodeMin { get; set; }
/// <summary> Gets or sets the type of the design. </summary>
///
/// <value> The type of the design. </value>
public DesignType DesignType { get; set; }
/// <summary> Gets or sets the design code. </summary>
///
/// <value> The design code. </value>
public string DesignCode { get; set; }
/// <summary> Gets or sets the design code minimum. </summary>
///
/// <value> The design code minimum. </value>
public string DesignCodeMin { get; set; }
/// <summary> Gets or sets the type of the quality. </summary>
///
/// <value> The type of the quality. </value>
public QualityType QualityType { get; set; }
/// <summary> Gets or sets the quality code. </summary>
///
/// <value> The quality code. </value>
public string QualityCode { get; set; }
/// <summary> Gets or sets the quality code minimum. </summary>
///
/// <value> The quality code minimum. </value>
public string QualityCodeMin { get; set; }
/// <summary> Gets or sets the usage. </summary>
///
/// <value> The usage. </value>
public UsageType Usage { get; set; }
/// <summary> Gets or sets a value indicating whether the inverted. </summary>
///
/// <value> True if inverted, false if not. </value>
public bool Inverted { get; set; }
/// <summary> Gets or sets the number of layers. </summary>
///
/// <value> The number of layers. </value>
public long LayerCount { get; set; }
/// <summary> Gets or sets the layer start. </summary>
///
/// <value> The layer start. </value>
public long LayerStart { get; set; }
/// <summary> Gets or sets the layer step. </summary>
///
/// <value> The layer step. </value>
public long LayerStep { get; set; }
/// <summary> Gets or sets the quality caliper. </summary>
///
/// <value> The quality caliper. </value>
public double QualityCaliper { get; set; }
/// <summary> Gets or sets the quality density. </summary>
///
/// <value> The quality density. </value>
public double QualityDensity { get; set; }
/// <summary> Gets or sets the length minimum. </summary>
///
/// <value> The length minimum. </value>
public double LengthMin { get; set; }
/// <summary> Gets or sets the length maximum. </summary>
///
/// <value> The length maximum. </value>
public double LengthMax { get; set; }
/// <summary> Gets or sets the breadth minimum. </summary>
///
/// <value> The breadth minimum. </value>
public double BreadthMin { get; set; }
/// <summary> Gets or sets the breadth maximum. </summary>
///
/// <value> The breadth maximum. </value>
public double BreadthMax { get; set; }
/// <summary> Gets or sets the height minimum. </summary>
///
/// <value> The height minimum. </value>
public double HeightMin { get; set; }
/// <summary> Gets or sets the height maximum. </summary>
///
/// <value> The height maximum. </value>
public double HeightMax { get; set; }
/// <summary> Gets or sets the caliper minimum. </summary>
///
/// <value> The caliper minimum. </value>
public double CaliperMin { get; set; }
/// <summary> Gets or sets the caliper maximum. </summary>
///
/// <value> The caliper maximum. </value>
public double CaliperMax { get; set; }
/// <summary> Gets or sets the packing gap x coordinate. </summary>
///
/// <value> The packing gap x coordinate. </value>
public double PackingGapX { get; set; }
/// <summary> Gets or sets the packing gap y coordinate. </summary>
///
/// <value> The packing gap y coordinate. </value>
public double PackingGapY { get; set; }
/// <summary> Gets or sets the packing gap z coordinate. </summary>
///
/// <value> The packing gap z coordinate. </value>
public double PackingGapZ { get; set; }
/// <summary> Gets or sets the safety factor minimum. </summary>
///
/// <value> The safety factor minimum. </value>
public double SafetyFactorMin { get; set; }
/// <summary> Gets or sets the safety factor maximum. </summary>
///
/// <value> The safety factor maximum. </value>
public double SafetyFactorMax { get; set; }
/// <summary> Gets or sets the front placement. </summary>
///
/// <value> The front placement. </value>
public long FrontPlacement { get; set; }
/// <summary> Gets or sets the back placement. </summary>
///
/// <value> The back placement. </value>
public long BackPlacement { get; set; }
/// <summary> Gets or sets the left placement. </summary>
///
/// <value> The left placement. </value>
public long LeftPlacement { get; set; }
/// <summary> Gets or sets the right placement. </summary>
///
/// <value> The right placement. </value>
public long RightPlacement { get; set; }
/// <summary> Gets or sets the top placement. </summary>
///
/// <value> The top placement. </value>
public long TopPlacement { get; set; }
/// <summary> Gets or sets the bottom placement. </summary>
///
/// <value> The bottom placement. </value>
public long BottomPlacement { get; set; }
/// <summary> Gets or sets the length thicknesses. </summary>
///
/// <value> The length thicknesses. </value>
public long LengthThicknesses { get; set; }
/// <summary> Gets or sets the length sink change. </summary>
///
/// <value> The length sink change. </value>
public long LengthSinkChange { get; set; }
/// <summary> Gets or sets the breadth thicknesses. </summary>
///
/// <value> The breadth thicknesses. </value>
public long BreadthThicknesses { get; set; }
/// <summary> Gets or sets the breadth sink change. </summary>
///
/// <value> The breadth sink change. </value>
public long BreadthSinkChange { get; set; }
/// <summary> Gets or sets the height thicknesses. </summary>
///
/// <value> The height thicknesses. </value>
public long HeightThicknesses { get; set; }
/// <summary> Gets or sets the height sink change. </summary>
///
/// <value> The height sink change. </value>
public long HeightSinkChange { get; set; }
/// <summary> Gets or sets the type of the costing. </summary>
///
/// <value> The type of the costing. </value>
public CostType CostingType { get; set; }
}
}
| |
//---------------------------------------------------------------------
// <copyright file="ODataParameterWriterCore.cs" company="Microsoft">
// Copyright (C) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information.
// </copyright>
//---------------------------------------------------------------------
namespace Microsoft.OData.Core
{
#region Namespaces
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.IO;
using System.Text;
#if ODATALIB_ASYNC
using System.Threading.Tasks;
#endif
using Microsoft.OData.Edm;
using Microsoft.OData.Core.Metadata;
#endregion Namespaces
/// <summary>
/// Base class for OData parameter writers that verifies a proper sequence of write calls on the writer.
/// </summary>
internal abstract class ODataParameterWriterCore : ODataParameterWriter, IODataReaderWriterListener, IODataOutputInStreamErrorListener
{
/// <summary>The output context to write to.</summary>
private readonly ODataOutputContext outputContext;
/// <summary>The operation whose parameters will be written.</summary>
private readonly IEdmOperation operation;
/// <summary>Stack of writer scopes to keep track of the current context of the writer.</summary>
private Stack<ParameterWriterState> scopes = new Stack<ParameterWriterState>();
/// <summary>Parameter names that have already been written, used to detect duplicate writes on a parameter.</summary>
private HashSet<string> parameterNamesWritten = new HashSet<string>(StringComparer.Ordinal);
/// <summary>Checker to detect duplicate property names on complex parameter values.</summary>
private DuplicatePropertyNamesChecker duplicatePropertyNamesChecker;
/// <summary>
/// Constructor.
/// </summary>
/// <param name="outputContext">The output context to write to.</param>
/// <param name="operation">The operation import whose parameters will be written.</param>
protected ODataParameterWriterCore(ODataOutputContext outputContext, IEdmOperation operation)
{
Debug.Assert(outputContext != null, "outputContext != null");
this.outputContext = outputContext;
this.operation = operation;
this.scopes.Push(ParameterWriterState.Start);
}
/// <summary>
/// An enumeration representing the current state of the writer.
/// </summary>
private enum ParameterWriterState
{
/// <summary>The writer is at the start; nothing has been written yet.</summary>
Start,
/// <summary>
/// The writer is in a state where the next parameter can be written.
/// The writer enters this state after WriteStart() or after the previous parameter is written.
/// </summary>
CanWriteParameter,
/// <summary>One of the create writer method has been called and the created sub writer is not in Completed state.</summary>
ActiveSubWriter,
/// <summary>The writer has completed; nothing can be written anymore.</summary>
Completed,
/// <summary>An error had occured while writing the payload; nothing can be written anymore.</summary>
Error
}
/// <summary>Checker to detect duplicate property names on complex parameter values.</summary>
protected DuplicatePropertyNamesChecker DuplicatePropertyNamesChecker
{
get
{
return this.duplicatePropertyNamesChecker ?? (this.duplicatePropertyNamesChecker = new DuplicatePropertyNamesChecker(false /*allowDuplicateProperties*/, false /*isResponse*/, !this.outputContext.MessageWriterSettings.EnableFullValidation));
}
}
/// <summary>
/// The current state of the writer.
/// </summary>
private ParameterWriterState State
{
get { return this.scopes.Peek(); }
}
/// <summary>
/// Flushes the write buffer to the underlying stream.
/// </summary>
public sealed override void Flush()
{
this.VerifyCanFlush(true /*synchronousCall*/);
// make sure we switch to writer state Error if an exception is thrown during flushing.
this.InterceptException(this.FlushSynchronously);
}
#if ODATALIB_ASYNC
/// <summary>
/// Asynchronously flushes the write buffer to the underlying stream.
/// </summary>
/// <returns>A task instance that represents the asynchronous operation.</returns>
public sealed override Task FlushAsync()
{
this.VerifyCanFlush(false /*synchronousCall*/);
// make sure we switch to writer state Error if an exception is thrown during flushing.
return this.FlushAsynchronously().FollowOnFaultWith(t => this.EnterErrorScope());
}
#endif
/// <summary>
/// Start writing a parameter payload.
/// </summary>
public sealed override void WriteStart()
{
this.VerifyCanWriteStart(true /*synchronousCall*/);
this.InterceptException(() => this.WriteStartImplementation());
}
#if ODATALIB_ASYNC
/// <summary>
/// Asynchronously start writing a parameter payload.
/// </summary>
/// <returns>A task instance that represents the asynchronous write operation.</returns>
public sealed override Task WriteStartAsync()
{
this.VerifyCanWriteStart(false /*synchronousCall*/);
return TaskUtils.GetTaskForSynchronousOperation(() => this.InterceptException(() => this.WriteStartImplementation()));
}
#endif
/// <summary>
/// Start writing a value parameter.
/// </summary>
/// <param name="parameterName">The name of the parameter to write.</param>
/// <param name="parameterValue">The value of the parameter to write (null/ODataComplexValue/ODataEnumValue/primitiveClrValue).</param>
public sealed override void WriteValue(string parameterName, object parameterValue)
{
ExceptionUtils.CheckArgumentStringNotNullOrEmpty(parameterName, "parameterName");
IEdmTypeReference expectedTypeReference = this.VerifyCanWriteValueParameter(true /*synchronousCall*/, parameterName, parameterValue);
this.InterceptException(() => this.WriteValueImplementation(parameterName, parameterValue, expectedTypeReference));
}
#if ODATALIB_ASYNC
/// <summary>
/// Asynchronously start writing a value parameter.
/// </summary>
/// <param name="parameterName">The name of the parameter to write.</param>
/// <param name="parameterValue">The value of the parameter to write.</param>
/// <returns>A task instance that represents the asynchronous write operation.</returns>
public sealed override Task WriteValueAsync(string parameterName, object parameterValue)
{
ExceptionUtils.CheckArgumentStringNotNullOrEmpty(parameterName, "parameterName");
IEdmTypeReference expectedTypeReference = this.VerifyCanWriteValueParameter(false /*synchronousCall*/, parameterName, parameterValue);
return TaskUtils.GetTaskForSynchronousOperation(() => this.InterceptException(() => this.WriteValueImplementation(parameterName, parameterValue, expectedTypeReference)));
}
#endif
/// <summary>
/// Creates an <see cref="ODataCollectionWriter"/> to write the value of a collection parameter.
/// </summary>
/// <param name="parameterName">The name of the collection parameter to write.</param>
/// <returns>The newly created <see cref="ODataCollectionWriter"/>.</returns>
public sealed override ODataCollectionWriter CreateCollectionWriter(string parameterName)
{
ExceptionUtils.CheckArgumentStringNotNullOrEmpty(parameterName, "parameterName");
IEdmTypeReference itemTypeReference = this.VerifyCanCreateCollectionWriter(true /*synchronousCall*/, parameterName);
return this.InterceptException(() => this.CreateCollectionWriterImplementation(parameterName, itemTypeReference));
}
#if ODATALIB_ASYNC
/// <summary>
/// Asynchronously creates an <see cref="ODataCollectionWriter"/> to write the value of a collection parameter.
/// </summary>
/// <param name="parameterName">The name of the collection parameter to write.</param>
/// <returns>A running task for the created writer.</returns>
public sealed override Task<ODataCollectionWriter> CreateCollectionWriterAsync(string parameterName)
{
ExceptionUtils.CheckArgumentStringNotNullOrEmpty(parameterName, "parameterName");
IEdmTypeReference itemTypeReference = this.VerifyCanCreateCollectionWriter(false /*synchronousCall*/, parameterName);
return TaskUtils.GetTaskForSynchronousOperation(
() => this.InterceptException(() => this.CreateCollectionWriterImplementation(parameterName, itemTypeReference)));
}
#endif
/// <summary> Creates an <see cref="T:Microsoft.OData.Core.ODataWriter" /> to write an entry. </summary>
/// <param name="parameterName">The name of the parameter to write.</param>
/// <returns>The created writer.</returns>
public sealed override ODataWriter CreateEntryWriter(string parameterName)
{
ExceptionUtils.CheckArgumentStringNotNullOrEmpty(parameterName, "parameterName");
IEdmTypeReference itemTypeReference = this.VerifyCanCreateEntryWriter(true /*synchronousCall*/, parameterName);
return this.InterceptException(() => this.CreateEntryWriterImplementation(parameterName, itemTypeReference));
}
#if ODATALIB_ASYNC
/// <summary>Asynchronously creates an <see cref="T:Microsoft.OData.Core.ODataWriter" /> to write an entry.</summary>
/// <param name="parameterName">The name of the parameter to write.</param>
/// <returns>The asynchronously created <see cref="T:Microsoft.OData.Core.ODataWriter" />.</returns>
public sealed override Task<ODataWriter> CreateEntryWriterAsync(string parameterName)
{
ExceptionUtils.CheckArgumentStringNotNullOrEmpty(parameterName, "parameterName");
IEdmTypeReference itemTypeReference = this.VerifyCanCreateEntryWriter(false /*synchronousCall*/, parameterName);
return TaskUtils.GetTaskForSynchronousOperation(
() => this.InterceptException(() => this.CreateEntryWriterImplementation(parameterName, itemTypeReference)));
}
#endif
/// <summary> Creates an <see cref="T:Microsoft.OData.Core.ODataWriter" /> to write a feed. </summary>
/// <param name="parameterName">The name of the parameter to write.</param>
/// <returns>The created writer.</returns>
public sealed override ODataWriter CreateFeedWriter(string parameterName)
{
ExceptionUtils.CheckArgumentStringNotNullOrEmpty(parameterName, "parameterName");
IEdmTypeReference itemTypeReference = this.VerifyCanCreateFeedWriter(true /*synchronousCall*/, parameterName);
return this.InterceptException(() => this.CreateFeedWriterImplementation(parameterName, itemTypeReference));
}
#if ODATALIB_ASYNC
/// <summary>Asynchronously creates an <see cref="T:Microsoft.OData.Core.ODataWriter" /> to write a feed.</summary>
/// <param name="parameterName">The name of the parameter to write.</param>
/// <returns>The asynchronously created <see cref="T:Microsoft.OData.Core.ODataWriter" />.</returns>
public sealed override Task<ODataWriter> CreateFeedWriterAsync(string parameterName)
{
ExceptionUtils.CheckArgumentStringNotNullOrEmpty(parameterName, "parameterName");
IEdmTypeReference itemTypeReference = this.VerifyCanCreateFeedWriter(false /*synchronousCall*/, parameterName);
return TaskUtils.GetTaskForSynchronousOperation(
() => this.InterceptException(() => this.CreateFeedWriterImplementation(parameterName, itemTypeReference)));
}
#endif
/// <summary>
/// Finish writing a parameter payload.
/// </summary>
public sealed override void WriteEnd()
{
this.VerifyCanWriteEnd(true /*synchronousCall*/);
this.InterceptException(() => this.WriteEndImplementation());
if (this.State == ParameterWriterState.Completed)
{
// Note that we intentionally go through the public API so that if the Flush fails the writer moves to the Error state.
this.Flush();
}
}
#if ODATALIB_ASYNC
/// <summary>
/// Asynchronously finish writing a parameter payload.
/// </summary>
/// <returns>A task instance that represents the asynchronous write operation.</returns>
public sealed override Task WriteEndAsync()
{
this.VerifyCanWriteEnd(false /*synchronousCall*/);
return TaskUtils.GetTaskForSynchronousOperation(() => this.InterceptException(() => this.WriteEndImplementation()))
.FollowOnSuccessWithTask(
task =>
{
if (this.State == ParameterWriterState.Completed)
{
// Note that we intentionally go through the public API so that if the Flush fails the writer moves to the Error state.
return this.FlushAsync();
}
else
{
return TaskUtils.CompletedTask;
}
});
}
#endif
/// <summary>
/// This method notifies the implementer of this interface that the created reader is in Exception state.
/// </summary>
void IODataReaderWriterListener.OnException()
{
Debug.Assert(this.State == ParameterWriterState.ActiveSubWriter, "this.State == ParameterWriterState.ActiveSubWriter");
this.ReplaceScope(ParameterWriterState.Error);
}
/// <summary>
/// This method notifies the implementer of this interface that the created reader is in Completed state.
/// </summary>
void IODataReaderWriterListener.OnCompleted()
{
Debug.Assert(this.State == ParameterWriterState.ActiveSubWriter, "this.State == ParameterWriterState.ActiveSubWriter");
this.ReplaceScope(ParameterWriterState.CanWriteParameter);
}
/// <summary>
/// This method notifies the listener, that an in-stream error is to be written.
/// </summary>
/// <remarks>
/// This listener can choose to fail, if the currently written payload doesn't support in-stream error at this position.
/// If the listener returns, the writer should not allow any more writing, since the in-stream error is the last thing in the payload.
/// </remarks>
void IODataOutputInStreamErrorListener.OnInStreamError()
{
// The parameter payload is writen by the client and read by the server, we do not support
// writing an in-stream error payload in this scenario.
throw new ODataException(Strings.ODataParameterWriter_InStreamErrorNotSupported);
}
/// <summary>
/// Check if the object has been disposed; called from all public API methods. Throws an ObjectDisposedException if the object
/// has already been disposed.
/// </summary>
protected abstract void VerifyNotDisposed();
/// <summary>
/// Flush the output.
/// </summary>
protected abstract void FlushSynchronously();
#if ODATALIB_ASYNC
/// <summary>
/// Flush the output.
/// </summary>
/// <returns>Task representing the pending flush operation.</returns>
protected abstract Task FlushAsynchronously();
#endif
/// <summary>
/// Start writing an OData payload.
/// </summary>
protected abstract void StartPayload();
/// <summary>
/// Writes a value parameter (either primitive or complex).
/// </summary>
/// <param name="parameterName">The name of the parameter to write.</param>
/// <param name="parameterValue">The value of the parameter to write.</param>
/// <param name="expectedTypeReference">The expected type reference of the parameter value.</param>
protected abstract void WriteValueParameter(string parameterName, object parameterValue, IEdmTypeReference expectedTypeReference);
/// <summary>
/// Creates a format specific <see cref="ODataCollectionWriter"/> to write the value of a collection parameter.
/// </summary>
/// <param name="parameterName">The name of the collection parameter to write.</param>
/// <param name="expectedItemType">The type reference of the expected item type or null if no expected item type exists.</param>
/// <returns>The newly created <see cref="ODataCollectionWriter"/>.</returns>
protected abstract ODataCollectionWriter CreateFormatCollectionWriter(string parameterName, IEdmTypeReference expectedItemType);
/// <summary>Creates a format specific <see cref="ODataWriter"/> to write an entry.</summary>
/// <param name="parameterName">The name of the parameter to write.</param>
/// <param name="expectedItemType">The type reference of the expected item type or null if no expected item type exists.</param>
/// <returns>The newly created <see cref="ODataWriter"/>.</returns>
protected abstract ODataWriter CreateFormatEntryWriter(string parameterName, IEdmTypeReference expectedItemType);
/// <summary>Creates a format specific <see cref="ODataWriter"/> to write a feed.</summary>
/// <param name="parameterName">The name of the parameter to write.</param>
/// <param name="expectedItemType">The type reference of the expected item type or null if no expected item type exists.</param>
/// <returns>The newly created <see cref="ODataWriter"/>.</returns>
protected abstract ODataWriter CreateFormatFeedWriter(string parameterName, IEdmTypeReference expectedItemType);
/// <summary>
/// Finish writing an OData payload.
/// </summary>
protected abstract void EndPayload();
/// <summary>
/// Verifies that calling WriteStart is valid.
/// </summary>
/// <param name="synchronousCall">true if the call is to be synchronous; false otherwise.</param>
private void VerifyCanWriteStart(bool synchronousCall)
{
this.VerifyNotDisposed();
this.VerifyCallAllowed(synchronousCall);
if (this.State != ParameterWriterState.Start)
{
throw new ODataException(Strings.ODataParameterWriterCore_CannotWriteStart);
}
}
/// <summary>
/// Start writing a parameter payload - implementation of the actual functionality.
/// </summary>
private void WriteStartImplementation()
{
Debug.Assert(this.State == ParameterWriterState.Start, "this.State == ParameterWriterState.Start");
this.InterceptException(this.StartPayload);
this.EnterScope(ParameterWriterState.CanWriteParameter);
}
/// <summary>
/// Verifies that the parameter with name <paramref name="parameterName"/> can be written and returns the
/// type reference of the parameter.
/// </summary>
/// <param name="synchronousCall">true if the call is to be synchronous; false otherwise.</param>
/// <param name="parameterName">The name of the parameter to be written.</param>
/// <returns>The type reference of the parameter; null if no operation import was specified to the writer.</returns>
private IEdmTypeReference VerifyCanWriteParameterAndGetTypeReference(bool synchronousCall, string parameterName)
{
Debug.Assert(!string.IsNullOrEmpty(parameterName), "!string.IsNullOrEmpty(parameterName)");
this.VerifyNotDisposed();
this.VerifyCallAllowed(synchronousCall);
this.VerifyNotInErrorOrCompletedState();
if (this.State != ParameterWriterState.CanWriteParameter)
{
throw new ODataException(Strings.ODataParameterWriterCore_CannotWriteParameter);
}
if (this.parameterNamesWritten.Contains(parameterName))
{
throw new ODataException(Strings.ODataParameterWriterCore_DuplicatedParameterNameNotAllowed(parameterName));
}
this.parameterNamesWritten.Add(parameterName);
return this.GetParameterTypeReference(parameterName);
}
/// <summary>
/// Verify that calling WriteValue is valid.
/// </summary>
/// <param name="synchronousCall">true if the call is to be synchronous; false otherwise.</param>
/// <param name="parameterName">The name of the parameter to be written.</param>
/// <param name="parameterValue">The value of the parameter to write.</param>
/// <returns>The type reference of the parameter; null if no operation import was specified to the writer.</returns>
private IEdmTypeReference VerifyCanWriteValueParameter(bool synchronousCall, string parameterName, object parameterValue)
{
Debug.Assert(!string.IsNullOrEmpty(parameterName), "!string.IsNullOrEmpty(parameterName)");
IEdmTypeReference parameterTypeReference = this.VerifyCanWriteParameterAndGetTypeReference(synchronousCall, parameterName);
if (parameterTypeReference != null && !parameterTypeReference.IsODataPrimitiveTypeKind() && !parameterTypeReference.IsODataComplexTypeKind() && !parameterTypeReference.IsODataEnumTypeKind() && !parameterTypeReference.IsODataTypeDefinitionTypeKind())
{
throw new ODataException(Strings.ODataParameterWriterCore_CannotWriteValueOnNonValueTypeKind(parameterName, parameterTypeReference.TypeKind()));
}
if (parameterValue != null && (!EdmLibraryExtensions.IsPrimitiveType(parameterValue.GetType()) || parameterValue is Stream) && !(parameterValue is ODataComplexValue) && !(parameterValue is ODataEnumValue))
{
throw new ODataException(Strings.ODataParameterWriterCore_CannotWriteValueOnNonSupportedValueType(parameterName, parameterValue.GetType()));
}
return parameterTypeReference;
}
/// <summary>
/// Verify that calling CreateCollectionWriter is valid.
/// </summary>
/// <param name="synchronousCall">true if the call is to be synchronous; false otherwise.</param>
/// <param name="parameterName">The name of the parameter to be written.</param>
/// <returns>The expected item type of the items in the collection or null if no item type is available.</returns>
private IEdmTypeReference VerifyCanCreateCollectionWriter(bool synchronousCall, string parameterName)
{
Debug.Assert(!string.IsNullOrEmpty(parameterName), "!string.IsNullOrEmpty(parameterName)");
IEdmTypeReference parameterTypeReference = this.VerifyCanWriteParameterAndGetTypeReference(synchronousCall, parameterName);
if (parameterTypeReference != null && !parameterTypeReference.IsNonEntityCollectionType())
{
throw new ODataException(Strings.ODataParameterWriterCore_CannotCreateCollectionWriterOnNonCollectionTypeKind(parameterName, parameterTypeReference.TypeKind()));
}
return parameterTypeReference == null ? null : parameterTypeReference.GetCollectionItemType();
}
/// <summary>
/// Verify that calling CreateEntryWriter is valid.
/// </summary>
/// <param name="synchronousCall">true if the call is to be synchronous; false otherwise.</param>
/// <param name="parameterName">The name of the parameter to be written.</param>
/// <returns>The expected item type of the entry or null.</returns>
private IEdmTypeReference VerifyCanCreateEntryWriter(bool synchronousCall, string parameterName)
{
Debug.Assert(!string.IsNullOrEmpty(parameterName), "!string.IsNullOrEmpty(parameterName)");
IEdmTypeReference parameterTypeReference = this.VerifyCanWriteParameterAndGetTypeReference(synchronousCall, parameterName);
if (parameterTypeReference != null && !parameterTypeReference.IsODataEntityTypeKind())
{
throw new ODataException(String.Format(CultureInfo.InvariantCulture, "The parameter '{0}' is of Edm type kind '{1}'. You cannot call CreateEntryWriter on a parameter that is not of Edm type kind 'Entity'.", parameterName, parameterTypeReference.TypeKind()));
}
return parameterTypeReference;
}
/// <summary>
/// Verify that calling CreateFeedWriter is valid.
/// </summary>
/// <param name="synchronousCall">true if the call is to be synchronous; false otherwise.</param>
/// <param name="parameterName">The name of the parameter to be written.</param>
/// <returns>The expected item type of the item in feed or null.</returns>
private IEdmTypeReference VerifyCanCreateFeedWriter(bool synchronousCall, string parameterName)
{
Debug.Assert(!string.IsNullOrEmpty(parameterName), "!string.IsNullOrEmpty(parameterName)");
IEdmTypeReference parameterTypeReference = this.VerifyCanWriteParameterAndGetTypeReference(synchronousCall, parameterName);
if (parameterTypeReference != null && !parameterTypeReference.IsEntityCollectionType())
{
throw new ODataException(String.Format(CultureInfo.InvariantCulture, "The parameter '{0}' is of Edm type kind '{1}'. You cannot call CreateFeedWriter on a parameter that is not of Edm type kind 'Collection(Entity)'.", parameterName, parameterTypeReference.TypeKind()));
}
return parameterTypeReference;
}
/// <summary>
/// Gets the type reference of the parameter in question. Returns null if no operation import was specified to the writer.
/// </summary>
/// <param name="parameterName">The name of the parameter in question.</param>
/// <returns>The type reference of the parameter; null if no operation import was specified to the writer.</returns>
private IEdmTypeReference GetParameterTypeReference(string parameterName)
{
if (this.operation != null)
{
IEdmOperationParameter parameter = this.operation.FindParameter(parameterName);
if (parameter == null)
{
throw new ODataException(Strings.ODataParameterWriterCore_ParameterNameNotFoundInOperation(parameterName, this.operation.Name));
}
return this.outputContext.EdmTypeResolver.GetParameterType(parameter);
}
return null;
}
/// <summary>
/// Write a value parameter - implementation of the actual functionality.
/// </summary>
/// <param name="parameterName">The name of the parameter to write.</param>
/// <param name="parameterValue">The value of the parameter to write (null/ODataComplexValue/ODataEnumValue/primitiveClrValue).</param>
/// <param name="expectedTypeReference">The expected type reference of the parameter value.</param>
private void WriteValueImplementation(string parameterName, object parameterValue, IEdmTypeReference expectedTypeReference)
{
Debug.Assert(this.State == ParameterWriterState.CanWriteParameter, "this.State == ParameterWriterState.CanWriteParameter");
this.InterceptException(() => this.WriteValueParameter(parameterName, parameterValue, expectedTypeReference));
}
/// <summary>
/// Creates an <see cref="ODataCollectionWriter"/> to write the value of a collection parameter.
/// </summary>
/// <param name="parameterName">The name of the collection parameter to write.</param>
/// <param name="expectedItemType">The type reference of the expected item type or null if no expected item type exists.</param>
/// <returns>The newly created <see cref="ODataCollectionWriter"/>.</returns>
private ODataCollectionWriter CreateCollectionWriterImplementation(string parameterName, IEdmTypeReference expectedItemType)
{
Debug.Assert(this.State == ParameterWriterState.CanWriteParameter, "this.State == ParameterWriterState.CanWriteParameter");
ODataCollectionWriter collectionWriter = this.CreateFormatCollectionWriter(parameterName, expectedItemType);
this.ReplaceScope(ParameterWriterState.ActiveSubWriter);
return collectionWriter;
}
/// <summary>
/// Creates an <see cref="ODataWriter"/> to write an entry parameter.
/// </summary>
/// <param name="parameterName">The name of the parameter to write.</param>
/// <param name="expectedItemType">The type reference of the expected item type or null if no expected item type exists.</param>
/// <returns>The newly created <see cref="ODataWriter"/>.</returns>
private ODataWriter CreateEntryWriterImplementation(string parameterName, IEdmTypeReference expectedItemType)
{
Debug.Assert(this.State == ParameterWriterState.CanWriteParameter, "this.State == ParameterWriterState.CanWriteParameter");
ODataWriter entryWriter = this.CreateFormatEntryWriter(parameterName, expectedItemType);
this.ReplaceScope(ParameterWriterState.ActiveSubWriter);
return entryWriter;
}
/// <summary>
/// Creates an <see cref="ODataWriter"/> to write a feed parameter.
/// </summary>
/// <param name="parameterName">The name of the collection parameter to write.</param>
/// <param name="expectedItemType">The type reference of the expected item type or null if no expected item type exists.</param>
/// <returns>The newly created <see cref="ODataCollectionWriter"/>.</returns>
private ODataWriter CreateFeedWriterImplementation(string parameterName, IEdmTypeReference expectedItemType)
{
Debug.Assert(this.State == ParameterWriterState.CanWriteParameter, "this.State == ParameterWriterState.CanWriteParameter");
ODataWriter feedWriter = this.CreateFormatFeedWriter(parameterName, expectedItemType);
this.ReplaceScope(ParameterWriterState.ActiveSubWriter);
return feedWriter;
}
/// <summary>
/// Verifies that calling WriteEnd is valid.
/// </summary>
/// <param name="synchronousCall">true if the call is to be synchronous; false otherwise.</param>
private void VerifyCanWriteEnd(bool synchronousCall)
{
this.VerifyNotDisposed();
this.VerifyCallAllowed(synchronousCall);
this.VerifyNotInErrorOrCompletedState();
if (this.State != ParameterWriterState.CanWriteParameter)
{
throw new ODataException(Strings.ODataParameterWriterCore_CannotWriteEnd);
}
this.VerifyAllParametersWritten();
}
/// <summary>
/// If an <see cref="IEdmOperationImport"/> is specified, then this method ensures that all parameters present in the
/// operation import are written to the payload.
/// </summary>
/// <remarks>The binding parameter is optional in the payload. Hence this method will not check for missing binding parameter.</remarks>
private void VerifyAllParametersWritten()
{
Debug.Assert(this.State == ParameterWriterState.CanWriteParameter, "this.State == ParameterWriterState.CanWriteParameter");
if (this.operation != null && this.operation.Parameters != null)
{
IEnumerable<IEdmOperationParameter> parameters = null;
if (this.operation.IsBound)
{
// The binding parameter may or may not be present in the payload. Hence we don't throw error if the binding parameter is missing.
parameters = this.operation.Parameters.Skip(1);
}
else
{
parameters = this.operation.Parameters;
}
IEnumerable<string> missingParameters = parameters.Where(p => !this.parameterNamesWritten.Contains(p.Name) && !this.outputContext.EdmTypeResolver.GetParameterType(p).IsNullable).Select(p => p.Name);
if (missingParameters.Any())
{
missingParameters = missingParameters.Select(name => String.Format(CultureInfo.InvariantCulture, "'{0}'", name));
// We're calling the ToArray here since not all platforms support the string.Join which takes IEnumerable.
throw new ODataException(Strings.ODataParameterWriterCore_MissingParameterInParameterPayload(string.Join(", ", missingParameters.ToArray()), this.operation.Name));
}
}
}
/// <summary>
/// Finish writing a parameter payload - implementation of the actual functionality.
/// </summary>
private void WriteEndImplementation()
{
this.InterceptException(() => this.EndPayload());
this.LeaveScope();
}
/// <summary>
/// Verifies that the current state is not Error or Completed.
/// </summary>
private void VerifyNotInErrorOrCompletedState()
{
if (this.State == ParameterWriterState.Error || this.State == ParameterWriterState.Completed)
{
throw new ODataException(Strings.ODataParameterWriterCore_CannotWriteInErrorOrCompletedState);
}
}
/// <summary>
/// Verifies that calling Flush is valid.
/// </summary>
/// <param name="synchronousCall">true if the call is to be synchronous; false otherwise.</param>
private void VerifyCanFlush(bool synchronousCall)
{
this.VerifyNotDisposed();
this.VerifyCallAllowed(synchronousCall);
}
/// <summary>
/// Verifies that a call is allowed to the writer.
/// </summary>
/// <param name="synchronousCall">true if the call is to be synchronous; false otherwise.</param>
private void VerifyCallAllowed(bool synchronousCall)
{
if (synchronousCall)
{
if (!this.outputContext.Synchronous)
{
throw new ODataException(Strings.ODataParameterWriterCore_SyncCallOnAsyncWriter);
}
}
else
{
#if ODATALIB_ASYNC
if (this.outputContext.Synchronous)
{
throw new ODataException(Strings.ODataParameterWriterCore_AsyncCallOnSyncWriter);
}
#else
Debug.Assert(false, "Async calls are not allowed in this build.");
#endif
}
}
/// <summary>
/// Catch any exception thrown by the action passed in; in the exception case move the writer into
/// state ExceptionThrown and then rethrow the exception.
/// </summary>
/// <param name="action">The action to execute.</param>
private void InterceptException(Action action)
{
try
{
action();
}
catch
{
this.EnterErrorScope();
throw;
}
}
/// <summary>
/// Catch any exception thrown by the function passed in; in the exception case move the writer into
/// state ExceptionThrown and then rethrow the exception.
/// </summary>
/// <typeparam name="T">The return type of <paramref name="function"/>.</typeparam>
/// <param name="function">The function to execute.</param>
/// <returns>Returns the return value from executing <paramref name="function"/>.</returns>
private T InterceptException<T>(Func<T> function)
{
try
{
return function();
}
catch
{
this.EnterErrorScope();
throw;
}
}
/// <summary>
/// Enters the Error scope if we are not already in Error state.
/// </summary>
private void EnterErrorScope()
{
if (this.State != ParameterWriterState.Error)
{
this.EnterScope(ParameterWriterState.Error);
}
}
/// <summary>
/// Verifies that the transition from the current state into new state is valid and enter a new writer scope.
/// </summary>
/// <param name="newState">The writer state to transition into.</param>
private void EnterScope(ParameterWriterState newState)
{
this.ValidateTransition(newState);
this.scopes.Push(newState);
}
/// <summary>
/// Leave the current writer scope and return to the previous scope.
/// When reaching the top-level replace the 'Start' scope with a 'Completed' scope.
/// </summary>
/// <remarks>Note that this method is never called once the writer is in 'Error' state.</remarks>
private void LeaveScope()
{
Debug.Assert(this.State != ParameterWriterState.Error, "this.State != WriterState.Error");
this.ValidateTransition(ParameterWriterState.Completed);
// scopes is either [Start, CanWriteParameter] or [Start]
if (this.State == ParameterWriterState.CanWriteParameter)
{
this.scopes.Pop();
}
Debug.Assert(this.State == ParameterWriterState.Start, "this.State == ParameterWriterState.Start");
this.ReplaceScope(ParameterWriterState.Completed);
}
/// <summary>
/// Replaces the current scope with a new scope; checks that the transition is valid.
/// </summary>
/// <param name="newState">The new state to transition into.</param>
private void ReplaceScope(ParameterWriterState newState)
{
this.ValidateTransition(newState);
this.scopes.Pop();
this.scopes.Push(newState);
}
/// <summary>
/// Verify that the transition from the current state into new state is valid.
/// </summary>
/// <param name="newState">The new writer state to transition into.</param>
private void ValidateTransition(ParameterWriterState newState)
{
if (this.State != ParameterWriterState.Error && newState == ParameterWriterState.Error)
{
// we can always transition into an error state if we are not already in an error state
return;
}
switch (this.State)
{
case ParameterWriterState.Start:
if (newState != ParameterWriterState.CanWriteParameter && newState != ParameterWriterState.Completed)
{
throw new ODataException(Strings.General_InternalError(InternalErrorCodes.ODataParameterWriterCore_ValidateTransition_InvalidTransitionFromStart));
}
break;
case ParameterWriterState.CanWriteParameter:
if (newState != ParameterWriterState.CanWriteParameter && newState != ParameterWriterState.ActiveSubWriter && newState != ParameterWriterState.Completed)
{
throw new ODataException(Strings.General_InternalError(InternalErrorCodes.ODataParameterWriterCore_ValidateTransition_InvalidTransitionFromCanWriteParameter));
}
break;
case ParameterWriterState.ActiveSubWriter:
if (newState != ParameterWriterState.CanWriteParameter)
{
throw new ODataException(Strings.General_InternalError(InternalErrorCodes.ODataParameterWriterCore_ValidateTransition_InvalidTransitionFromActiveSubWriter));
}
break;
case ParameterWriterState.Completed:
// we should never see a state transition when in state 'Completed'
throw new ODataException(Strings.General_InternalError(InternalErrorCodes.ODataParameterWriterCore_ValidateTransition_InvalidTransitionFromCompleted));
case ParameterWriterState.Error:
if (newState != ParameterWriterState.Error)
{
// No more state transitions once we are in error state
throw new ODataException(Strings.General_InternalError(InternalErrorCodes.ODataParameterWriterCore_ValidateTransition_InvalidTransitionFromError));
}
break;
default:
throw new ODataException(Strings.General_InternalError(InternalErrorCodes.ODataParameterWriterCore_ValidateTransition_UnreachableCodePath));
}
}
}
}
| |
//
// GtkEngine.cs
//
// Author:
// Lluis Sanchez <lluis@xamarin.com>
//
// Copyright (c) 2011 Xamarin Inc
//
// 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 Xwt.Backends;
using Xwt.CairoBackend;
using Gdk;
using System.Reflection;
using System.IO;
namespace Xwt.GtkBackend
{
public class GtkEngine: ToolkitEngineBackend
{
GtkPlatformBackend platformBackend;
internal GtkPlatformBackend PlatformBackend { get { return platformBackend; } }
public override void InitializeApplication ()
{
Gtk.Application.Init ();
}
public override void InitializeBackends ()
{
RegisterBackend<ICustomWidgetBackend, CustomWidgetBackend> ();
RegisterBackend<IWindowBackend, WindowBackend> ();
RegisterBackend<ILabelBackend, LabelBackend> ();
RegisterBackend<IBoxBackend, BoxBackend> ();
RegisterBackend<IButtonBackend, ButtonBackend> ();
RegisterBackend<INotebookBackend, NotebookBackend> ();
RegisterBackend<ITreeViewBackend, TreeViewBackend> ();
RegisterBackend<ITreeStoreBackend, TreeStoreBackend> ();
RegisterBackend<IListViewBackend, ListViewBackend> ();
RegisterBackend<IListStoreBackend, ListStoreBackend> ();
RegisterBackend<ICanvasBackend, CanvasBackend> ();
RegisterBackend<ImageBackendHandler, ImageHandler> ();
RegisterBackend<Xwt.Backends.ContextBackendHandler, CairoContextBackendHandler> ();
RegisterBackend<TextLayoutBackendHandler, GtkTextLayoutBackendHandler> ();
RegisterBackend<DrawingPathBackendHandler, CairoContextBackendHandler> ();
RegisterBackend<GradientBackendHandler, CairoGradientBackendHandler> ();
RegisterBackend<FontBackendHandler, GtkFontBackendHandler> ();
RegisterBackend<IMenuBackend, MenuBackend> ();
RegisterBackend<IMenuItemBackend, MenuItemBackend> ();
RegisterBackend<ICheckBoxMenuItemBackend, CheckBoxMenuItemBackend> ();
RegisterBackend<IRadioButtonMenuItemBackend, RadioButtonMenuItemBackend> ();
RegisterBackend<ISeparatorMenuItemBackend, SeparatorMenuItemBackend> ();
RegisterBackend<IScrollViewBackend, ScrollViewBackend> ();
RegisterBackend<IComboBoxBackend, ComboBoxBackend> ();
RegisterBackend<IDesignerSurfaceBackend, DesignerSurfaceBackend> ();
RegisterBackend<IMenuButtonBackend, MenuButtonBackend> ();
RegisterBackend<ITextEntryBackend, TextEntryBackend> ();
RegisterBackend<IToggleButtonBackend, ToggleButtonBackend> ();
RegisterBackend<IImageViewBackend, ImageViewBackend> ();
RegisterBackend<IAlertDialogBackend, AlertDialogBackend> ();
RegisterBackend<ICheckBoxBackend, CheckBoxBackend> ();
RegisterBackend<IFrameBackend, FrameBackend> ();
RegisterBackend<ISeparatorBackend, SeparatorBackend> ();
RegisterBackend<IDialogBackend, DialogBackend> ();
RegisterBackend<IComboBoxEntryBackend, ComboBoxEntryBackend> ();
RegisterBackend<ClipboardBackend, GtkClipboardBackend> ();
RegisterBackend<ImagePatternBackendHandler, GtkImagePatternBackendHandler> ();
RegisterBackend<ImageBuilderBackendHandler, ImageBuilderBackend> ();
RegisterBackend<IScrollAdjustmentBackend, ScrollAdjustmentBackend> ();
RegisterBackend<IOpenFileDialogBackend, OpenFileDialogBackend> ();
RegisterBackend<ISaveFileDialogBackend, SaveFileDialogBackend> ();
RegisterBackend<ISelectFolderDialogBackend, SelectFolderDialogBackend> ();
RegisterBackend<IPanedBackend, PanedBackend> ();
RegisterBackend<ISelectColorDialogBackend, SelectColorDialogBackend> ();
RegisterBackend<IListBoxBackend, ListBoxBackend> ();
RegisterBackend<IStatusIconBackend, StatusIconBackend> ();
RegisterBackend<IProgressBarBackend, ProgressBarBackend> ();
RegisterBackend<IPopoverBackend, PopoverBackend> ();
RegisterBackend<ISpinButtonBackend, SpinButtonBackend> ();
RegisterBackend<IDatePickerBackend, DatePickerBackend> ();
RegisterBackend<ILinkLabelBackend, LinkLabelBackend> ();
RegisterBackend<ISpinnerBackend, SpinnerBackend> ();
RegisterBackend<IRichTextViewBackend, RichTextViewBackend> ();
RegisterBackend<IExpanderBackend, ExpanderBackend> ();
RegisterBackend<DesktopBackend, GtkDesktopBackend> ();
RegisterBackend<IEmbeddedWidgetBackend, EmbeddedWidgetBackend> ();
RegisterBackend<ISegmentedButtonBackend, SegmentedButtonBackend> ();
RegisterBackend<ISliderBackend, SliderBackend> ();
RegisterBackend<IRadioButtonBackend, RadioButtonBackend> ();
RegisterBackend<IScrollbarBackend, ScrollbarBackend> ();
RegisterBackend<IPasswordEntryBackend, PasswordEntryBackend> ();
RegisterBackend<KeyboardHandler, GtkKeyboardHandler> ();
RegisterBackend<ISearchTextEntryBackend, SearchTextEntryBackend> ();
RegisterBackend<IWebViewBackend, WebViewBackend> ();
RegisterBackend<IColorSelectorBackend, ColorSelectorBackend> ();
RegisterBackend<IColorPickerBackend, ColorPickerBackend> ();
RegisterBackend<ICalendarBackend, CalendarBackend> ();
RegisterBackend<IFontSelectorBackend, FontSelectorBackend> ();
RegisterBackend<ISelectFontDialogBackend, SelectFontDialogBackend> ();
RegisterBackend<IAccessibleBackend, AccessibleBackend> ();
RegisterBackend<IPopupWindowBackend, PopupWindowBackend> ();
RegisterBackend<IUtilityWindowBackend, UtilityWindowBackend> ();
string typeName = null;
string asmName = null;
if (Platform.IsMac) {
typeName = "Xwt.Gtk.Mac.MacPlatformBackend";
asmName = "Xwt.Gtk.Mac";
}
else if (Platform.IsWindows) {
typeName = "Xwt.Gtk.Windows.WindowsPlatformBackend";
asmName = "Xwt.Gtk.Windows";
}
if (typeName != null) {
var loc = Path.GetDirectoryName (GetType ().Assembly.Location);
loc = Path.Combine (loc, asmName + ".dll");
Assembly asm = null;
try {
if (File.Exists (loc)) {
asm = Assembly.LoadFrom (loc);
} else {
asm = Assembly.Load (asmName);
}
} catch {
// Not found
}
Type platformType = asm != null ? asm.GetType (typeName) : null;
if (platformType != null) {
platformBackend = (GtkPlatformBackend)Activator.CreateInstance (platformType);
platformBackend.Initialize (this);
}
}
}
public override void Dispose ()
{
GtkTextLayoutBackendHandler.DisposeResources ();
base.Dispose();
}
public override void RunApplication ()
{
Gtk.Application.Run ();
}
public override void ExitApplication ()
{
Gtk.Application.Quit ();
}
public override bool HandlesSizeNegotiation {
get {
return true;
}
}
public static void ReplaceChild (Gtk.Widget oldWidget, Gtk.Widget newWidget)
{
Gtk.Container cont = oldWidget.Parent as Gtk.Container;
if (cont == null)
return;
if (cont is IGtkContainer) {
((IGtkContainer)cont).ReplaceChild (oldWidget, newWidget);
}
else if (cont is Gtk.Notebook) {
Gtk.Notebook notebook = (Gtk.Notebook)cont;
Gtk.Notebook.NotebookChild nc = (Gtk.Notebook.NotebookChild)notebook [oldWidget];
var detachable = nc.Detachable;
var pos = nc.Position;
var reorderable = nc.Reorderable;
var tabExpand = nc.TabExpand;
var tabFill = nc.TabFill;
var label = notebook.GetTabLabel (oldWidget);
notebook.Remove (oldWidget);
notebook.InsertPage (newWidget, label, pos);
nc = (Gtk.Notebook.NotebookChild)notebook [newWidget];
nc.Detachable = detachable;
nc.Reorderable = reorderable;
nc.TabExpand = tabExpand;
nc.TabFill = tabFill;
}
else if (cont is Gtk.Paned) {
var paned = (Gtk.Paned)cont;
var pc = (Gtk.Paned.PanedChild)paned[oldWidget];
var resize = pc.Resize;
var shrink = pc.Shrink;
var pos = paned.Position;
if (paned.Child1 == oldWidget) {
paned.Remove (oldWidget);
paned.Pack1 (newWidget, resize, shrink);
} else {
paned.Remove (oldWidget);
paned.Pack2 (newWidget, resize, shrink);
}
paned.Position = pos;
}
else if (cont is Gtk.Bin) {
((Gtk.Bin)cont).Remove (oldWidget);
((Gtk.Bin)cont).Child = newWidget;
}
}
public override void InvokeAsync (Action action)
{
if (action == null)
throw new ArgumentNullException ("action");
// Switch to no Invoke(Action) once a gtk# release is done.
Gtk.Application.Invoke ((o, args) => {
action ();
});
}
public override object TimerInvoke (Func<bool> action, TimeSpan timeSpan)
{
if (action == null)
throw new ArgumentNullException ("action");
if (timeSpan.TotalMilliseconds < 0)
throw new ArgumentException ("Timer period must be >=0", "timeSpan");
return GLib.Timeout.Add ((uint) timeSpan.TotalMilliseconds, action.Invoke);
}
public override void CancelTimerInvoke (object id)
{
if (id == null)
throw new ArgumentNullException ("id");
GLib.Source.Remove ((uint)id);
}
public override object GetNativeWidget (Widget w)
{
IGtkWidgetBackend wb = (IGtkWidgetBackend)Toolkit.GetBackend (w);
return wb.Widget;
}
public override object GetNativeImage (Xwt.Drawing.Image image)
{
var pix = (GtkImage)Toolkit.GetBackend (image);
return pix.ToPixbuf (ApplicationContext, image.Size.Width, image.Size.Height);
}
public override IWindowFrameBackend GetBackendForWindow (object nativeWindow)
{
var win = new WindowFrameBackend ();
win.Window = (Gtk.Window) nativeWindow;
return win;
}
public override object GetNativeWindow (IWindowFrameBackend backend)
{
if (backend.Window is Gtk.Window)
return backend.Window;
if (Platform.IsMac)
return GtkMacInterop.GetGtkWindow (backend.Window);
return null;
}
public override object GetBackendForImage (object nativeImage)
{
if (nativeImage is Gdk.Pixbuf)
return new GtkImage ((Gdk.Pixbuf)nativeImage);
else if (nativeImage is string)
return new GtkImage ((string)nativeImage);
else if (nativeImage is GtkImage)
return nativeImage;
else
throw new NotSupportedException ();
}
public override object GetBackendForContext (object nativeWidget, object nativeContext)
{
Gtk.Widget w = (Gtk.Widget)nativeWidget;
return new CairoContextBackend (Util.GetScaleFactor (w)) { Context = (Cairo.Context)nativeContext };
}
public override object GetNativeParentWindow (Widget w)
{
IGtkWidgetBackend wb = (IGtkWidgetBackend)Toolkit.GetBackend (w);
return wb.Widget.Toplevel as Gtk.Window;
}
public override bool HasNativeParent (Widget w)
{
IGtkWidgetBackend wb = (IGtkWidgetBackend)Toolkit.GetBackend (w);
return wb.Widget.Parent != null;
}
public override void DispatchPendingEvents ()
{
// The loop is limited to 1000 iterations as a workaround for an issue that some users
// have experienced. Sometimes EventsPending starts return 'true' for all iterations,
// causing the loop to never end.
int n = 1000;
Gdk.Threads.Enter();
while (Gtk.Application.EventsPending () && --n > 0) {
Gtk.Application.RunIteration (false);
}
Gdk.Threads.Leave();
}
public override object RenderWidget (Widget widget)
{
var w = ((WidgetBackend)widget.GetBackend ()).Widget;
Gdk.Window win = w.GdkWindow;
if (win != null && win.IsViewable) {
int ww, wh;
win.GetSize (out ww, out wh);
if (ww == w.Allocation.Width && wh == w.Allocation.Height)
return new GtkImage (win.ToPixbuf (0, 0, w.Allocation.Width, w.Allocation.Height));
return new GtkImage (win.ToPixbuf (w.Allocation.X, w.Allocation.Y, w.Allocation.Width, w.Allocation.Height));
}
throw new InvalidOperationException ();
}
public override void RenderImage (object nativeWidget, object nativeContext, ImageDescription img, double x, double y)
{
GtkImage gim = (GtkImage)img.Backend;
Cairo.Context ctx = nativeContext as Cairo.Context;
Gtk.Widget w = (Gtk.Widget)nativeWidget;
if (ctx != null)
gim.Draw (ApplicationContext, ctx, Util.GetScaleFactor (w), x, y, img);
}
public override Rectangle GetScreenBounds (object nativeWidget)
{
var widget = nativeWidget as Gtk.Widget;
if (widget == null)
throw new InvalidOperationException ("Widget belongs to a different toolkit");
int x = 0, y = 0;
widget.GdkWindow?.GetOrigin (out x, out y);
var a = widget.Allocation;
x += a.X;
y += a.Y;
return new Rectangle (x, y, widget.Allocation.Width, widget.Allocation.Height);
}
public override ToolkitFeatures SupportedFeatures {
get {
var f = ToolkitFeatures.All;
if (GtkWorkarounds.GtkMajorVersion <= 2 ||
GtkWorkarounds.GtkMajorVersion == 3 && GtkWorkarounds.GtkMinorVersion < 8)
f &= ~ToolkitFeatures.WidgetOpacity;
if (Platform.IsWindows)
f &= ~ToolkitFeatures.WindowOpacity;
return f;
}
}
protected override Type GetBackendImplementationType (Type backendType)
{
if (platformBackend != null) {
var bt = platformBackend.GetBackendImplementationType (backendType);
if (bt != null)
return bt;
}
return base.GetBackendImplementationType (backendType);
}
}
public interface IGtkContainer
{
void ReplaceChild (Gtk.Widget oldWidget, Gtk.Widget newWidget);
}
}
| |
// 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.Xml.Schema
{
using System;
using System.Xml;
using System.Diagnostics;
using System.Text;
/// <summary>
/// This enum specifies what format should be used when converting string to XsdDateTime
/// </summary>
[Flags]
internal enum XsdDateTimeFlags
{
DateTime = 0x01,
Time = 0x02,
Date = 0x04,
GYearMonth = 0x08,
GYear = 0x10,
GMonthDay = 0x20,
GDay = 0x40,
GMonth = 0x80,
XdrDateTimeNoTz = 0x100,
XdrDateTime = 0x200,
XdrTimeNoTz = 0x400, //XDRTime with tz is the same as xsd:time
AllXsd = 0xFF //All still does not include the XDR formats
}
/// <summary>
/// This structure extends System.DateTime to support timeInTicks zone and Gregorian types components of an Xsd Duration. It is used internally to support Xsd durations without loss
/// of fidelity. XsdDuration structures are immutable once they've been created.
/// </summary>
internal struct XsdDateTime
{
// DateTime is being used as an internal representation only
// Casting XsdDateTime to DateTime might return a different value
private DateTime _dt;
// Additional information that DateTime is not preserving
// Information is stored in the following format:
// Bits Info
// 31-24 DateTimeTypeCode
// 23-16 XsdDateTimeKind
// 15-8 Zone Hours
// 7-0 Zone Minutes
private uint _extra;
// Subset of XML Schema types XsdDateTime represents
private enum DateTimeTypeCode
{
DateTime,
Time,
Date,
GYearMonth,
GYear,
GMonthDay,
GDay,
GMonth,
XdrDateTime,
}
// Internal representation of DateTimeKind
private enum XsdDateTimeKind
{
Unspecified,
Zulu,
LocalWestOfZulu, // GMT-1..14, N..Y
LocalEastOfZulu // GMT+1..14, A..M
}
// Masks and shifts used for packing and unpacking extra
private const uint TypeMask = 0xFF000000;
private const uint KindMask = 0x00FF0000;
private const uint ZoneHourMask = 0x0000FF00;
private const uint ZoneMinuteMask = 0x000000FF;
private const int TypeShift = 24;
private const int KindShift = 16;
private const int ZoneHourShift = 8;
// Maximum number of fraction digits;
private const short maxFractionDigits = 7;
private const int ticksToFractionDivisor = 10000000;
private static readonly int s_lzyyyy = "yyyy".Length;
private static readonly int s_lzyyyy_ = "yyyy-".Length;
private static readonly int s_lzyyyy_MM = "yyyy-MM".Length;
private static readonly int s_lzyyyy_MM_ = "yyyy-MM-".Length;
private static readonly int s_lzyyyy_MM_dd = "yyyy-MM-dd".Length;
private static readonly int s_lzyyyy_MM_ddT = "yyyy-MM-ddT".Length;
private static readonly int s_lzHH = "HH".Length;
private static readonly int s_lzHH_ = "HH:".Length;
private static readonly int s_lzHH_mm = "HH:mm".Length;
private static readonly int s_lzHH_mm_ = "HH:mm:".Length;
private static readonly int s_lzHH_mm_ss = "HH:mm:ss".Length;
private static readonly int s_Lz_ = "-".Length;
private static readonly int s_lz_zz = "-zz".Length;
private static readonly int s_lz_zz_ = "-zz:".Length;
private static readonly int s_lz_zz_zz = "-zz:zz".Length;
private static readonly int s_Lz__ = "--".Length;
private static readonly int s_lz__mm = "--MM".Length;
private static readonly int s_lz__mm_ = "--MM-".Length;
private static readonly int s_lz__mm__ = "--MM--".Length;
private static readonly int s_lz__mm_dd = "--MM-dd".Length;
private static readonly int s_Lz___ = "---".Length;
private static readonly int s_lz___dd = "---dd".Length;
// These values were copied from the DateTime class and are
// needed to convert ticks to year, month and day. See comment
// for method GetYearMonthDay for rationale.
// Number of 100ns ticks per time unit
private const long TicksPerMillisecond = 10000;
private const long TicksPerSecond = TicksPerMillisecond * 1000;
private const long TicksPerMinute = TicksPerSecond * 60;
private const long TicksPerHour = TicksPerMinute * 60;
private const long TicksPerDay = TicksPerHour * 24;
// Number of days in a non-leap year
private const int DaysPerYear = 365;
// Number of days in 4 years
private const int DaysPer4Years = DaysPerYear * 4 + 1; // 1461
// Number of days in 100 years
private const int DaysPer100Years = DaysPer4Years * 25 - 1; // 36524
// Number of days in 400 years
private const int DaysPer400Years = DaysPer100Years * 4 + 1; // 146097
private static readonly int[] DaysToMonth365 = {
0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365};
private static readonly int[] DaysToMonth366 = {
0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335, 366};
/// <summary>
/// Constructs an XsdDateTime from a string using specific format.
/// </summary>
public XsdDateTime(string text, XsdDateTimeFlags kinds) : this()
{
Parser parser = new Parser();
if (!parser.Parse(text, kinds))
{
throw new FormatException(SR.Format(SR.XmlConvert_BadFormat, text, kinds));
}
InitiateXsdDateTime(parser);
}
private XsdDateTime(Parser parser) : this()
{
InitiateXsdDateTime(parser);
}
private void InitiateXsdDateTime(Parser parser)
{
_dt = new DateTime(parser.year, parser.month, parser.day, parser.hour, parser.minute, parser.second);
if (parser.fraction != 0)
{
_dt = _dt.AddTicks(parser.fraction);
}
_extra = (uint)(((int)parser.typeCode << TypeShift) | ((int)parser.kind << KindShift) | (parser.zoneHour << ZoneHourShift) | parser.zoneMinute);
}
internal static bool TryParse(string text, XsdDateTimeFlags kinds, out XsdDateTime result)
{
Parser parser = new Parser();
if (!parser.Parse(text, kinds))
{
result = new XsdDateTime();
return false;
}
result = new XsdDateTime(parser);
return true;
}
/// <summary>
/// Constructs an XsdDateTime from a DateTime.
/// </summary>
public XsdDateTime(DateTime dateTime, XsdDateTimeFlags kinds)
{
Debug.Assert(Bits.ExactlyOne((uint)kinds), "Only one DateTime type code can be set.");
_dt = dateTime;
DateTimeTypeCode code = (DateTimeTypeCode)(Bits.LeastPosition((uint)kinds) - 1);
int zoneHour = 0;
int zoneMinute = 0;
XsdDateTimeKind kind;
switch (dateTime.Kind)
{
case DateTimeKind.Unspecified: kind = XsdDateTimeKind.Unspecified; break;
case DateTimeKind.Utc: kind = XsdDateTimeKind.Zulu; break;
default:
{
Debug.Assert(dateTime.Kind == DateTimeKind.Local, "Unknown DateTimeKind: " + dateTime.Kind);
TimeSpan utcOffset = TimeZoneInfo.Local.GetUtcOffset(dateTime);
if (utcOffset.Ticks < 0)
{
kind = XsdDateTimeKind.LocalWestOfZulu;
zoneHour = -utcOffset.Hours;
zoneMinute = -utcOffset.Minutes;
}
else
{
kind = XsdDateTimeKind.LocalEastOfZulu;
zoneHour = utcOffset.Hours;
zoneMinute = utcOffset.Minutes;
}
break;
}
}
_extra = (uint)(((int)code << TypeShift) | ((int)kind << KindShift) | (zoneHour << ZoneHourShift) | zoneMinute);
}
// Constructs an XsdDateTime from a DateTimeOffset
public XsdDateTime(DateTimeOffset dateTimeOffset) : this(dateTimeOffset, XsdDateTimeFlags.DateTime)
{
}
public XsdDateTime(DateTimeOffset dateTimeOffset, XsdDateTimeFlags kinds)
{
Debug.Assert(Bits.ExactlyOne((uint)kinds), "Only one DateTime type code can be set.");
_dt = dateTimeOffset.DateTime;
TimeSpan zoneOffset = dateTimeOffset.Offset;
DateTimeTypeCode code = (DateTimeTypeCode)(Bits.LeastPosition((uint)kinds) - 1);
XsdDateTimeKind kind;
if (zoneOffset.TotalMinutes < 0)
{
zoneOffset = zoneOffset.Negate();
kind = XsdDateTimeKind.LocalWestOfZulu;
}
else if (zoneOffset.TotalMinutes > 0)
{
kind = XsdDateTimeKind.LocalEastOfZulu;
}
else
{
kind = XsdDateTimeKind.Zulu;
}
_extra = (uint)(((int)code << TypeShift) | ((int)kind << KindShift) | (zoneOffset.Hours << ZoneHourShift) | zoneOffset.Minutes);
}
/// <summary>
/// Returns auxiliary enumeration of XSD date type
/// </summary>
private DateTimeTypeCode InternalTypeCode
{
get { return (DateTimeTypeCode)((_extra & TypeMask) >> TypeShift); }
}
/// <summary>
/// Returns geographical "position" of the value
/// </summary>
private XsdDateTimeKind InternalKind
{
get { return (XsdDateTimeKind)((_extra & KindMask) >> KindShift); }
}
/// <summary>
/// Returns XmlTypeCode of the value being stored
/// </summary>
public XmlTypeCode TypeCode
{
get { return s_typeCodes[(int)InternalTypeCode]; }
}
/// <summary>
/// Returns the year part of XsdDateTime
/// The returned value is integer between 1 and 9999
/// </summary>
public int Year
{
get { return _dt.Year; }
}
/// <summary>
/// Returns the month part of XsdDateTime
/// The returned value is integer between 1 and 12
/// </summary>
public int Month
{
get { return _dt.Month; }
}
/// <summary>
/// Returns the day of the month part of XsdDateTime
/// The returned value is integer between 1 and 31
/// </summary>
public int Day
{
get { return _dt.Day; }
}
/// <summary>
/// Returns the hour part of XsdDateTime
/// The returned value is integer between 0 and 23
/// </summary>
public int Hour
{
get { return _dt.Hour; }
}
/// <summary>
/// Returns the minute part of XsdDateTime
/// The returned value is integer between 0 and 60
/// </summary>
public int Minute
{
get { return _dt.Minute; }
}
/// <summary>
/// Returns the second part of XsdDateTime
/// The returned value is integer between 0 and 60
/// </summary>
public int Second
{
get { return _dt.Second; }
}
/// <summary>
/// Returns number of ticks in the fraction of the second
/// The returned value is integer between 0 and 9999999
/// </summary>
public int Fraction
{
get { return (int)(_dt.Ticks % ticksToFractionDivisor); }
}
/// <summary>
/// Returns the hour part of the time zone
/// The returned value is integer between -13 and 13
/// </summary>
public int ZoneHour
{
get
{
uint result = (_extra & ZoneHourMask) >> ZoneHourShift;
return (int)result;
}
}
/// <summary>
/// Returns the minute part of the time zone
/// The returned value is integer between 0 and 60
/// </summary>
public int ZoneMinute
{
get
{
uint result = (_extra & ZoneMinuteMask);
return (int)result;
}
}
public DateTime ToZulu()
{
switch (InternalKind)
{
case XsdDateTimeKind.Zulu:
// set it to UTC
return new DateTime(_dt.Ticks, DateTimeKind.Utc);
case XsdDateTimeKind.LocalEastOfZulu:
// Adjust to UTC and then convert to local in the current time zone
return new DateTime(_dt.Subtract(new TimeSpan(ZoneHour, ZoneMinute, 0)).Ticks, DateTimeKind.Utc);
case XsdDateTimeKind.LocalWestOfZulu:
// Adjust to UTC and then convert to local in the current time zone
return new DateTime(_dt.Add(new TimeSpan(ZoneHour, ZoneMinute, 0)).Ticks, DateTimeKind.Utc);
default:
return _dt;
}
}
/// <summary>
/// Cast to DateTime
/// The following table describes the behaviors of getting the default value
/// when a certain year/month/day values are missing.
///
/// An "X" means that the value exists. And "--" means that value is missing.
///
/// Year Month Day => ResultYear ResultMonth ResultDay Note
///
/// X X X Parsed year Parsed month Parsed day
/// X X -- Parsed Year Parsed month First day If we have year and month, assume the first day of that month.
/// X -- X Parsed year First month Parsed day If the month is missing, assume first month of that year.
/// X -- -- Parsed year First month First day If we have only the year, assume the first day of that year.
///
/// -- X X CurrentYear Parsed month Parsed day If the year is missing, assume the current year.
/// -- X -- CurrentYear Parsed month First day If we have only a month value, assume the current year and current day.
/// -- -- X CurrentYear First month Parsed day If we have only a day value, assume current year and first month.
/// -- -- -- CurrentYear Current month Current day So this means that if the date string only contains time, you will get current date.
/// </summary>
public static implicit operator DateTime(XsdDateTime xdt)
{
DateTime result;
switch (xdt.InternalTypeCode)
{
case DateTimeTypeCode.GMonth:
case DateTimeTypeCode.GDay:
result = new DateTime(DateTime.Now.Year, xdt.Month, xdt.Day);
break;
case DateTimeTypeCode.Time:
//back to DateTime.Now
DateTime currentDateTime = DateTime.Now;
TimeSpan addDiff = new DateTime(currentDateTime.Year, currentDateTime.Month, currentDateTime.Day) - new DateTime(xdt.Year, xdt.Month, xdt.Day);
result = xdt._dt.Add(addDiff);
break;
default:
result = xdt._dt;
break;
}
long ticks;
switch (xdt.InternalKind)
{
case XsdDateTimeKind.Zulu:
// set it to UTC
result = new DateTime(result.Ticks, DateTimeKind.Utc);
break;
case XsdDateTimeKind.LocalEastOfZulu:
// Adjust to UTC and then convert to local in the current time zone
ticks = result.Ticks - new TimeSpan(xdt.ZoneHour, xdt.ZoneMinute, 0).Ticks;
if (ticks < DateTime.MinValue.Ticks)
{
// Underflow. Return the DateTime as local time directly
ticks += TimeZoneInfo.Local.GetUtcOffset(result).Ticks;
if (ticks < DateTime.MinValue.Ticks)
ticks = DateTime.MinValue.Ticks;
return new DateTime(ticks, DateTimeKind.Local);
}
result = new DateTime(ticks, DateTimeKind.Utc).ToLocalTime();
break;
case XsdDateTimeKind.LocalWestOfZulu:
// Adjust to UTC and then convert to local in the current time zone
ticks = result.Ticks + new TimeSpan(xdt.ZoneHour, xdt.ZoneMinute, 0).Ticks;
if (ticks > DateTime.MaxValue.Ticks)
{
// Overflow. Return the DateTime as local time directly
ticks += TimeZoneInfo.Local.GetUtcOffset(result).Ticks;
if (ticks > DateTime.MaxValue.Ticks)
ticks = DateTime.MaxValue.Ticks;
return new DateTime(ticks, DateTimeKind.Local);
}
result = new DateTime(ticks, DateTimeKind.Utc).ToLocalTime();
break;
default:
break;
}
return result;
}
public static implicit operator DateTimeOffset(XsdDateTime xdt)
{
DateTime dt;
switch (xdt.InternalTypeCode)
{
case DateTimeTypeCode.GMonth:
case DateTimeTypeCode.GDay:
dt = new DateTime(DateTime.Now.Year, xdt.Month, xdt.Day);
break;
case DateTimeTypeCode.Time:
//back to DateTime.Now
DateTime currentDateTime = DateTime.Now;
TimeSpan addDiff = new DateTime(currentDateTime.Year, currentDateTime.Month, currentDateTime.Day) - new DateTime(xdt.Year, xdt.Month, xdt.Day);
dt = xdt._dt.Add(addDiff);
break;
default:
dt = xdt._dt;
break;
}
DateTimeOffset result;
switch (xdt.InternalKind)
{
case XsdDateTimeKind.LocalEastOfZulu:
result = new DateTimeOffset(dt, new TimeSpan(xdt.ZoneHour, xdt.ZoneMinute, 0));
break;
case XsdDateTimeKind.LocalWestOfZulu:
result = new DateTimeOffset(dt, new TimeSpan(-xdt.ZoneHour, -xdt.ZoneMinute, 0));
break;
case XsdDateTimeKind.Zulu:
result = new DateTimeOffset(dt, new TimeSpan(0));
break;
case XsdDateTimeKind.Unspecified:
default:
result = new DateTimeOffset(dt, TimeZoneInfo.Local.GetUtcOffset(dt));
break;
}
return result;
}
/// <summary>
/// Serialization to a string
/// </summary>
public override string ToString()
{
StringBuilder sb = new StringBuilder(64);
char[] text;
switch (InternalTypeCode)
{
case DateTimeTypeCode.DateTime:
PrintDate(sb);
sb.Append('T');
PrintTime(sb);
break;
case DateTimeTypeCode.Time:
PrintTime(sb);
break;
case DateTimeTypeCode.Date:
PrintDate(sb);
break;
case DateTimeTypeCode.GYearMonth:
text = new char[s_lzyyyy_MM];
IntToCharArray(text, 0, Year, 4);
text[s_lzyyyy] = '-';
ShortToCharArray(text, s_lzyyyy_, Month);
sb.Append(text);
break;
case DateTimeTypeCode.GYear:
text = new char[s_lzyyyy];
IntToCharArray(text, 0, Year, 4);
sb.Append(text);
break;
case DateTimeTypeCode.GMonthDay:
text = new char[s_lz__mm_dd];
text[0] = '-';
text[s_Lz_] = '-';
ShortToCharArray(text, s_Lz__, Month);
text[s_lz__mm] = '-';
ShortToCharArray(text, s_lz__mm_, Day);
sb.Append(text);
break;
case DateTimeTypeCode.GDay:
text = new char[s_lz___dd];
text[0] = '-';
text[s_Lz_] = '-';
text[s_Lz__] = '-';
ShortToCharArray(text, s_Lz___, Day);
sb.Append(text);
break;
case DateTimeTypeCode.GMonth:
text = new char[s_lz__mm__];
text[0] = '-';
text[s_Lz_] = '-';
ShortToCharArray(text, s_Lz__, Month);
text[s_lz__mm] = '-';
text[s_lz__mm_] = '-';
sb.Append(text);
break;
}
PrintZone(sb);
return sb.ToString();
}
// Serialize year, month and day
private void PrintDate(StringBuilder sb)
{
char[] text = new char[s_lzyyyy_MM_dd];
int year, month, day;
GetYearMonthDay(out year, out month, out day);
IntToCharArray(text, 0, year, 4);
text[s_lzyyyy] = '-';
ShortToCharArray(text, s_lzyyyy_, month);
text[s_lzyyyy_MM] = '-';
ShortToCharArray(text, s_lzyyyy_MM_, day);
sb.Append(text);
}
// When printing the date, we need the year, month and the day. When
// requesting these values from DateTime, it needs to redo the year
// calculation before it can calculate the month, and it needs to redo
// the year and month calculation before it can calculate the day. This
// results in the year being calculated 3 times, the month twice and the
// day once. As we know that we need all 3 values, by duplicating the
// logic here we can calculate the number of days and return the intermediate
// calculations for month and year without the added cost.
private void GetYearMonthDay(out int year, out int month, out int day)
{
long ticks = _dt.Ticks;
// n = number of days since 1/1/0001
int n = (int)(ticks / TicksPerDay);
// y400 = number of whole 400-year periods since 1/1/0001
int y400 = n / DaysPer400Years;
// n = day number within 400-year period
n -= y400 * DaysPer400Years;
// y100 = number of whole 100-year periods within 400-year period
int y100 = n / DaysPer100Years;
// Last 100-year period has an extra day, so decrement result if 4
if (y100 == 4)
y100 = 3;
// n = day number within 100-year period
n -= y100 * DaysPer100Years;
// y4 = number of whole 4-year periods within 100-year period
int y4 = n / DaysPer4Years;
// n = day number within 4-year period
n -= y4 * DaysPer4Years;
// y1 = number of whole years within 4-year period
int y1 = n / DaysPerYear;
// Last year has an extra day, so decrement result if 4
if (y1 == 4)
y1 = 3;
year = y400 * 400 + y100 * 100 + y4 * 4 + y1 + 1;
// n = day number within year
n -= y1 * DaysPerYear;
// Leap year calculation looks different from IsLeapYear since y1, y4,
// and y100 are relative to year 1, not year 0
bool leapYear = y1 == 3 && (y4 != 24 || y100 == 3);
int[] days = leapYear ? DaysToMonth366 : DaysToMonth365;
// All months have less than 32 days, so n >> 5 is a good conservative
// estimate for the month
month = n >> 5 + 1;
// m = 1-based month number
while (n >= days[month])
month++;
day = n - days[month - 1] + 1;
}
// Serialize hour, minute, second and fraction
private void PrintTime(StringBuilder sb)
{
char[] text = new char[s_lzHH_mm_ss];
ShortToCharArray(text, 0, Hour);
text[s_lzHH] = ':';
ShortToCharArray(text, s_lzHH_, Minute);
text[s_lzHH_mm] = ':';
ShortToCharArray(text, s_lzHH_mm_, Second);
sb.Append(text);
int fraction = Fraction;
if (fraction != 0)
{
int fractionDigits = maxFractionDigits;
while (fraction % 10 == 0)
{
fractionDigits--;
fraction /= 10;
}
text = new char[fractionDigits + 1];
text[0] = '.';
IntToCharArray(text, 1, fraction, fractionDigits);
sb.Append(text);
}
}
// Serialize time zone
private void PrintZone(StringBuilder sb)
{
char[] text;
switch (InternalKind)
{
case XsdDateTimeKind.Zulu:
sb.Append('Z');
break;
case XsdDateTimeKind.LocalWestOfZulu:
text = new char[s_lz_zz_zz];
text[0] = '-';
ShortToCharArray(text, s_Lz_, ZoneHour);
text[s_lz_zz] = ':';
ShortToCharArray(text, s_lz_zz_, ZoneMinute);
sb.Append(text);
break;
case XsdDateTimeKind.LocalEastOfZulu:
text = new char[s_lz_zz_zz];
text[0] = '+';
ShortToCharArray(text, s_Lz_, ZoneHour);
text[s_lz_zz] = ':';
ShortToCharArray(text, s_lz_zz_, ZoneMinute);
sb.Append(text);
break;
default:
// do nothing
break;
}
}
// Serialize integer into character array starting with index [start].
// Number of digits is set by [digits]
private void IntToCharArray(char[] text, int start, int value, int digits)
{
while (digits-- != 0)
{
text[start + digits] = (char)(value % 10 + '0');
value /= 10;
}
}
// Serialize two digit integer into character array starting with index [start].
private void ShortToCharArray(char[] text, int start, int value)
{
text[start] = (char)(value / 10 + '0');
text[start + 1] = (char)(value % 10 + '0');
}
private static readonly XmlTypeCode[] s_typeCodes = {
XmlTypeCode.DateTime,
XmlTypeCode.Time,
XmlTypeCode.Date,
XmlTypeCode.GYearMonth,
XmlTypeCode.GYear,
XmlTypeCode.GMonthDay,
XmlTypeCode.GDay,
XmlTypeCode.GMonth
};
// Parsing string according to XML schema spec
private struct Parser
{
private const int leapYear = 1904;
private const int firstMonth = 1;
private const int firstDay = 1;
public DateTimeTypeCode typeCode;
public int year;
public int month;
public int day;
public int hour;
public int minute;
public int second;
public int fraction;
public XsdDateTimeKind kind;
public int zoneHour;
public int zoneMinute;
private string _text;
private int _length;
public bool Parse(string text, XsdDateTimeFlags kinds)
{
_text = text;
_length = text.Length;
// Skip leading whitespace
int start = 0;
while (start < _length && char.IsWhiteSpace(text[start]))
{
start++;
}
// Choose format starting from the most common and trying not to reparse the same thing too many times
if (Test(kinds, XsdDateTimeFlags.DateTime | XsdDateTimeFlags.Date | XsdDateTimeFlags.XdrDateTime | XsdDateTimeFlags.XdrDateTimeNoTz))
{
if (ParseDate(start))
{
if (Test(kinds, XsdDateTimeFlags.DateTime))
{
if (ParseChar(start + s_lzyyyy_MM_dd, 'T') && ParseTimeAndZoneAndWhitespace(start + s_lzyyyy_MM_ddT))
{
typeCode = DateTimeTypeCode.DateTime;
return true;
}
}
if (Test(kinds, XsdDateTimeFlags.Date))
{
if (ParseZoneAndWhitespace(start + s_lzyyyy_MM_dd))
{
typeCode = DateTimeTypeCode.Date;
return true;
}
}
if (Test(kinds, XsdDateTimeFlags.XdrDateTime))
{
if (ParseZoneAndWhitespace(start + s_lzyyyy_MM_dd) || (ParseChar(start + s_lzyyyy_MM_dd, 'T') && ParseTimeAndZoneAndWhitespace(start + s_lzyyyy_MM_ddT)))
{
typeCode = DateTimeTypeCode.XdrDateTime;
return true;
}
}
if (Test(kinds, XsdDateTimeFlags.XdrDateTimeNoTz))
{
if (ParseChar(start + s_lzyyyy_MM_dd, 'T'))
{
if (ParseTimeAndWhitespace(start + s_lzyyyy_MM_ddT))
{
typeCode = DateTimeTypeCode.XdrDateTime;
return true;
}
}
else
{
typeCode = DateTimeTypeCode.XdrDateTime;
return true;
}
}
}
}
if (Test(kinds, XsdDateTimeFlags.Time))
{
if (ParseTimeAndZoneAndWhitespace(start))
{ //Equivalent to NoCurrentDateDefault on DateTimeStyles while parsing xs:time
year = leapYear;
month = firstMonth;
day = firstDay;
typeCode = DateTimeTypeCode.Time;
return true;
}
}
if (Test(kinds, XsdDateTimeFlags.XdrTimeNoTz))
{
if (ParseTimeAndWhitespace(start))
{ //Equivalent to NoCurrentDateDefault on DateTimeStyles while parsing xs:time
year = leapYear;
month = firstMonth;
day = firstDay;
typeCode = DateTimeTypeCode.Time;
return true;
}
}
if (Test(kinds, XsdDateTimeFlags.GYearMonth | XsdDateTimeFlags.GYear))
{
if (Parse4Dig(start, ref year) && 1 <= year)
{
if (Test(kinds, XsdDateTimeFlags.GYearMonth))
{
if (
ParseChar(start + s_lzyyyy, '-') &&
Parse2Dig(start + s_lzyyyy_, ref month) && 1 <= month && month <= 12 &&
ParseZoneAndWhitespace(start + s_lzyyyy_MM)
)
{
day = firstDay;
typeCode = DateTimeTypeCode.GYearMonth;
return true;
}
}
if (Test(kinds, XsdDateTimeFlags.GYear))
{
if (ParseZoneAndWhitespace(start + s_lzyyyy))
{
month = firstMonth;
day = firstDay;
typeCode = DateTimeTypeCode.GYear;
return true;
}
}
}
}
if (Test(kinds, XsdDateTimeFlags.GMonthDay | XsdDateTimeFlags.GMonth))
{
if (
ParseChar(start, '-') &&
ParseChar(start + s_Lz_, '-') &&
Parse2Dig(start + s_Lz__, ref month) && 1 <= month && month <= 12
)
{
if (Test(kinds, XsdDateTimeFlags.GMonthDay) && ParseChar(start + s_lz__mm, '-'))
{
if (
Parse2Dig(start + s_lz__mm_, ref day) && 1 <= day && day <= DateTime.DaysInMonth(leapYear, month) &&
ParseZoneAndWhitespace(start + s_lz__mm_dd)
)
{
year = leapYear;
typeCode = DateTimeTypeCode.GMonthDay;
return true;
}
}
if (Test(kinds, XsdDateTimeFlags.GMonth))
{
if (ParseZoneAndWhitespace(start + s_lz__mm) || (ParseChar(start + s_lz__mm, '-') && ParseChar(start + s_lz__mm_, '-') && ParseZoneAndWhitespace(start + s_lz__mm__)))
{
year = leapYear;
day = firstDay;
typeCode = DateTimeTypeCode.GMonth;
return true;
}
}
}
}
if (Test(kinds, XsdDateTimeFlags.GDay))
{
if (
ParseChar(start, '-') &&
ParseChar(start + s_Lz_, '-') &&
ParseChar(start + s_Lz__, '-') &&
Parse2Dig(start + s_Lz___, ref day) && 1 <= day && day <= DateTime.DaysInMonth(leapYear, firstMonth) &&
ParseZoneAndWhitespace(start + s_lz___dd)
)
{
year = leapYear;
month = firstMonth;
typeCode = DateTimeTypeCode.GDay;
return true;
}
}
return false;
}
private bool ParseDate(int start)
{
return
Parse4Dig(start, ref year) && 1 <= year &&
ParseChar(start + s_lzyyyy, '-') &&
Parse2Dig(start + s_lzyyyy_, ref month) && 1 <= month && month <= 12 &&
ParseChar(start + s_lzyyyy_MM, '-') &&
Parse2Dig(start + s_lzyyyy_MM_, ref day) && 1 <= day && day <= DateTime.DaysInMonth(year, month);
}
private bool ParseTimeAndZoneAndWhitespace(int start)
{
if (ParseTime(ref start))
{
if (ParseZoneAndWhitespace(start))
{
return true;
}
}
return false;
}
private bool ParseTimeAndWhitespace(int start)
{
if (ParseTime(ref start))
{
while (start < _length)
{//&& char.IsWhiteSpace(text[start])) {
start++;
}
return start == _length;
}
return false;
}
private static int[] s_power10 = new int[maxFractionDigits] { -1, 10, 100, 1000, 10000, 100000, 1000000 };
private bool ParseTime(ref int start)
{
if (
Parse2Dig(start, ref hour) && hour < 24 &&
ParseChar(start + s_lzHH, ':') &&
Parse2Dig(start + s_lzHH_, ref minute) && minute < 60 &&
ParseChar(start + s_lzHH_mm, ':') &&
Parse2Dig(start + s_lzHH_mm_, ref second) && second < 60
)
{
start += s_lzHH_mm_ss;
if (ParseChar(start, '.'))
{
// Parse factional part of seconds
// We allow any number of digits, but keep only first 7
this.fraction = 0;
int fractionDigits = 0;
int round = 0;
while (++start < _length)
{
int d = _text[start] - '0';
if (9u < unchecked((uint)d))
{ // d < 0 || 9 < d
break;
}
if (fractionDigits < maxFractionDigits)
{
this.fraction = (this.fraction * 10) + d;
}
else if (fractionDigits == maxFractionDigits)
{
if (5 < d)
{
round = 1;
}
else if (d == 5)
{
round = -1;
}
}
else if (round < 0 && d != 0)
{
round = 1;
}
fractionDigits++;
}
if (fractionDigits < maxFractionDigits)
{
if (fractionDigits == 0)
{
return false; // cannot end with .
}
fraction *= s_power10[maxFractionDigits - fractionDigits];
}
else
{
if (round < 0)
{
round = fraction & 1;
}
fraction += round;
}
}
return true;
}
// cleanup - conflict with gYear
hour = 0;
return false;
}
private bool ParseZoneAndWhitespace(int start)
{
if (start < _length)
{
char ch = _text[start];
if (ch == 'Z' || ch == 'z')
{
kind = XsdDateTimeKind.Zulu;
start++;
}
else if (start + 5 < _length)
{
if (
Parse2Dig(start + s_Lz_, ref zoneHour) && zoneHour <= 99 &&
ParseChar(start + s_lz_zz, ':') &&
Parse2Dig(start + s_lz_zz_, ref zoneMinute) && zoneMinute <= 99
)
{
if (ch == '-')
{
kind = XsdDateTimeKind.LocalWestOfZulu;
start += s_lz_zz_zz;
}
else if (ch == '+')
{
kind = XsdDateTimeKind.LocalEastOfZulu;
start += s_lz_zz_zz;
}
}
}
}
while (start < _length && char.IsWhiteSpace(_text[start]))
{
start++;
}
return start == _length;
}
private bool Parse4Dig(int start, ref int num)
{
if (start + 3 < _length)
{
int d4 = _text[start] - '0';
int d3 = _text[start + 1] - '0';
int d2 = _text[start + 2] - '0';
int d1 = _text[start + 3] - '0';
if (0 <= d4 && d4 < 10 &&
0 <= d3 && d3 < 10 &&
0 <= d2 && d2 < 10 &&
0 <= d1 && d1 < 10
)
{
num = ((d4 * 10 + d3) * 10 + d2) * 10 + d1;
return true;
}
}
return false;
}
private bool Parse2Dig(int start, ref int num)
{
if (start + 1 < _length)
{
int d2 = _text[start] - '0';
int d1 = _text[start + 1] - '0';
if (0 <= d2 && d2 < 10 &&
0 <= d1 && d1 < 10
)
{
num = d2 * 10 + d1;
return true;
}
}
return false;
}
private bool ParseChar(int start, char ch)
{
return start < _length && _text[start] == ch;
}
private static bool Test(XsdDateTimeFlags left, XsdDateTimeFlags right)
{
return (left & right) != 0;
}
}
}
}
| |
//
// ContentDisposition.cs
//
// Author: Jeffrey Stedfast <jeff@xamarin.com>
//
// Copyright (c) 2013-2016 Xamarin Inc.
//
// 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.Text;
#if PORTABLE
using Encoding = Portable.Text.Encoding;
#endif
using MimeKit.Utils;
namespace MimeKit {
/// <summary>
/// A class representing a Content-Disposition header value.
/// </summary>
/// <remarks>
/// The Content-Disposition header is a way for the originating client to
/// suggest to the receiving client whether to present the part to the user
/// as an attachment or as part of the content (inline).
/// </remarks>
public class ContentDisposition
{
/// <summary>
/// The attachment disposition.
/// </summary>
/// <remarks>
/// Indicates that the <see cref="MimePart"/> should be treated as an attachment.
/// </remarks>
public const string Attachment = "attachment";
/// <summary>
/// The form-data disposition.
/// </summary>
/// <remarks>
/// Indicates that the <see cref="MimePart"/> should be treated as form data.
/// </remarks>
public const string FormData = "form-data";
/// <summary>
/// The inline disposition.
/// </summary>
/// <remarks>
/// Indicates that the <see cref="MimePart"/> should be rendered inline.
/// </remarks>
public const string Inline = "inline";
ParameterList parameters;
string disposition;
/// <summary>
/// Initializes a new instance of the <see cref="MimeKit.ContentDisposition"/> class.
/// </summary>
/// <remarks>
/// The disposition should either be <see cref="ContentDisposition.Attachment"/>
/// or <see cref="ContentDisposition.Inline"/>.
/// </remarks>
/// <param name="disposition">The disposition.</param>
/// <exception cref="System.ArgumentNullException">
/// <paramref name="disposition"/> is <c>null</c>.
/// </exception>
/// <exception cref="System.ArgumentException">
/// <paramref name="disposition"/> is not <c>"attachment"</c> or <c>"inline"</c>.
/// </exception>
public ContentDisposition (string disposition)
{
Parameters = new ParameterList ();
Disposition = disposition;
}
/// <summary>
/// Initializes a new instance of the <see cref="MimeKit.ContentDisposition"/> class.
/// </summary>
/// <remarks>
/// This is identical to <see cref="ContentDisposition(string)"/> with a disposition
/// value of <see cref="ContentDisposition.Attachment"/>.
/// </remarks>
public ContentDisposition () : this (Attachment)
{
}
static bool IsAsciiAtom (byte c)
{
return c.IsAsciiAtom ();
}
/// <summary>
/// Gets or sets the disposition.
/// </summary>
/// <remarks>
/// The disposition is typically either <c>"attachment"</c> or <c>"inline"</c>.
/// </remarks>
/// <value>The disposition.</value>
/// <exception cref="System.ArgumentNullException">
/// <paramref name="value"/> is <c>null</c>.
/// </exception>
/// <exception cref="System.ArgumentException">
/// <paramref name="value"/> is an invalid disposition value.
/// </exception>
public string Disposition {
get { return disposition; }
set {
if (value == null)
throw new ArgumentNullException ("value");
if (value.Length == 0)
throw new ArgumentException ("The disposition is not allowed to be empty.", "value");
for (int i = 0; i < value.Length; i++) {
if (value[i] >= 127 || !IsAsciiAtom ((byte) value[i]))
throw new ArgumentException ("Illegal characters in disposition value.", "value");
}
if (disposition == value)
return;
disposition = value;
OnChanged ();
}
}
/// <summary>
/// Gets or sets a value indicating whether the <see cref="MimePart"/> is an attachment.
/// </summary>
/// <remarks>
/// A convenience property to determine if the entity should be considered an attachment or not.
/// </remarks>
/// <value><c>true</c> if the <see cref="MimePart"/> is an attachment; otherwise, <c>false</c>.</value>
public bool IsAttachment {
get { return disposition.Equals (Attachment, StringComparison.OrdinalIgnoreCase); }
set { disposition = value ? Attachment : Inline; }
}
/// <summary>
/// Gets the parameters.
/// </summary>
/// <remarks>
/// In addition to specifying whether the entity should be treated as an
/// attachment vs displayed inline, the Content-Disposition header may also
/// contain parameters to provide further information to the receiving client
/// such as the file attributes.
/// </remarks>
/// <value>The parameters.</value>
public ParameterList Parameters {
get { return parameters; }
private set {
if (parameters != null)
parameters.Changed -= OnParametersChanged;
value.Changed += OnParametersChanged;
parameters = value;
}
}
/// <summary>
/// Gets or sets the name of the file.
/// </summary>
/// <remarks>
/// When set, this can provide a useful hint for a default file name for the
/// content when the user decides to save it to disk.
/// </remarks>
/// <value>The name of the file.</value>
public string FileName {
get { return Parameters["filename"]; }
set {
if (value != null)
Parameters["filename"] = value;
else
Parameters.Remove ("filename");
}
}
static bool IsNullOrWhiteSpace (string value)
{
if (string.IsNullOrEmpty (value))
return true;
for (int i = 0; i < value.Length; i++) {
if (!char.IsWhiteSpace (value[i]))
return false;
}
return true;
}
/// <summary>
/// Gets or sets the creation-date parameter.
/// </summary>
/// <remarks>
/// Refers to the date and time that the content file was created on the
/// originating system. This parameter serves little purpose and is
/// typically not used by mail clients.
/// </remarks>
/// <value>The creation date.</value>
public DateTimeOffset? CreationDate {
get {
var value = Parameters["creation-date"];
if (IsNullOrWhiteSpace (value))
return null;
var buffer = Encoding.UTF8.GetBytes (value);
DateTimeOffset ctime;
if (!DateUtils.TryParse (buffer, 0, buffer.Length, out ctime))
return null;
return ctime;
}
set {
if (value.HasValue)
Parameters["creation-date"] = DateUtils.FormatDate (value.Value);
else
Parameters.Remove ("creation-date");
}
}
/// <summary>
/// Gets or sets the modification-date parameter.
/// </summary>
/// <remarks>
/// Refers to the date and time that the content file was last modified on
/// the originating system. This parameter serves little purpose and is
/// typically not used by mail clients.
/// </remarks>
/// <value>The modification date.</value>
public DateTimeOffset? ModificationDate {
get {
var value = Parameters["modification-date"];
if (IsNullOrWhiteSpace (value))
return null;
var buffer = Encoding.UTF8.GetBytes (value);
DateTimeOffset mtime;
if (!DateUtils.TryParse (buffer, 0, buffer.Length, out mtime))
return null;
return mtime;
}
set {
if (value.HasValue)
Parameters["modification-date"] = DateUtils.FormatDate (value.Value);
else
Parameters.Remove ("modification-date");
}
}
/// <summary>
/// Gets or sets the read-date parameter.
/// </summary>
/// <remarks>
/// Refers to the date and time that the content file was last read on the
/// originating system. This parameter serves little purpose and is typically
/// not used by mail clients.
/// </remarks>
/// <value>The read date.</value>
public DateTimeOffset? ReadDate {
get {
var value = Parameters["read-date"];
if (IsNullOrWhiteSpace (value))
return null;
var buffer = Encoding.UTF8.GetBytes (value);
DateTimeOffset atime;
if (!DateUtils.TryParse (buffer, 0, buffer.Length, out atime))
return null;
return atime;
}
set {
if (value.HasValue)
Parameters["read-date"] = DateUtils.FormatDate (value.Value);
else
Parameters.Remove ("read-date");
}
}
/// <summary>
/// Gets or sets the size parameter.
/// </summary>
/// <remarks>
/// When set, the size parameter typically refers to the original size of the
/// content on disk. This parameter is rarely used by mail clients as it serves
/// little purpose.
/// </remarks>
/// <value>The size.</value>
public long? Size {
get {
var value = Parameters["size"];
if (IsNullOrWhiteSpace (value))
return null;
long size;
if (!long.TryParse (value, out size))
return null;
return size;
}
set {
if (value.HasValue)
Parameters["size"] = value.Value.ToString ();
else
Parameters.Remove ("size");
}
}
internal string Encode (FormatOptions options, Encoding charset)
{
int lineLength = "Content-Disposition:".Length;
var value = new StringBuilder (" ");
value.Append (disposition);
lineLength += value.Length;
Parameters.Encode (options, value, ref lineLength, charset);
value.Append (options.NewLine);
return value.ToString ();
}
/// <summary>
/// Serializes the <see cref="MimeKit.ContentDisposition"/> to a string,
/// optionally encoding the parameters.
/// </summary>
/// <remarks>
/// Creates a string-representation of the <see cref="ContentDisposition"/>,
/// optionally encoding the parameters as they would be encoded for trabsport.
/// </remarks>
/// <returns>The serialized string.</returns>
/// <param name="options">The formatting options.</param>
/// <param name="charset">The charset to be used when encoding the parameter values.</param>
/// <param name="encode">If set to <c>true</c>, the parameter values will be encoded.</param>
/// <exception cref="System.ArgumentNullException">
/// <para><paramref name="options"/> is <c>null</c>.</para>
/// <para>-or-</para>
/// <para><paramref name="charset"/> is <c>null</c>.</para>
/// </exception>
public string ToString (FormatOptions options, Encoding charset, bool encode)
{
if (options == null)
throw new ArgumentNullException ("options");
if (charset == null)
throw new ArgumentNullException ("charset");
var value = new StringBuilder ("Content-Disposition: ");
value.Append (disposition);
if (encode) {
int lineLength = value.Length;
Parameters.Encode (options, value, ref lineLength, charset);
} else {
value.Append (Parameters.ToString ());
}
return value.ToString ();
}
/// <summary>
/// Serializes the <see cref="MimeKit.ContentDisposition"/> to a string,
/// optionally encoding the parameters.
/// </summary>
/// <remarks>
/// Creates a string-representation of the <see cref="ContentDisposition"/>,
/// optionally encoding the parameters as they would be encoded for trabsport.
/// </remarks>
/// <returns>The serialized string.</returns>
/// <param name="charset">The charset to be used when encoding the parameter values.</param>
/// <param name="encode">If set to <c>true</c>, the parameter values will be encoded.</param>
/// <exception cref="System.ArgumentNullException">
/// <paramref name="charset"/> is <c>null</c>.
/// </exception>
public string ToString (Encoding charset, bool encode)
{
return ToString (FormatOptions.Default, charset, encode);
}
/// <summary>
/// Returns a <see cref="System.String"/> that represents the current
/// <see cref="MimeKit.ContentDisposition"/>.
/// </summary>
/// <remarks>
/// Creates a string-representation of the <see cref="ContentDisposition"/>.
/// </remarks>
/// <returns>A <see cref="System.String"/> that represents the current
/// <see cref="MimeKit.ContentDisposition"/>.</returns>
public override string ToString ()
{
return ToString (FormatOptions.Default, Encoding.UTF8, false);
}
internal event EventHandler Changed;
void OnParametersChanged (object sender, EventArgs e)
{
OnChanged ();
}
void OnChanged ()
{
if (Changed != null)
Changed (this, EventArgs.Empty);
}
internal static bool TryParse (ParserOptions options, byte[] text, ref int index, int endIndex, bool throwOnError, out ContentDisposition disposition)
{
string type;
int atom;
disposition = null;
if (!ParseUtils.SkipCommentsAndWhiteSpace (text, ref index, endIndex, throwOnError))
return false;
atom = index;
if (!ParseUtils.SkipAtom (text, ref index, endIndex)) {
if (throwOnError)
throw new ParseException (string.Format ("Invalid atom token at position {0}", atom), atom, index);
return false;
}
type = Encoding.ASCII.GetString (text, atom, index - atom);
if (!ParseUtils.SkipCommentsAndWhiteSpace (text, ref index, endIndex, throwOnError))
return false;
disposition = new ContentDisposition ();
disposition.disposition = type;
if (index >= endIndex)
return true;
if (text[index] != (byte) ';') {
if (throwOnError)
throw new ParseException (string.Format ("Expected ';' at position {0}", index), index, index);
return false;
}
index++;
if (!ParseUtils.SkipCommentsAndWhiteSpace (text, ref index, endIndex, throwOnError))
return false;
if (index >= endIndex)
return true;
ParameterList parameters;
if (!ParameterList.TryParse (options, text, ref index, endIndex, throwOnError, out parameters))
return false;
disposition.Parameters = parameters;
return true;
}
/// <summary>
/// Tries to parse the given input buffer into a new <see cref="MimeKit.ContentDisposition"/> instance.
/// </summary>
/// <remarks>
/// Parses a Content-Disposition value from the supplied buffer starting at the given index
/// and spanning across the specified number of bytes.
/// </remarks>
/// <returns><c>true</c>, if the disposition was successfully parsed, <c>false</c> otherwise.</returns>
/// <param name="options">The parser options.</param>
/// <param name="buffer">The input buffer.</param>
/// <param name="startIndex">The starting index of the input buffer.</param>
/// <param name="length">The number of bytes in the input buffer to parse.</param>
/// <param name="disposition">The parsed disposition.</param>
/// <exception cref="System.ArgumentNullException">
/// <para><paramref name="options"/> is <c>null</c>.</para>
/// <para>-or-</para>
/// <para><paramref name="buffer"/> is <c>null</c>.</para>
/// </exception>
/// <exception cref="System.ArgumentOutOfRangeException">
/// <paramref name="startIndex"/> and <paramref name="length"/> do not specify
/// a valid range in the byte array.
/// </exception>
public static bool TryParse (ParserOptions options, byte[] buffer, int startIndex, int length, out ContentDisposition disposition)
{
ParseUtils.ValidateArguments (options, buffer, startIndex, length);
int index = startIndex;
return TryParse (options, buffer, ref index, startIndex + length, false, out disposition);
}
/// <summary>
/// Tries to parse the given input buffer into a new <see cref="MimeKit.ContentDisposition"/> instance.
/// </summary>
/// <remarks>
/// Parses a Content-Disposition value from the supplied buffer starting at the given index
/// and spanning across the specified number of bytes.
/// </remarks>
/// <returns><c>true</c>, if the disposition was successfully parsed, <c>false</c> otherwise.</returns>
/// <param name="buffer">The input buffer.</param>
/// <param name="startIndex">The starting index of the input buffer.</param>
/// <param name="length">The number of bytes in the input buffer to parse.</param>
/// <param name="disposition">The parsed disposition.</param>
/// <exception cref="System.ArgumentNullException">
/// <paramref name="buffer"/> is <c>null</c>.
/// </exception>
/// <exception cref="System.ArgumentOutOfRangeException">
/// <paramref name="startIndex"/> and <paramref name="length"/> do not specify
/// a valid range in the byte array.
/// </exception>
public static bool TryParse (byte[] buffer, int startIndex, int length, out ContentDisposition disposition)
{
return TryParse (ParserOptions.Default, buffer, startIndex, length, out disposition);
}
/// <summary>
/// Tries to parse the given input buffer into a new <see cref="MimeKit.ContentDisposition"/> instance.
/// </summary>
/// <remarks>
/// Parses a Content-Disposition value from the supplied buffer starting at the specified index.
/// </remarks>
/// <returns><c>true</c>, if the disposition was successfully parsed, <c>false</c> otherwise.</returns>
/// <param name="options">The parser options.</param>
/// <param name="buffer">The input buffer.</param>
/// <param name="startIndex">The starting index of the input buffer.</param>
/// <param name="disposition">The parsed disposition.</param>
/// <exception cref="System.ArgumentNullException">
/// <para><paramref name="options"/> is <c>null</c>.</para>
/// <para>-or-</para>
/// <para><paramref name="buffer"/> is <c>null</c>.</para>
/// </exception>
/// <exception cref="System.ArgumentOutOfRangeException">
/// <paramref name="startIndex"/> is out of range.
/// </exception>
public static bool TryParse (ParserOptions options, byte[] buffer, int startIndex, out ContentDisposition disposition)
{
ParseUtils.ValidateArguments (options, buffer, startIndex);
int index = startIndex;
return TryParse (options, buffer, ref index, buffer.Length, false, out disposition);
}
/// <summary>
/// Tries to parse the given input buffer into a new <see cref="MimeKit.ContentDisposition"/> instance.
/// </summary>
/// <remarks>
/// Parses a Content-Disposition value from the supplied buffer starting at the specified index.
/// </remarks>
/// <returns><c>true</c>, if the disposition was successfully parsed, <c>false</c> otherwise.</returns>
/// <param name="buffer">The input buffer.</param>
/// <param name="startIndex">The starting index of the input buffer.</param>
/// <param name="disposition">The parsed disposition.</param>
/// <exception cref="System.ArgumentNullException">
/// <paramref name="buffer"/> is <c>null</c>.
/// </exception>
/// <exception cref="System.ArgumentOutOfRangeException">
/// <paramref name="startIndex"/> is out of range.
/// </exception>
public static bool TryParse (byte[] buffer, int startIndex, out ContentDisposition disposition)
{
return TryParse (ParserOptions.Default, buffer, startIndex, out disposition);
}
/// <summary>
/// Tries to parse the given input buffer into a new <see cref="MimeKit.ContentDisposition"/> instance.
/// </summary>
/// <remarks>
/// Parses a Content-Disposition value from the specified buffer.
/// </remarks>
/// <returns><c>true</c>, if the disposition was successfully parsed, <c>false</c> otherwise.</returns>
/// <param name="options">The parser options.</param>
/// <param name="buffer">The input buffer.</param>
/// <param name="disposition">The parsed disposition.</param>
/// <exception cref="System.ArgumentNullException">
/// <para><paramref name="options"/> is <c>null</c>.</para>
/// <para>-or-</para>
/// <para><paramref name="buffer"/> is <c>null</c>.</para>
/// </exception>
public static bool TryParse (ParserOptions options, byte[] buffer, out ContentDisposition disposition)
{
ParseUtils.ValidateArguments (options, buffer);
int index = 0;
return TryParse (options, buffer, ref index, buffer.Length, false, out disposition);
}
/// <summary>
/// Tries to parse the given input buffer into a new <see cref="MimeKit.ContentDisposition"/> instance.
/// </summary>
/// <remarks>
/// Parses a Content-Disposition value from the specified buffer.
/// </remarks>
/// <returns><c>true</c>, if the disposition was successfully parsed, <c>false</c> otherwise.</returns>
/// <param name="buffer">The input buffer.</param>
/// <param name="disposition">The parsed disposition.</param>
/// <exception cref="System.ArgumentNullException">
/// <paramref name="buffer"/> is <c>null</c>.
/// </exception>
public static bool TryParse (byte[] buffer, out ContentDisposition disposition)
{
return TryParse (ParserOptions.Default, buffer, out disposition);
}
/// <summary>
/// Tries to parse the given text into a new <see cref="MimeKit.ContentDisposition"/> instance.
/// </summary>
/// <remarks>
/// Parses a Content-Disposition value from the supplied text.
/// </remarks>
/// <returns><c>true</c>, if the disposition was successfully parsed, <c>false</c> otherwise.</returns>
/// <param name="options">The parser options.</param>
/// <param name="text">The text to parse.</param>
/// <param name="disposition">The parsed disposition.</param>
/// <exception cref="System.ArgumentNullException">
/// <para><paramref name="options"/> is <c>null</c>.</para>
/// <para>-or-</para>
/// <para><paramref name="text"/> is <c>null</c>.</para>
/// </exception>
public static bool TryParse (ParserOptions options, string text, out ContentDisposition disposition)
{
ParseUtils.ValidateArguments (options, text);
var buffer = Encoding.UTF8.GetBytes (text);
int index = 0;
return TryParse (ParserOptions.Default, buffer, ref index, buffer.Length, false, out disposition);
}
/// <summary>
/// Tries to parse the given text into a new <see cref="MimeKit.ContentDisposition"/> instance.
/// </summary>
/// <remarks>
/// Parses a Content-Disposition value from the supplied text.
/// </remarks>
/// <returns><c>true</c>, if the disposition was successfully parsed, <c>false</c> otherwise.</returns>
/// <param name="text">The text to parse.</param>
/// <param name="disposition">The parsed disposition.</param>
/// <exception cref="System.ArgumentNullException">
/// <paramref name="text"/> is <c>null</c>.
/// </exception>
public static bool TryParse (string text, out ContentDisposition disposition)
{
return TryParse (ParserOptions.Default, text, out disposition);
}
/// <summary>
/// Parse the specified input buffer into a new instance of the <see cref="MimeKit.ContentDisposition"/> class.
/// </summary>
/// <remarks>
/// Parses a Content-Disposition value from the supplied buffer starting at the given index
/// and spanning across the specified number of bytes.
/// </remarks>
/// <returns>The parsed <see cref="MimeKit.ContentDisposition"/>.</returns>
/// <param name="options">The parser options.</param>
/// <param name="buffer">The input buffer.</param>
/// <param name="startIndex">The start index of the buffer.</param>
/// <param name="length">The length of the buffer.</param>
/// <exception cref="System.ArgumentNullException">
/// <para><paramref name="options"/> is <c>null</c>.</para>
/// <para>-or-</para>
/// <para><paramref name="buffer"/> is <c>null</c>.</para>
/// </exception>
/// <exception cref="System.ArgumentOutOfRangeException">
/// <paramref name="startIndex"/> and <paramref name="length"/> do not specify
/// a valid range in the byte array.
/// </exception>
/// <exception cref="MimeKit.ParseException">
/// The <paramref name="buffer"/> could not be parsed.
/// </exception>
public static ContentDisposition Parse (ParserOptions options, byte[] buffer, int startIndex, int length)
{
ParseUtils.ValidateArguments (options, buffer, startIndex, length);
ContentDisposition disposition;
int index = startIndex;
TryParse (options, buffer, ref index, startIndex + length, true, out disposition);
return disposition;
}
/// <summary>
/// Parse the specified input buffer into a new instance of the <see cref="MimeKit.ContentDisposition"/> class.
/// </summary>
/// <remarks>
/// Parses a Content-Disposition value from the supplied buffer starting at the given index
/// and spanning across the specified number of bytes.
/// </remarks>
/// <returns>The parsed <see cref="MimeKit.ContentDisposition"/>.</returns>
/// <param name="buffer">The input buffer.</param>
/// <param name="startIndex">The start index of the buffer.</param>
/// <param name="length">The length of the buffer.</param>
/// <exception cref="System.ArgumentNullException">
/// <paramref name="buffer"/> is <c>null</c>.
/// </exception>
/// <exception cref="System.ArgumentOutOfRangeException">
/// <paramref name="startIndex"/> and <paramref name="length"/> do not specify
/// a valid range in the byte array.
/// </exception>
/// <exception cref="MimeKit.ParseException">
/// The <paramref name="buffer"/> could not be parsed.
/// </exception>
public static ContentDisposition Parse (byte[] buffer, int startIndex, int length)
{
return Parse (ParserOptions.Default, buffer, startIndex, length);
}
/// <summary>
/// Parse the specified input buffer into a new instance of the <see cref="MimeKit.ContentDisposition"/> class.
/// </summary>
/// <remarks>
/// Parses a Content-Disposition value from the supplied buffer starting at the specified index.
/// </remarks>
/// <returns>The parsed <see cref="MimeKit.ContentDisposition"/>.</returns>
/// <param name="options">The parser options.</param>
/// <param name="buffer">The input buffer.</param>
/// <param name="startIndex">The start index of the buffer.</param>
/// <exception cref="System.ArgumentNullException">
/// <para><paramref name="options"/> is <c>null</c>.</para>
/// <para>-or-</para>
/// <para><paramref name="buffer"/> is <c>null</c>.</para>
/// </exception>
/// <exception cref="System.ArgumentOutOfRangeException">
/// <paramref name="startIndex"/> is out of range.
/// </exception>
/// <exception cref="MimeKit.ParseException">
/// The <paramref name="buffer"/> could not be parsed.
/// </exception>
public static ContentDisposition Parse (ParserOptions options, byte[] buffer, int startIndex)
{
ParseUtils.ValidateArguments (options, buffer, startIndex);
ContentDisposition disposition;
int index = startIndex;
TryParse (options, buffer, ref index, buffer.Length, true, out disposition);
return disposition;
}
/// <summary>
/// Parse the specified input buffer into a new instance of the <see cref="MimeKit.ContentDisposition"/> class.
/// </summary>
/// <remarks>
/// Parses a Content-Disposition value from the supplied buffer starting at the specified index.
/// </remarks>
/// <returns>The parsed <see cref="MimeKit.ContentDisposition"/>.</returns>
/// <param name="buffer">The input buffer.</param>
/// <param name="startIndex">The start index of the buffer.</param>
/// <exception cref="System.ArgumentNullException">
/// <paramref name="buffer"/> is <c>null</c>.
/// </exception>
/// <exception cref="System.ArgumentOutOfRangeException">
/// <paramref name="startIndex"/> is out of range.
/// </exception>
/// <exception cref="MimeKit.ParseException">
/// The <paramref name="buffer"/> could not be parsed.
/// </exception>
public static ContentDisposition Parse (byte[] buffer, int startIndex)
{
return Parse (ParserOptions.Default, buffer, startIndex);
}
/// <summary>
/// Parse the specified input buffer into a new instance of the <see cref="MimeKit.ContentDisposition"/> class.
/// </summary>
/// <remarks>
/// Parses a Content-Disposition value from the supplied buffer.
/// </remarks>
/// <returns>The parsed <see cref="MimeKit.ContentDisposition"/>.</returns>
/// <param name="options">The parser options.</param>
/// <param name="buffer">The input buffer.</param>
/// <exception cref="System.ArgumentNullException">
/// <para><paramref name="options"/> is <c>null</c>.</para>
/// <para>-or-</para>
/// <para><paramref name="buffer"/> is <c>null</c>.</para>
/// </exception>
/// <exception cref="MimeKit.ParseException">
/// The <paramref name="buffer"/> could not be parsed.
/// </exception>
public static ContentDisposition Parse (ParserOptions options, byte[] buffer)
{
ParseUtils.ValidateArguments (options, buffer);
ContentDisposition disposition;
int index = 0;
TryParse (options, buffer, ref index, buffer.Length, true, out disposition);
return disposition;
}
/// <summary>
/// Parse the specified input buffer into a new instance of the <see cref="MimeKit.ContentDisposition"/> class.
/// </summary>
/// <remarks>
/// Parses a Content-Disposition value from the supplied buffer.
/// </remarks>
/// <returns>The parsed <see cref="MimeKit.ContentDisposition"/>.</returns>
/// <param name="buffer">The input buffer.</param>
/// <exception cref="System.ArgumentNullException">
/// <paramref name="buffer"/> is <c>null</c>.
/// </exception>
/// <exception cref="MimeKit.ParseException">
/// The <paramref name="buffer"/> could not be parsed.
/// </exception>
public static ContentDisposition Parse (byte[] buffer)
{
return Parse (ParserOptions.Default, buffer);
}
/// <summary>
/// Parse the specified text into a new instance of the <see cref="MimeKit.ContentDisposition"/> class.
/// </summary>
/// <remarks>
/// Parses a Content-Disposition value from the specified text.
/// </remarks>
/// <returns>The parsed <see cref="MimeKit.ContentDisposition"/>.</returns>
/// <param name="options">The parser options.</param>
/// <param name="text">The input text.</param>
/// <exception cref="System.ArgumentNullException">
/// <para><paramref name="options"/> is <c>null</c>.</para>
/// <para>-or-</para>
/// <para><paramref name="text"/> is <c>null</c>.</para>
/// </exception>
/// <exception cref="MimeKit.ParseException">
/// The <paramref name="text"/> could not be parsed.
/// </exception>
public static ContentDisposition Parse (ParserOptions options, string text)
{
ParseUtils.ValidateArguments (options, text);
var buffer = Encoding.UTF8.GetBytes (text);
ContentDisposition disposition;
int index = 0;
TryParse (options, buffer, ref index, buffer.Length, true, out disposition);
return disposition;
}
/// <summary>
/// Parse the specified text into a new instance of the <see cref="MimeKit.ContentDisposition"/> class.
/// </summary>
/// <remarks>
/// Parses a Content-Disposition value from the specified text.
/// </remarks>
/// <returns>The parsed <see cref="MimeKit.ContentDisposition"/>.</returns>
/// <param name="text">The input text.</param>
/// <exception cref="System.ArgumentNullException">
/// <paramref name="text"/> is <c>null</c>.
/// </exception>
/// <exception cref="MimeKit.ParseException">
/// The <paramref name="text"/> could not be parsed.
/// </exception>
public static ContentDisposition Parse (string text)
{
return Parse (ParserOptions.Default, text);
}
}
}
| |
/*
* Exchange Web Services Managed API
*
* Copyright (c) Microsoft Corporation
* All rights reserved.
*
* MIT License
*
* 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.
*/
namespace Microsoft.Exchange.WebServices.Data
{
using System;
using System.IO;
using System.Net;
using System.Text;
using System.Xml;
/// <summary>
/// WindowsLiveCredentials provides credentials for Windows Live ID authentication.
/// </summary>
internal sealed class WindowsLiveCredentials : WSSecurityBasedCredentials
{
private string windowsLiveId;
private string password;
private Uri windowsLiveUrl;
private bool isAuthenticated;
private bool traceEnabled;
private ITraceListener traceListener = new EwsTraceListener();
// XML-Encryption Namespace.
internal const string XmlEncNamespace = "http://www.w3.org/2001/04/xmlenc#";
// Windows Live SOAP namespace prefix (which is S: instead of soap:)
internal const string WindowsLiveSoapNamespacePrefix = "S";
// XML element names used in RSTR responses from Windows Live
internal const string RequestSecurityTokenResponseCollectionElementName = "RequestSecurityTokenResponseCollection";
internal const string RequestSecurityTokenResponseElementName = "RequestSecurityTokenResponse";
internal const string EncryptedDataElementName = "EncryptedData";
internal const string PpElementName = "pp";
internal const string ReqstatusElementName = "reqstatus";
// The reqstatus we should receive from Windows Live.
internal const string SuccessfulReqstatus = "0x0";
// The default Windows Live URL.
internal static readonly Uri DefaultWindowsLiveUrl = new Uri("https://login.live.com/rst2.srf");
// The reference we use for creating the XML signature.
internal const string XmlSignatureReference = "_EWSTKREF";
/// <summary>
/// Initializes a new instance of the <see cref="WindowsLiveCredentials"/> class.
/// </summary>
/// <param name="windowsLiveId">The user's WindowsLiveId.</param>
/// <param name="password">The password.</param>
public WindowsLiveCredentials(string windowsLiveId, string password)
{
if (windowsLiveId == null)
{
throw new ArgumentNullException("windowsLiveId");
}
if (password == null)
{
throw new ArgumentNullException("password");
}
this.windowsLiveId = windowsLiveId;
this.password = password;
this.windowsLiveUrl = WindowsLiveCredentials.DefaultWindowsLiveUrl;
}
/// <summary>
/// Gets or sets a flag indicating whether tracing is enabled.
/// </summary>
public bool TraceEnabled
{
get
{
return this.traceEnabled;
}
set
{
this.traceEnabled = value;
if (this.traceEnabled && (this.traceListener == null))
{
this.traceListener = new EwsTraceListener();
}
}
}
/// <summary>
/// Gets or sets the trace listener.
/// </summary>
/// <value>The trace listener.</value>
public ITraceListener TraceListener
{
get
{
return this.traceListener;
}
set
{
this.traceListener = value;
this.traceEnabled = value != null;
}
}
/// <summary>
/// Gets or sets the Windows Live Url to use.
/// </summary>
public Uri WindowsLiveUrl
{
get
{
return this.windowsLiveUrl;
}
set
{
// Reset the EWS URL to make sure we go back and re-authenticate next time.
this.EwsUrl = null;
this.IsAuthenticated = false;
this.windowsLiveUrl = value;
}
}
/// <summary>
/// This method is called to apply credentials to a service request before the request is made.
/// </summary>
/// <param name="request">The request.</param>
internal override void PrepareWebRequest(IEwsHttpWebRequest request)
{
if ((this.EwsUrl == null) || (this.EwsUrl != request.RequestUri))
{
this.IsAuthenticated = false;
this.MakeTokenRequestToWindowsLive(request.RequestUri);
this.IsAuthenticated = true;
this.EwsUrl = request.RequestUri;
}
}
/// <summary>
/// Gets or sets a value indicating whether this <see cref="WindowsLiveCredentials"/> has been authenticated.
/// </summary>
/// <value><c>true</c> if authenticated; otherwise, <c>false</c>.</value>
public bool IsAuthenticated
{
get { return this.isAuthenticated; }
internal set { this.isAuthenticated = value; }
}
/// <summary>
/// Function that sends the token request to Windows Live.
/// </summary>
/// <param name="uriForTokenEndpointReference">The Uri to use for the endpoint reference for our token</param>
/// <returns>Response to token request.</returns>
private HttpWebResponse EmitTokenRequest(Uri uriForTokenEndpointReference)
{
const string TokenRequest =
"<?xml version='1.0' encoding='UTF-8'?>" +
"<s:Envelope xmlns:s='http://www.w3.org/2003/05/soap-envelope' " +
" xmlns:wsse='http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd' " +
" xmlns:saml='urn:oasis:names:tc:SAML:1.0:assertion' " +
" xmlns:wsp='http://schemas.xmlsoap.org/ws/2004/09/policy' " +
" xmlns:wsu='http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd' " +
" xmlns:wsa='http://www.w3.org/2005/08/addressing' " +
" xmlns:wssc='http://schemas.xmlsoap.org/ws/2005/02/sc' " +
" xmlns:wst='http://schemas.xmlsoap.org/ws/2005/02/trust' " +
" xmlns:ps='http://schemas.microsoft.com/Passport/SoapServices/PPCRL'>" +
" <s:Header>" +
" <wsa:Action s:mustUnderstand='1'>http://schemas.xmlsoap.org/ws/2005/02/trust/RST/Issue</wsa:Action>" +
" <wsa:To s:mustUnderstand='1'>{0}</wsa:To>" +
" <ps:AuthInfo Id='PPAuthInfo'>" +
" <ps:HostingApp>{{63f179af-8bcd-49a0-a3e5-1154c02df090}}</ps:HostingApp>" + //// NOTE: I generated a new GUID for the EWS API
" <ps:BinaryVersion>5</ps:BinaryVersion>" +
" <ps:UIVersion>1</ps:UIVersion>" +
" <ps:Cookies></ps:Cookies>" +
" <ps:RequestParams>AQAAAAIAAABsYwQAAAAxMDMz</ps:RequestParams>" +
" </ps:AuthInfo>" +
" <wsse:Security>" +
" <wsse:UsernameToken wsu:Id='user'>" +
" <wsse:Username>{1}</wsse:Username>" +
" <wsse:Password>{2}</wsse:Password>" +
" </wsse:UsernameToken>" +
" <wsu:Timestamp Id='Timestamp'>" +
" <wsu:Created>{3}</wsu:Created>" +
" <wsu:Expires>{4}</wsu:Expires>" +
" </wsu:Timestamp>" +
" </wsse:Security>" +
" </s:Header>" +
" <s:Body>" +
" <ps:RequestMultipleSecurityTokens Id='RSTS'>" +
" <wst:RequestSecurityToken Id='RST0'>" +
" <wst:RequestType>http://schemas.xmlsoap.org/ws/2005/02/trust/Issue</wst:RequestType>" +
" <wsp:AppliesTo>" +
" <wsa:EndpointReference>" +
" <wsa:Address>http://Passport.NET/tb</wsa:Address>" +
" </wsa:EndpointReference>" +
" </wsp:AppliesTo>" +
" </wst:RequestSecurityToken>" +
" <wst:RequestSecurityToken Id='RST1'>" +
" <wst:RequestType>http://schemas.xmlsoap.org/ws/2005/02/trust/Issue</wst:RequestType>" +
" <wsp:AppliesTo>" +
" <wsa:EndpointReference>" +
" <wsa:Address>{5}</wsa:Address>" +
" </wsa:EndpointReference>" +
" </wsp:AppliesTo>" +
" <wsp:PolicyReference URI='LBI_FED_SSL'></wsp:PolicyReference>" +
" </wst:RequestSecurityToken>" +
" </ps:RequestMultipleSecurityTokens>" +
" </s:Body>" +
"</s:Envelope>";
// Create a security timestamp valid for 5 minutes to send with the request.
DateTime now = DateTime.UtcNow;
SecurityTimestamp securityTimestamp = new SecurityTimestamp(now, now.AddMinutes(5), "Timestamp");
// Format the request string to send to the server, filling in all the bits.
string requestToSend = String.Format(
TokenRequest,
this.windowsLiveUrl,
this.windowsLiveId,
this.password,
securityTimestamp.GetCreationTimeChars(),
securityTimestamp.GetExpiryTimeChars(),
uriForTokenEndpointReference.ToString());
// Create and send the request.
HttpWebRequest webRequest = (HttpWebRequest) HttpWebRequest.Create(this.windowsLiveUrl);
webRequest.Method = "POST";
webRequest.ContentType = "text/xml; charset=utf-8";
byte[] requestBytes = Encoding.UTF8.GetBytes(requestToSend);
webRequest.ContentLength = requestBytes.Length;
// NOTE: We're not tracing the request to Windows Live here because it has the user name and
// password in it.
using (Stream requestStream = webRequest.GetRequestStream())
{
requestStream.Write(requestBytes, 0, requestBytes.Length);
}
return (HttpWebResponse)webRequest.GetResponse();
}
/// <summary>
/// Traces the response.
/// </summary>
/// <param name="response">The response.</param>
/// <param name="memoryStream">The response content in a MemoryStream.</param>
private void TraceResponse(HttpWebResponse response, MemoryStream memoryStream)
{
EwsUtilities.Assert(
memoryStream != null,
"WindowsLiveCredentials.TraceResponse",
"memoryStream cannot be null");
if (!this.TraceEnabled)
{
return;
}
if (!string.IsNullOrEmpty(response.ContentType) &&
(response.ContentType.StartsWith("text/", StringComparison.OrdinalIgnoreCase) ||
response.ContentType.StartsWith("application/soap", StringComparison.OrdinalIgnoreCase)))
{
this.traceListener.Trace(
"WindowsLiveResponse",
EwsUtilities.FormatLogMessageWithXmlContent("WindowsLiveResponse", memoryStream));
}
else
{
this.traceListener.Trace(
"WindowsLiveResponse",
"Non-textual response");
}
}
private void TraceWebException(WebException e)
{
// If there wasn't a response, there's nothing to trace.
if (e.Response == null)
{
if (this.TraceEnabled)
{
string logMessage = string.Format(
"Exception Received when sending Windows Live token request: {0}",
e);
this.traceListener.Trace("WindowsLiveResponse", logMessage);
}
return;
}
// If tracing is enabled, we read the entire response into a MemoryStream so that we
// can pass it along to the ITraceListener. Then we parse the response from the
// MemoryStream.
if (this.TraceEnabled)
{
using (MemoryStream memoryStream = new MemoryStream())
{
using (Stream responseStream = e.Response.GetResponseStream())
{
// Copy response to in-memory stream and reset position to start.
EwsUtilities.CopyStream(responseStream, memoryStream);
memoryStream.Position = 0;
}
this.TraceResponse((HttpWebResponse) e.Response, memoryStream);
}
}
}
/// <summary>
/// Makes a request to Windows Live to get a token.
/// </summary>
/// <param name="uriForTokenEndpointReference">URL where token is to be used</param>
private void MakeTokenRequestToWindowsLive(Uri uriForTokenEndpointReference)
{
// Post the request to Windows Live and load the response into an EwsXmlReader for
// processing.
HttpWebResponse response;
try
{
response = this.EmitTokenRequest(uriForTokenEndpointReference);
}
catch (WebException e)
{
if (e.Status == WebExceptionStatus.ProtocolError && e.Response != null)
{
this.TraceWebException(e);
}
else
{
if (this.TraceEnabled)
{
string traceString = string.Format(
"Error occurred sending request - status was {0}, exception {1}",
e.Status,
e);
this.traceListener.Trace(
"WindowsLiveCredentials",
traceString);
}
}
throw new ServiceRequestException(string.Format(Strings.ServiceRequestFailed, e.Message), e);
}
try
{
this.ProcessTokenResponse(response);
}
catch (WebException e)
{
if (this.TraceEnabled)
{
string traceString = string.Format(
"Error occurred sending request - status was {0}, exception {1}",
e.Status,
e);
this.traceListener.Trace(
"WindowsLiveCredentials",
traceString);
}
throw new ServiceRequestException(string.Format(Strings.ServiceRequestFailed, e.Message), e);
}
}
/// <summary>
/// Function that parses the SOAP headers from the response to the RST to Windows Live.
/// </summary>
/// <param name="rstResponse">The Windows Live response, positioned at the beginning of the SOAP headers.</param>
private void ReadWindowsLiveRSTResponseHeaders(EwsXmlReader rstResponse)
{
// Read the beginning of the SOAP header, then go looking for the Passport SOAP fault section...
rstResponse.ReadStartElement(
WindowsLiveSoapNamespacePrefix,
XmlElementNames.SOAPHeaderElementName);
// Attempt to read to the psf:pp element - if at the end of the ReadToDescendant call we're at the
// end element for the SOAP headers, we didn't find it.
rstResponse.ReadToDescendant(XmlNamespace.PassportSoapFault, PpElementName);
if (rstResponse.IsEndElement(WindowsLiveSoapNamespacePrefix, XmlElementNames.SOAPHeaderElementName))
{
// We didn't find the psf:pp element - without that, we don't know what happened -
// something went wrong. Trace and throw.
if (this.TraceEnabled)
{
this.traceListener.Trace(
"WindowsLiveResponse",
"Could not find Passport SOAP fault information in Windows Live response");
}
throw new ServiceRequestException(string.Format(Strings.ServiceRequestFailed, PpElementName));
}
// Now that we've found the psf:pp element, look for the 'reqstatus' element under it. If after
// the ReadToDescendant call we're at the end element for the psf:pp element, we didn't find it.
rstResponse.ReadToDescendant(XmlNamespace.PassportSoapFault, ReqstatusElementName);
if (rstResponse.IsEndElement(XmlNamespace.PassportSoapFault, PpElementName))
{
// We didn't find the "reqstatus" element - without that, we don't know what happened -
// something went wrong. Trace and throw.
if (this.TraceEnabled)
{
this.traceListener.Trace(
"WindowsLiveResponse",
"Could not find reqstatus element in Passport SOAP fault information in Windows Live response");
}
throw new ServiceRequestException(string.Format(Strings.ServiceRequestFailed, ReqstatusElementName));
}
// Now that we've found the reqstatus element, get its value.
string reqstatus = rstResponse.ReadElementValue();
// Read to body tag in both success and failure cases,
// since we need to trace the fault response in failure cases
while (!rstResponse.IsEndElement(WindowsLiveSoapNamespacePrefix, XmlElementNames.SOAPHeaderElementName))
{
rstResponse.Read();
}
if (!string.Equals(reqstatus, SuccessfulReqstatus))
{
// Our request status was non-zero - something went wrong. Trace and throw.
if (this.TraceEnabled)
{
string logMessage = string.Format(
"Received status {0} from Windows Live instead of {1}.",
reqstatus,
SuccessfulReqstatus);
this.traceListener.Trace("WindowsLiveResponse", logMessage);
rstResponse.ReadStartElement(
WindowsLiveSoapNamespacePrefix,
XmlElementNames.SOAPBodyElementName);
// Trace Fault Information
this.traceListener.Trace(
"WindowsLiveResponse",
string.Format(
"Windows Live reported Fault : {0}",
rstResponse.ReadInnerXml()));
}
throw new ServiceRequestException(string.Format(Strings.ServiceRequestFailed, ReqstatusElementName + ": " + reqstatus));
}
}
/// <summary>
/// Function that parses the RSTR from Windows Live and pulls out all the important pieces
/// of data from it.
/// </summary>
/// <param name="rstResponse">The RSTR, positioned at the beginning of the SOAP body.</param>
private void ParseWindowsLiveRSTResponseBody(EwsXmlReader rstResponse)
{
// Read the WS-Trust RequestSecurityTokenResponseCollection node.
rstResponse.ReadStartElement(
XmlNamespace.WSTrustFebruary2005,
RequestSecurityTokenResponseCollectionElementName);
// Skip the first token - our interest is in the second token (the service token).
rstResponse.SkipElement(
XmlNamespace.WSTrustFebruary2005,
RequestSecurityTokenResponseElementName);
// Now process the second token.
rstResponse.ReadStartElement(
XmlNamespace.WSTrustFebruary2005,
RequestSecurityTokenResponseElementName);
while (!rstResponse.IsEndElement(
XmlNamespace.WSTrustFebruary2005,
RequestSecurityTokenResponseElementName))
{
// Watch for the EncryptedData element - when we find it, parse out the appropriate bits of data.
//
// Also watch for the "pp" element in the Passport SOAP fault namespace, which indicates that
// something went wrong with the token request. If we find it, trace and throw accordingly.
if (rstResponse.IsStartElement() &&
(rstResponse.LocalName == EncryptedDataElementName) &&
(rstResponse.NamespaceUri == XmlEncNamespace))
{
this.SecurityToken = rstResponse.ReadOuterXml();
}
else if (rstResponse.IsStartElement(XmlNamespace.PassportSoapFault, PpElementName))
{
if (this.TraceEnabled)
{
string logMessage = string.Format(
"Windows Live reported an error retrieving the token - {0}",
rstResponse.ReadOuterXml());
this.traceListener.Trace("WindowsLiveResponse", logMessage);
}
throw new ServiceRequestException(string.Format(Strings.ServiceRequestFailed, EncryptedDataElementName));
}
// Move to the next bit of data...
rstResponse.Read();
}
// If we didn't find the token, throw.
if (this.SecurityToken == null)
{
if (this.TraceEnabled)
{
string logMessage = string.Format(
"Did not find all required parts of the Windows Live response - " +
"Security Token - {0}",
(this.SecurityToken == null) ? "NOT FOUND" : "found");
this.traceListener.Trace("WindowsLiveResponse", logMessage);
}
throw new ServiceRequestException(string.Format(Strings.ServiceRequestFailed, "No security token found."));
}
// Read past the RequestSecurityTokenResponseCollection end element.
rstResponse.Read();
}
/// <summary>
/// Grabs the issued token information out of a response from Windows Live.
/// </summary>
/// <param name="response">The token response</param>
private void ProcessTokenResponse(HttpWebResponse response)
{
// NOTE: We're not tracing responses here because they contain the actual token information
// from Windows Live.
using (Stream responseStream = response.GetResponseStream())
{
// Always start fresh (nulls in all the data we're going to fill in).
this.SecurityToken = null;
EwsXmlReader rstResponse = new EwsXmlReader(responseStream);
rstResponse.Read(XmlNodeType.XmlDeclaration);
rstResponse.ReadStartElement(
WindowsLiveSoapNamespacePrefix,
XmlElementNames.SOAPEnvelopeElementName);
// Process the SOAP headers from the response.
this.ReadWindowsLiveRSTResponseHeaders(rstResponse);
rstResponse.ReadStartElement(
WindowsLiveSoapNamespacePrefix,
XmlElementNames.SOAPBodyElementName);
// Process the SOAP body from the response.
this.ParseWindowsLiveRSTResponseBody(rstResponse);
}
}
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* 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 OpenSimulator Project 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 DEVELOPERS ``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 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.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Threading;
using log4net;
using Nini.Config;
using Nwc.XmlRpc;
using OpenMetaverse;
using Mono.Addins;
using OpenSim.Framework;
using OpenSim.Framework.Servers.HttpServer;
using OpenSim.Framework.Servers;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;
using OpenSim.Services.Interfaces;
using OpenSim.Services.Connectors.Friends;
using OpenSim.Server.Base;
using FriendInfo = OpenSim.Services.Interfaces.FriendInfo;
using PresenceInfo = OpenSim.Services.Interfaces.PresenceInfo;
using GridRegion = OpenSim.Services.Interfaces.GridRegion;
namespace OpenSim.Region.CoreModules.Avatar.Friends
{
[Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "FriendsModule")]
public class FriendsModule : ISharedRegionModule, IFriendsModule
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
protected bool m_Enabled = false;
protected class UserFriendData
{
public UUID PrincipalID;
public FriendInfo[] Friends;
public int Refcount;
public bool IsFriend(string friend)
{
foreach (FriendInfo fi in Friends)
{
if (fi.Friend == friend)
return true;
}
return false;
}
}
protected static readonly FriendInfo[] EMPTY_FRIENDS = new FriendInfo[0];
protected List<Scene> m_Scenes = new List<Scene>();
protected IPresenceService m_PresenceService = null;
protected IFriendsService m_FriendsService = null;
protected FriendsSimConnector m_FriendsSimConnector;
/// <summary>
/// Cache friends lists for users.
/// </summary>
/// <remarks>
/// This is a complex and error-prone thing to do. At the moment, we assume that the efficiency gained in
/// permissions checks outweighs the disadvantages of that complexity.
/// </remarks>
protected Dictionary<UUID, UserFriendData> m_Friends = new Dictionary<UUID, UserFriendData>();
/// <summary>
/// Maintain a record of clients that need to notify about their online status. This only
/// needs to be done on login. Subsequent online/offline friend changes are sent by a different mechanism.
/// </summary>
protected HashSet<UUID> m_NeedsToNotifyStatus = new HashSet<UUID>();
/// <summary>
/// Maintain a record of viewers that need to be sent notifications for friends that are online. This only
/// needs to be done on login. Subsequent online/offline friend changes are sent by a different mechanism.
/// </summary>
protected HashSet<UUID> m_NeedsListOfOnlineFriends = new HashSet<UUID>();
protected IPresenceService PresenceService
{
get
{
if (m_PresenceService == null)
{
if (m_Scenes.Count > 0)
m_PresenceService = m_Scenes[0].RequestModuleInterface<IPresenceService>();
}
return m_PresenceService;
}
}
public IFriendsService FriendsService
{
get
{
if (m_FriendsService == null)
{
if (m_Scenes.Count > 0)
m_FriendsService = m_Scenes[0].RequestModuleInterface<IFriendsService>();
}
return m_FriendsService;
}
}
protected IGridService GridService
{
get { return m_Scenes[0].GridService; }
}
public IUserAccountService UserAccountService
{
get { return m_Scenes[0].UserAccountService; }
}
public IScene Scene
{
get
{
if (m_Scenes.Count > 0)
return m_Scenes[0];
else
return null;
}
}
#region ISharedRegionModule
public void Initialise(IConfigSource config)
{
IConfig moduleConfig = config.Configs["Modules"];
if (moduleConfig != null)
{
string name = moduleConfig.GetString("FriendsModule", "FriendsModule");
if (name == Name)
{
InitModule(config);
m_Enabled = true;
m_log.DebugFormat("[FRIENDS MODULE]: {0} enabled.", Name);
}
}
}
protected virtual void InitModule(IConfigSource config)
{
IConfig friendsConfig = config.Configs["Friends"];
if (friendsConfig != null)
{
int mPort = friendsConfig.GetInt("Port", 0);
string connector = friendsConfig.GetString("Connector", String.Empty);
Object[] args = new Object[] { config };
m_FriendsService = ServerUtils.LoadPlugin<IFriendsService>(connector, args);
m_FriendsSimConnector = new FriendsSimConnector();
// Instantiate the request handler
IHttpServer server = MainServer.GetHttpServer((uint)mPort);
if (server != null)
server.AddStreamHandler(new FriendsRequestHandler(this));
}
if (m_FriendsService == null)
{
m_log.Error("[FRIENDS]: No Connector defined in section Friends, or failed to load, cannot continue");
throw new Exception("Connector load error");
}
}
public void PostInitialise()
{
}
public void Close()
{
}
public virtual void AddRegion(Scene scene)
{
if (!m_Enabled)
return;
// m_log.DebugFormat("[FRIENDS MODULE]: AddRegion on {0}", Name);
m_Scenes.Add(scene);
scene.RegisterModuleInterface<IFriendsModule>(this);
scene.EventManager.OnNewClient += OnNewClient;
scene.EventManager.OnClientClosed += OnClientClosed;
scene.EventManager.OnMakeRootAgent += OnMakeRootAgent;
scene.EventManager.OnClientLogin += OnClientLogin;
}
public virtual void RegionLoaded(Scene scene) {}
public void RemoveRegion(Scene scene)
{
if (!m_Enabled)
return;
m_Scenes.Remove(scene);
}
public virtual string Name
{
get { return "FriendsModule"; }
}
public Type ReplaceableInterface
{
get { return null; }
}
#endregion
public virtual int GetRightsGrantedByFriend(UUID principalID, UUID friendID)
{
FriendInfo[] friends = GetFriendsFromCache(principalID);
FriendInfo finfo = GetFriend(friends, friendID);
if (finfo != null)
{
return finfo.TheirFlags;
}
return 0;
}
private void OnNewClient(IClientAPI client)
{
client.OnInstantMessage += OnInstantMessage;
client.OnApproveFriendRequest += OnApproveFriendRequest;
client.OnDenyFriendRequest += OnDenyFriendRequest;
client.OnTerminateFriendship += RemoveFriendship;
client.OnGrantUserRights += GrantRights;
client.OnFindAgent += FindFriend;
// We need to cache information for child agents as well as root agents so that friend edit/move/delete
// permissions will work across borders where both regions are on different simulators.
//
// Do not do this asynchronously. If we do, then subsequent code can outrace CacheFriends() and
// return misleading results from the still empty friends cache.
// If we absolutely need to do this asynchronously, then a signalling mechanism is needed so that calls
// to GetFriends() will wait until CacheFriends() completes. Locks are insufficient.
CacheFriends(client);
}
/// <summary>
/// Cache the friends list or increment the refcount for the existing friends list.
/// </summary>
/// <param name="client">
/// </param>
/// <returns>
/// Returns true if the list was fetched, false if it wasn't
/// </returns>
protected virtual bool CacheFriends(IClientAPI client)
{
UUID agentID = client.AgentId;
lock (m_Friends)
{
UserFriendData friendsData;
if (m_Friends.TryGetValue(agentID, out friendsData))
{
friendsData.Refcount++;
return false;
}
else
{
friendsData = new UserFriendData();
friendsData.PrincipalID = agentID;
friendsData.Friends = GetFriendsFromService(client);
friendsData.Refcount = 1;
m_Friends[agentID] = friendsData;
return true;
}
}
}
private void OnClientClosed(UUID agentID, Scene scene)
{
ScenePresence sp = scene.GetScenePresence(agentID);
if (sp != null && !sp.IsChildAgent)
{
// do this for root agents closing out
StatusChange(agentID, false);
}
lock (m_Friends)
{
UserFriendData friendsData;
if (m_Friends.TryGetValue(agentID, out friendsData))
{
friendsData.Refcount--;
if (friendsData.Refcount <= 0)
m_Friends.Remove(agentID);
}
}
}
private void OnMakeRootAgent(ScenePresence sp)
{
RecacheFriends(sp.ControllingClient);
lock (m_NeedsToNotifyStatus)
{
if (m_NeedsToNotifyStatus.Remove(sp.UUID))
{
// Inform the friends that this user is online. This can only be done once the client is a Root Agent.
StatusChange(sp.UUID, true);
}
}
}
private void OnClientLogin(IClientAPI client)
{
UUID agentID = client.AgentId;
//m_log.DebugFormat("[XXX]: OnClientLogin!");
// Register that we need to send this user's status to friends. This can only be done
// once the client becomes a Root Agent, because as part of sending out the presence
// we also get back the presence of the HG friends, and we need to send that to the
// client, but that can only be done when the client is a Root Agent.
lock (m_NeedsToNotifyStatus)
m_NeedsToNotifyStatus.Add(agentID);
// Register that we need to send the list of online friends to this user
lock (m_NeedsListOfOnlineFriends)
m_NeedsListOfOnlineFriends.Add(agentID);
}
public virtual bool SendFriendsOnlineIfNeeded(IClientAPI client)
{
UUID agentID = client.AgentId;
// Check if the online friends list is needed
lock (m_NeedsListOfOnlineFriends)
{
if (!m_NeedsListOfOnlineFriends.Remove(agentID))
return false;
}
// Send the friends online
List<UUID> online = GetOnlineFriends(agentID);
if (online.Count > 0)
client.SendAgentOnline(online.ToArray());
// Send outstanding friendship offers
List<string> outstanding = new List<string>();
FriendInfo[] friends = GetFriendsFromCache(agentID);
foreach (FriendInfo fi in friends)
{
if (fi.TheirFlags == -1)
outstanding.Add(fi.Friend);
}
GridInstantMessage im = new GridInstantMessage(client.Scene, UUID.Zero, String.Empty, agentID, (byte)InstantMessageDialog.FriendshipOffered,
"Will you be my friend?", true, Vector3.Zero);
foreach (string fid in outstanding)
{
UUID fromAgentID;
string firstname = "Unknown", lastname = "UserFMSFOIN";
if (!GetAgentInfo(client.Scene.RegionInfo.ScopeID, fid, out fromAgentID, out firstname, out lastname))
{
m_log.DebugFormat("[FRIENDS MODULE]: skipping malformed friend {0}", fid);
continue;
}
im.offline = 0;
im.fromAgentID = fromAgentID.Guid;
im.fromAgentName = firstname + " " + lastname;
im.imSessionID = im.fromAgentID;
im.message = FriendshipMessage(fid);
LocalFriendshipOffered(agentID, im);
}
return true;
}
protected virtual string FriendshipMessage(string friendID)
{
return "Will you be my friend?";
}
protected virtual bool GetAgentInfo(UUID scopeID, string fid, out UUID agentID, out string first, out string last)
{
first = "Unknown"; last = "UserFMGAI";
if (!UUID.TryParse(fid, out agentID))
return false;
UserAccount account = m_Scenes[0].UserAccountService.GetUserAccount(scopeID, agentID);
if (account != null)
{
first = account.FirstName;
last = account.LastName;
}
return true;
}
List<UUID> GetOnlineFriends(UUID userID)
{
List<string> friendList = new List<string>();
FriendInfo[] friends = GetFriendsFromCache(userID);
foreach (FriendInfo fi in friends)
{
if (((fi.TheirFlags & (int)FriendRights.CanSeeOnline) != 0) && (fi.TheirFlags != -1))
friendList.Add(fi.Friend);
}
List<UUID> online = new List<UUID>();
if (friendList.Count > 0)
GetOnlineFriends(userID, friendList, online);
// m_log.DebugFormat(
// "[FRIENDS MODULE]: User {0} has {1} friends online", userID, online.Count);
return online;
}
protected virtual void GetOnlineFriends(UUID userID, List<string> friendList, /*collector*/ List<UUID> online)
{
// m_log.DebugFormat(
// "[FRIENDS MODULE]: Looking for online presence of {0} users for {1}", friendList.Count, userID);
PresenceInfo[] presence = PresenceService.GetAgents(friendList.ToArray());
foreach (PresenceInfo pi in presence)
{
UUID presenceID;
if (UUID.TryParse(pi.UserID, out presenceID))
online.Add(presenceID);
}
}
/// <summary>
/// Find the client for a ID
/// </summary>
public IClientAPI LocateClientObject(UUID agentID)
{
lock (m_Scenes)
{
foreach (Scene scene in m_Scenes)
{
ScenePresence presence = scene.GetScenePresence(agentID);
if (presence != null && !presence.IsChildAgent)
return presence.ControllingClient;
}
}
return null;
}
/// <summary>
/// Caller beware! Call this only for root agents.
/// </summary>
/// <param name="agentID"></param>
/// <param name="online"></param>
private void StatusChange(UUID agentID, bool online)
{
FriendInfo[] friends = GetFriendsFromCache(agentID);
if (friends.Length > 0)
{
List<FriendInfo> friendList = new List<FriendInfo>();
foreach (FriendInfo fi in friends)
{
if (((fi.MyFlags & (int)FriendRights.CanSeeOnline) != 0) && (fi.TheirFlags != -1))
friendList.Add(fi);
}
Util.FireAndForget(
delegate
{
// m_log.DebugFormat(
// "[FRIENDS MODULE]: Notifying {0} friends of {1} of online status {2}",
// friendList.Count, agentID, online);
// Notify about this user status
StatusNotify(friendList, agentID, online);
}, null, "FriendsModule.StatusChange"
);
}
}
protected virtual void StatusNotify(List<FriendInfo> friendList, UUID userID, bool online)
{
//m_log.DebugFormat("[FRIENDS]: Entering StatusNotify for {0}", userID);
List<string> friendStringIds = friendList.ConvertAll<string>(friend => friend.Friend);
List<string> remoteFriendStringIds = new List<string>();
foreach (string friendStringId in friendStringIds)
{
UUID friendUuid;
if (UUID.TryParse(friendStringId, out friendUuid))
{
if (LocalStatusNotification(userID, friendUuid, online))
continue;
remoteFriendStringIds.Add(friendStringId);
}
else
{
m_log.WarnFormat("[FRIENDS]: Error parsing friend ID {0}", friendStringId);
}
}
// We do this regrouping so that we can efficiently send a single request rather than one for each
// friend in what may be a very large friends list.
PresenceInfo[] friendSessions = PresenceService.GetAgents(remoteFriendStringIds.ToArray());
foreach (PresenceInfo friendSession in friendSessions)
{
// let's guard against sessions-gone-bad
if (friendSession != null && friendSession.RegionID != UUID.Zero)
{
//m_log.DebugFormat("[FRIENDS]: Get region {0}", friendSession.RegionID);
GridRegion region = GridService.GetRegionByUUID(m_Scenes[0].RegionInfo.ScopeID, friendSession.RegionID);
if (region != null)
{
m_FriendsSimConnector.StatusNotify(region, userID, friendSession.UserID, online);
}
}
//else
// m_log.DebugFormat("[FRIENDS]: friend session is null or the region is UUID.Zero");
}
}
protected virtual void OnInstantMessage(IClientAPI client, GridInstantMessage im)
{
if ((InstantMessageDialog)im.dialog == InstantMessageDialog.FriendshipOffered)
{
// we got a friendship offer
UUID principalID = new UUID(im.fromAgentID);
UUID friendID = new UUID(im.toAgentID);
m_log.DebugFormat("[FRIENDS]: {0} ({1}) offered friendship to {2} ({3})", principalID, client.FirstName + client.LastName, friendID, im.fromAgentName);
// Check that the friendship doesn't exist yet
FriendInfo[] finfos = GetFriendsFromCache(principalID);
if (finfos != null)
{
FriendInfo f = GetFriend(finfos, friendID);
if (f != null)
{
client.SendAgentAlertMessage("This person is already your friend. Please delete it first if you want to reestablish the friendship.", false);
return;
}
}
// This user wants to be friends with the other user.
// Let's add the relation backwards, in case the other is not online
StoreBackwards(friendID, principalID);
// Now let's ask the other user to be friends with this user
ForwardFriendshipOffer(principalID, friendID, im);
}
}
protected virtual bool ForwardFriendshipOffer(UUID agentID, UUID friendID, GridInstantMessage im)
{
// !!!!!!!! This is a hack so that we don't have to keep state (transactionID/imSessionID)
// We stick this agent's ID as imSession, so that it's directly available on the receiving end
im.imSessionID = im.fromAgentID;
im.fromAgentName = GetFriendshipRequesterName(agentID);
// Try the local sim
if (LocalFriendshipOffered(friendID, im))
return true;
// The prospective friend is not here [as root]. Let's forward.
PresenceInfo[] friendSessions = PresenceService.GetAgents(new string[] { friendID.ToString() });
if (friendSessions != null && friendSessions.Length > 0)
{
PresenceInfo friendSession = friendSessions[0];
if (friendSession != null)
{
GridRegion region = GridService.GetRegionByUUID(m_Scenes[0].RegionInfo.ScopeID, friendSession.RegionID);
m_FriendsSimConnector.FriendshipOffered(region, agentID, friendID, im.message);
return true;
}
}
// If the prospective friend is not online, he'll get the message upon login.
return false;
}
protected virtual string GetFriendshipRequesterName(UUID agentID)
{
UserAccount account = UserAccountService.GetUserAccount(UUID.Zero, agentID);
return (account == null) ? "Unknown" : account.FirstName + " " + account.LastName;
}
protected virtual void OnApproveFriendRequest(IClientAPI client, UUID friendID, List<UUID> callingCardFolders)
{
m_log.DebugFormat("[FRIENDS]: {0} accepted friendship from {1}", client.AgentId, friendID);
AddFriendship(client, friendID);
}
public void AddFriendship(IClientAPI client, UUID friendID)
{
StoreFriendships(client.AgentId, friendID);
ICallingCardModule ccm = client.Scene.RequestModuleInterface<ICallingCardModule>();
if (ccm != null)
{
ccm.CreateCallingCard(client.AgentId, friendID, UUID.Zero);
}
// Update the local cache.
RecacheFriends(client);
//
// Notify the friend
//
// Try Local
if (LocalFriendshipApproved(client.AgentId, client.Name, friendID))
{
client.SendAgentOnline(new UUID[] { friendID });
return;
}
// The friend is not here
PresenceInfo[] friendSessions = PresenceService.GetAgents(new string[] { friendID.ToString() });
if (friendSessions != null && friendSessions.Length > 0)
{
PresenceInfo friendSession = friendSessions[0];
if (friendSession != null)
{
GridRegion region = GridService.GetRegionByUUID(m_Scenes[0].RegionInfo.ScopeID, friendSession.RegionID);
m_FriendsSimConnector.FriendshipApproved(region, client.AgentId, client.Name, friendID);
client.SendAgentOnline(new UUID[] { friendID });
}
}
}
private void OnDenyFriendRequest(IClientAPI client, UUID friendID, List<UUID> callingCardFolders)
{
m_log.DebugFormat("[FRIENDS]: {0} denied friendship to {1}", client.AgentId, friendID);
DeleteFriendship(client.AgentId, friendID);
//
// Notify the friend
//
// Try local
if (LocalFriendshipDenied(client.AgentId, client.Name, friendID))
return;
PresenceInfo[] friendSessions = PresenceService.GetAgents(new string[] { friendID.ToString() });
if (friendSessions != null && friendSessions.Length > 0)
{
PresenceInfo friendSession = friendSessions[0];
if (friendSession != null)
{
GridRegion region = GridService.GetRegionByUUID(m_Scenes[0].RegionInfo.ScopeID, friendSession.RegionID);
if (region != null)
m_FriendsSimConnector.FriendshipDenied(region, client.AgentId, client.Name, friendID);
else
m_log.WarnFormat("[FRIENDS]: Could not find region {0} in locating {1}", friendSession.RegionID, friendID);
}
}
}
public void RemoveFriendship(IClientAPI client, UUID exfriendID)
{
if (!DeleteFriendship(client.AgentId, exfriendID))
client.SendAlertMessage("Unable to terminate friendship on this sim.");
// Update local cache
RecacheFriends(client);
client.SendTerminateFriend(exfriendID);
//
// Notify the friend
//
// Try local
if (LocalFriendshipTerminated(client.AgentId, exfriendID))
return;
PresenceInfo[] friendSessions = PresenceService.GetAgents(new string[] { exfriendID.ToString() });
if (friendSessions != null && friendSessions.Length > 0)
{
PresenceInfo friendSession = friendSessions[0];
if (friendSession != null)
{
GridRegion region = GridService.GetRegionByUUID(m_Scenes[0].RegionInfo.ScopeID, friendSession.RegionID);
m_FriendsSimConnector.FriendshipTerminated(region, client.AgentId, exfriendID);
}
}
}
public void FindFriend(IClientAPI remoteClient,UUID HunterID ,UUID PreyID)
{
UUID requester = remoteClient.AgentId;
if(requester != HunterID) // only allow client agent to be the hunter (?)
return;
FriendInfo[] friends = GetFriendsFromCache(requester);
if (friends.Length == 0)
return;
FriendInfo friend = GetFriend(friends, PreyID);
if (friend == null)
return;
if((friend.TheirFlags & (int)FriendRights.CanSeeOnMap) == 0)
return;
Scene hunterScene = (Scene)remoteClient.Scene;
if(hunterScene == null)
return;
// check local
ScenePresence sp;
double px;
double py;
if(hunterScene.TryGetScenePresence(PreyID, out sp))
{
if(sp == null)
return;
px = hunterScene.RegionInfo.WorldLocX + sp.AbsolutePosition.X;
py = hunterScene.RegionInfo.WorldLocY + sp.AbsolutePosition.Y;
remoteClient.SendFindAgent(HunterID, PreyID, px, py);
return;
}
PresenceInfo[] friendSessions = PresenceService.GetAgents(new string[] { PreyID.ToString() });
if (friendSessions == null || friendSessions.Length == 0)
return;
PresenceInfo friendSession = friendSessions[0];
if (friendSession == null)
return;
GridRegion region = GridService.GetRegionByUUID(hunterScene.RegionInfo.ScopeID, friendSession.RegionID);
if(region == null)
return;
// we don't have presence location so point to a standard region center for now
px = region.RegionLocX + 128.0;
py = region.RegionLocY + 128.0;
remoteClient.SendFindAgent(HunterID, PreyID, px, py);
}
public void GrantRights(IClientAPI remoteClient, UUID friendID, int rights)
{
UUID requester = remoteClient.AgentId;
m_log.DebugFormat(
"[FRIENDS MODULE]: User {0} changing rights to {1} for friend {2}",
requester, rights, friendID);
FriendInfo[] friends = GetFriendsFromCache(requester);
if (friends.Length == 0)
{
return;
}
// Let's find the friend in this user's friend list
FriendInfo friend = GetFriend(friends, friendID);
if (friend != null) // Found it
{
// Store it on service
if (!StoreRights(requester, friendID, rights))
{
remoteClient.SendAlertMessage("Unable to grant rights.");
return;
}
// Store it in the local cache
int myFlags = friend.MyFlags;
friend.MyFlags = rights;
// Always send this back to the original client
remoteClient.SendChangeUserRights(requester, friendID, rights);
//
// Notify the friend
//
// Try local
if (LocalGrantRights(requester, friendID, myFlags, rights))
return;
PresenceInfo[] friendSessions = PresenceService.GetAgents(new string[] { friendID.ToString() });
if (friendSessions != null && friendSessions.Length > 0)
{
PresenceInfo friendSession = friendSessions[0];
if (friendSession != null)
{
GridRegion region = GridService.GetRegionByUUID(m_Scenes[0].RegionInfo.ScopeID, friendSession.RegionID);
// TODO: You might want to send the delta to save the lookup
// on the other end!!
m_FriendsSimConnector.GrantRights(region, requester, friendID, myFlags, rights);
}
}
}
else
{
m_log.DebugFormat("[FRIENDS MODULE]: friend {0} not found for {1}", friendID, requester);
}
}
protected virtual FriendInfo GetFriend(FriendInfo[] friends, UUID friendID)
{
foreach (FriendInfo fi in friends)
{
if (fi.Friend == friendID.ToString())
return fi;
}
return null;
}
#region Local
public virtual bool LocalFriendshipOffered(UUID toID, GridInstantMessage im)
{
IClientAPI friendClient = LocateClientObject(toID);
if (friendClient != null)
{
// the prospective friend in this sim as root agent
friendClient.SendInstantMessage(im);
// we're done
return true;
}
return false;
}
public bool LocalFriendshipApproved(UUID userID, string userName, UUID friendID)
{
IClientAPI friendClient = LocateClientObject(friendID);
if (friendClient != null)
{
// the prospective friend in this sim as root agent
GridInstantMessage im = new GridInstantMessage(Scene, userID, userName, friendID,
(byte)OpenMetaverse.InstantMessageDialog.FriendshipAccepted, userID.ToString(), false, Vector3.Zero);
friendClient.SendInstantMessage(im);
ICallingCardModule ccm = friendClient.Scene.RequestModuleInterface<ICallingCardModule>();
if (ccm != null)
{
ccm.CreateCallingCard(friendID, userID, UUID.Zero);
}
// Update the local cache
RecacheFriends(friendClient);
// we're done
return true;
}
return false;
}
public bool LocalFriendshipDenied(UUID userID, string userName, UUID friendID)
{
IClientAPI friendClient = LocateClientObject(friendID);
if (friendClient != null)
{
// the prospective friend in this sim as root agent
GridInstantMessage im = new GridInstantMessage(Scene, userID, userName, friendID,
(byte)OpenMetaverse.InstantMessageDialog.FriendshipDeclined, userID.ToString(), false, Vector3.Zero);
friendClient.SendInstantMessage(im);
// we're done
return true;
}
return false;
}
public bool LocalFriendshipTerminated(UUID userID, UUID exfriendID)
{
IClientAPI friendClient = LocateClientObject(exfriendID);
if (friendClient != null)
{
// the friend in this sim as root agent
friendClient.SendTerminateFriend(userID);
// update local cache
RecacheFriends(friendClient);
// we're done
return true;
}
return false;
}
public bool LocalGrantRights(UUID userID, UUID friendID, int oldRights, int newRights)
{
IClientAPI friendClient = LocateClientObject(friendID);
if (friendClient != null)
{
int changedRights = newRights ^ oldRights;
bool onlineBitChanged = (changedRights & (int)FriendRights.CanSeeOnline) != 0;
if (onlineBitChanged)
{
if ((newRights & (int)FriendRights.CanSeeOnline) == 1)
friendClient.SendAgentOnline(new UUID[] { userID });
else
friendClient.SendAgentOffline(new UUID[] { userID });
}
if(changedRights != 0)
friendClient.SendChangeUserRights(userID, friendID, newRights);
// Update local cache
UpdateLocalCache(userID, friendID, newRights);
return true;
}
return false;
}
public bool LocalStatusNotification(UUID userID, UUID friendID, bool online)
{
//m_log.DebugFormat("[FRIENDS]: Local Status Notify {0} that user {1} is {2}", friendID, userID, online);
IClientAPI friendClient = LocateClientObject(friendID);
if (friendClient != null)
{
// the friend in this sim as root agent
if (online)
friendClient.SendAgentOnline(new UUID[] { userID });
else
friendClient.SendAgentOffline(new UUID[] { userID });
// we're done
return true;
}
return false;
}
#endregion
#region Get / Set friends in several flavours
public FriendInfo[] GetFriendsFromCache(UUID userID)
{
UserFriendData friendsData;
lock (m_Friends)
{
if (m_Friends.TryGetValue(userID, out friendsData))
return friendsData.Friends;
}
return EMPTY_FRIENDS;
}
/// <summary>
/// Update local cache only
/// </summary>
/// <param name="userID"></param>
/// <param name="friendID"></param>
/// <param name="rights"></param>
protected void UpdateLocalCache(UUID userID, UUID friendID, int rights)
{
// Update local cache
lock (m_Friends)
{
FriendInfo[] friends = GetFriendsFromCache(friendID);
if(friends != EMPTY_FRIENDS)
{
FriendInfo finfo = GetFriend(friends, userID);
if(finfo!= null)
finfo.TheirFlags = rights;
}
}
}
public virtual FriendInfo[] GetFriendsFromService(IClientAPI client)
{
return FriendsService.GetFriends(client.AgentId);
}
protected void RecacheFriends(IClientAPI client)
{
// FIXME: Ideally, we want to avoid doing this here since it sits the EventManager.OnMakeRootAgent event
// is on the critical path for transferring an avatar from one region to another.
UUID agentID = client.AgentId;
lock (m_Friends)
{
UserFriendData friendsData;
if (m_Friends.TryGetValue(agentID, out friendsData))
friendsData.Friends = GetFriendsFromService(client);
}
}
public bool AreFriendsCached(UUID userID)
{
lock (m_Friends)
return m_Friends.ContainsKey(userID);
}
protected virtual bool StoreRights(UUID agentID, UUID friendID, int rights)
{
FriendsService.StoreFriend(agentID.ToString(), friendID.ToString(), rights);
return true;
}
protected virtual void StoreBackwards(UUID friendID, UUID agentID)
{
FriendsService.StoreFriend(friendID.ToString(), agentID.ToString(), 0);
}
protected virtual void StoreFriendships(UUID agentID, UUID friendID)
{
FriendsService.StoreFriend(agentID.ToString(), friendID.ToString(), (int)FriendRights.CanSeeOnline);
FriendsService.StoreFriend(friendID.ToString(), agentID.ToString(), (int)FriendRights.CanSeeOnline);
}
protected virtual bool DeleteFriendship(UUID agentID, UUID exfriendID)
{
FriendsService.Delete(agentID, exfriendID.ToString());
FriendsService.Delete(exfriendID, agentID.ToString());
return true;
}
#endregion
}
}
| |
/*
* Copyright (c) InWorldz Halcyon Developers
* Copyright (c) Contributors, http://opensimulator.org/
*
* 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 OpenSimulator Project 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 DEVELOPERS ``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 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.Collections.Generic;
using System.Reflection;
using log4net;
using Mono.Addins;
using Nini.Config;
using OpenSim;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;
namespace OpenSim.ApplicationPlugins.RegionModulesController
{
public class RegionModulesControllerPlugin : IRegionModulesController,
IApplicationPlugin
{
// Logger
private static readonly ILog m_log =
LogManager.GetLogger(
MethodBase.GetCurrentMethod().DeclaringType);
// Config access
private OpenSimBase m_openSim;
// Our name
private string m_name;
// Internal lists to collect information about modules present
private List<TypeExtensionNode> m_nonSharedModules =
new List<TypeExtensionNode>();
private List<TypeExtensionNode> m_sharedModules =
new List<TypeExtensionNode>();
// List of shared module instances, for adding to Scenes
private List<ISharedRegionModule> m_sharedInstances =
new List<ISharedRegionModule>();
#region IApplicationPlugin implementation
public void Initialize (OpenSimBase openSim)
{
m_openSim = openSim;
m_openSim.ApplicationRegistry.RegisterInterface<IRegionModulesController>(this);
m_log.DebugFormat("[REGIONMODULES]: Initializing...");
// Who we are
string id = AddinManager.CurrentAddin.Id;
// Make friendly name
int pos = id.LastIndexOf(".");
if (pos == -1)
m_name = id;
else
m_name = id.Substring(pos + 1);
// The [Modules] section in the ini file
IConfig modulesConfig =
m_openSim.ConfigSource.Source.Configs["Modules"];
if (modulesConfig == null)
modulesConfig = m_openSim.ConfigSource.Source.AddConfig("Modules");
// Scan modules and load all that aren't disabled
foreach (TypeExtensionNode node in
AddinManager.GetExtensionNodes("/OpenSim/RegionModules"))
{
if (typeof(ISharedRegionModule).IsAssignableFrom(node.Type))
{
if (CheckModuleEnabled(node, modulesConfig))
{
m_log.DebugFormat("[REGIONMODULES]: Found shared region module {0}, class {1}", node.Id, node.Type);
m_sharedModules.Add(node);
}
}
else if (typeof(INonSharedRegionModule).IsAssignableFrom(node.Type))
{
if (CheckModuleEnabled(node, modulesConfig))
{
m_log.DebugFormat("[REGIONMODULES]: Found non-shared region module {0}, class {1}", node.Id, node.Type);
m_nonSharedModules.Add(node);
}
}
else
{
m_log.DebugFormat("[REGIONMODULES]: Found unknown type of module {0}, class {1}", node.Id, node.Type);
}
}
// Load and init the module. We try a constructor with a port
// if a port was given, fall back to one without if there is
// no port or the more specific constructor fails.
// This will be removed, so that any module capable of using a port
// must provide a constructor with a port in the future.
// For now, we do this so migration is easy.
//
foreach (TypeExtensionNode node in m_sharedModules)
{
Object[] ctorArgs = new Object[] { (uint)0 };
// Read the config again
string moduleString =
modulesConfig.GetString("Setup_" + node.Id, String.Empty);
// Get the port number, if there is one
if (!String.IsNullOrEmpty(moduleString))
{
// Get the port number from the string
string[] moduleParts = moduleString.Split(new char[] { '/' },
2);
if (moduleParts.Length > 1)
ctorArgs[0] = Convert.ToUInt32(moduleParts[0]);
}
// Try loading and initilaizing the module, using the
// port if appropriate
ISharedRegionModule module = null;
try
{
module = (ISharedRegionModule)Activator.CreateInstance(
node.Type, ctorArgs);
}
catch
{
module = (ISharedRegionModule)Activator.CreateInstance(
node.Type);
}
// OK, we're up and running
m_sharedInstances.Add(module);
module.Initialize(m_openSim.ConfigSource.Source);
}
}
public void PostInitialize()
{
m_log.DebugFormat("[REGIONMODULES]: PostInitializing...");
// Immediately run PostInitialize on shared modules
foreach (ISharedRegionModule module in m_sharedInstances)
{
module.PostInitialize();
}
}
#endregion
#region IPlugin implementation
// We don't do that here
//
public void Initialize ()
{
throw new System.NotImplementedException();
}
#endregion
#region IDisposable implementation
// Cleanup
//
public void Dispose ()
{
// We expect that all regions have been removed already
while (m_sharedInstances.Count > 0)
{
m_sharedInstances[0].Close();
m_sharedInstances.RemoveAt(0);
}
m_sharedModules.Clear();
m_nonSharedModules.Clear();
}
#endregion
public string Version
{
get
{
return AddinManager.CurrentAddin.Version;
}
}
public string Name
{
get
{
return m_name;
}
}
#region IRegionModulesController implementation
/// <summary>
/// Check that the given module is no disabled in the [Modules] section of the config files.
/// </summary>
/// <param name="node"></param>
/// <param name="modulesConfig">The config section</param>
/// <returns>true if the module is enabled, false if it is disabled</returns>
protected bool CheckModuleEnabled(TypeExtensionNode node, IConfig modulesConfig)
{
// Get the config string
string moduleString =
modulesConfig.GetString("Setup_" + node.Id, String.Empty);
// We have a selector
if (!String.IsNullOrEmpty(moduleString))
{
// Allow disabling modules even if they don't have
// support for it
if (moduleString == "disabled")
return false;
// Split off port, if present
string[] moduleParts = moduleString.Split(new char[] { '/' }, 2);
// Format is [port/][class]
string className = moduleParts[0];
if (moduleParts.Length > 1)
className = moduleParts[1];
// Match the class name if given
if (!(String.IsNullOrEmpty(className) ||
node.Type.ToString() == className))
return false;
}
return true;
}
// The root of all evil.
// This is where we handle adding the modules to scenes when they
// load. This means that here we deal with replaceable interfaces,
// nonshared modules, etc.
//
public void AddRegionToModules (Scene scene)
{
Dictionary<Type, ISharedRegionModule> deferredSharedModules =
new Dictionary<Type, ISharedRegionModule>();
Dictionary<Type, INonSharedRegionModule> deferredNonSharedModules =
new Dictionary<Type, INonSharedRegionModule>();
// We need this to see if a module has already been loaded and
// has defined a replaceable interface. It's a generic call,
// so this can't be used directly. It will be used later
Type s = scene.GetType();
MethodInfo mi = s.GetMethod("RequestModuleInterface");
// This will hold the shared modules we actually load
List<ISharedRegionModule> sharedlist =
new List<ISharedRegionModule>();
// Iterate over the shared modules that have been loaded
// Add them to the new Scene
foreach (ISharedRegionModule module in m_sharedInstances)
{
// Here is where we check if a replaceable interface
// is defined. If it is, the module is checked against
// the interfaces already defined. If the interface is
// defined, we simply skip the module. Else, if the module
// defines a replaceable interface, we add it to the deferred
// list.
Type replaceableInterface = module.ReplaceableInterface;
if (replaceableInterface != null)
{
MethodInfo mii = mi.MakeGenericMethod(replaceableInterface);
if (mii.Invoke(scene, new object[0]) != null)
{
m_log.DebugFormat("[REGIONMODULE]: Not loading {0} because another module has registered {1}", module.Name, replaceableInterface.ToString());
continue;
}
deferredSharedModules[replaceableInterface] = module;
m_log.DebugFormat("[REGIONMODULE]: Deferred load of {0}", module.Name);
continue;
}
m_log.DebugFormat("[REGIONMODULE]: Adding scene {0} to shared module {1}",
scene.RegionInfo.RegionName, module.Name);
module.AddRegion(scene);
scene.AddRegionModule(module.Name, module);
sharedlist.Add(module);
}
IConfig modulesConfig =
m_openSim.ConfigSource.Source.Configs["Modules"];
// Scan for, and load, nonshared modules
List<INonSharedRegionModule> list = new List<INonSharedRegionModule>();
foreach (TypeExtensionNode node in m_nonSharedModules)
{
Object[] ctorArgs = new Object[] {0};
// Read the config
string moduleString =
modulesConfig.GetString("Setup_" + node.Id, String.Empty);
// Get the port number, if there is one
if (!String.IsNullOrEmpty(moduleString))
{
// Get the port number from the string
string[] moduleParts = moduleString.Split(new char[] {'/'},
2);
if (moduleParts.Length > 1)
ctorArgs[0] = Convert.ToUInt32(moduleParts[0]);
}
// Actually load it
INonSharedRegionModule module = null;
Type[] ctorParamTypes = new Type[ctorArgs.Length];
for (int i = 0; i < ctorParamTypes.Length; i++)
ctorParamTypes[i] = ctorArgs[i].GetType();
if (node.Type.GetConstructor(ctorParamTypes) != null)
module = (INonSharedRegionModule)Activator.CreateInstance(node.Type, ctorArgs);
else
module = (INonSharedRegionModule)Activator.CreateInstance(node.Type);
// Check for replaceable interfaces
Type replaceableInterface = module.ReplaceableInterface;
if (replaceableInterface != null)
{
MethodInfo mii = mi.MakeGenericMethod(replaceableInterface);
if (mii.Invoke(scene, new object[0]) != null)
{
m_log.DebugFormat("[REGIONMODULE]: Not loading {0} because another module has registered {1}", module.Name, replaceableInterface.ToString());
continue;
}
deferredNonSharedModules[replaceableInterface] = module;
m_log.DebugFormat("[REGIONMODULE]: Deferred load of {0}", module.Name);
continue;
}
m_log.DebugFormat("[REGIONMODULE]: Adding scene {0} to non-shared module {1}",
scene.RegionInfo.RegionName, module.Name);
// Initialize the module
module.Initialize(m_openSim.ConfigSource.Source);
list.Add(module);
}
// Now add the modules that we found to the scene. If a module
// wishes to override a replaceable interface, it needs to
// register it in Initialize, so that the deferred module
// won't load.
foreach (INonSharedRegionModule module in list)
{
module.AddRegion(scene);
scene.AddRegionModule(module.Name, module);
}
// Now all modules without a replaceable base interface are loaded
// Replaceable modules have either been skipped, or omitted.
// Now scan the deferred modules here
foreach (ISharedRegionModule module in deferredSharedModules.Values)
{
// Determine if the interface has been replaced
Type replaceableInterface = module.ReplaceableInterface;
MethodInfo mii = mi.MakeGenericMethod(replaceableInterface);
if (mii.Invoke(scene, new object[0]) != null)
{
m_log.DebugFormat("[REGIONMODULE]: Not loading {0} because another module has registered {1}", module.Name, replaceableInterface.ToString());
continue;
}
m_log.DebugFormat("[REGIONMODULE]: Adding scene {0} to shared module {1} (deferred)",
scene.RegionInfo.RegionName, module.Name);
// Not replaced, load the module
module.AddRegion(scene);
scene.AddRegionModule(module.Name, module);
sharedlist.Add(module);
}
// Same thing for nonshared modules, load them unless overridden
List<INonSharedRegionModule> deferredlist =
new List<INonSharedRegionModule>();
foreach (INonSharedRegionModule module in deferredNonSharedModules.Values)
{
// Check interface override
Type replaceableInterface = module.ReplaceableInterface;
if (replaceableInterface != null)
{
MethodInfo mii = mi.MakeGenericMethod(replaceableInterface);
if (mii.Invoke(scene, new object[0]) != null)
{
m_log.DebugFormat("[REGIONMODULE]: Not loading {0} because another module has registered {1}", module.Name, replaceableInterface.ToString());
continue;
}
}
m_log.DebugFormat("[REGIONMODULE]: Adding scene {0} to non-shared module {1} (deferred)",
scene.RegionInfo.RegionName, module.Name);
module.Initialize(m_openSim.ConfigSource.Source);
list.Add(module);
deferredlist.Add(module);
}
// Finally, load valid deferred modules
foreach (INonSharedRegionModule module in deferredlist)
{
module.AddRegion(scene);
scene.AddRegionModule(module.Name, module);
}
// This is needed for all module types. Modules will register
// Interfaces with scene in AddScene, and will also need a means
// to access interfaces registered by other modules. Without
// this extra method, a module attempting to use another modules's
// interface would be successful only depending on load order,
// which can't be depended upon, or modules would need to resort
// to ugly kludges to attempt to request interfaces when needed
// and unneccessary caching logic repeated in all modules.
// The extra function stub is just that much cleaner
//
foreach (ISharedRegionModule module in sharedlist)
{
module.RegionLoaded(scene);
}
foreach (INonSharedRegionModule module in list)
{
module.RegionLoaded(scene);
}
}
public void RemoveRegionFromModules (Scene scene)
{
foreach (IRegionModuleBase module in scene.RegionModules.Values)
{
m_log.DebugFormat("[REGIONMODULE]: Removing scene {0} from module {1}",
scene.RegionInfo.RegionName, module.Name);
module.RemoveRegion(scene);
if (module is INonSharedRegionModule)
{
// as we were the only user, this instance has to die
module.Close();
}
}
scene.RegionModules.Clear();
}
#endregion
}
}
| |
/// This code was generated by
/// \ / _ _ _| _ _
/// | (_)\/(_)(_|\/| |(/_ v1.0.0
/// / /
using NSubstitute;
using NSubstitute.ExceptionExtensions;
using NUnit.Framework;
using System;
using System.Collections.Generic;
using Twilio.Clients;
using Twilio.Converters;
using Twilio.Exceptions;
using Twilio.Http;
using Twilio.Rest.Serverless.V1.Service;
namespace Twilio.Tests.Rest.Serverless.V1.Service
{
[TestFixture]
public class FunctionTest : TwilioTest
{
[Test]
public void TestReadRequest()
{
var twilioRestClient = Substitute.For<ITwilioRestClient>();
var request = new Request(
HttpMethod.Get,
Twilio.Rest.Domain.Serverless,
"/v1/Services/ZSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Functions",
""
);
twilioRestClient.Request(request).Throws(new ApiException("Server Error, no content"));
try
{
FunctionResource.Read("ZSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", client: twilioRestClient);
Assert.Fail("Expected TwilioException to be thrown for 500");
}
catch (ApiException) {}
twilioRestClient.Received().Request(request);
}
[Test]
public void TestReadEmptyResponse()
{
var twilioRestClient = Substitute.For<ITwilioRestClient>();
twilioRestClient.AccountSid.Returns("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX");
twilioRestClient.Request(Arg.Any<Request>())
.Returns(new Response(
System.Net.HttpStatusCode.OK,
"{\"functions\": [],\"meta\": {\"first_page_url\": \"https://serverless.twilio.com/v1/Services/ZS00000000000000000000000000000000/Functions?PageSize=50&Page=0\",\"key\": \"functions\",\"next_page_url\": null,\"page\": 0,\"page_size\": 50,\"previous_page_url\": null,\"url\": \"https://serverless.twilio.com/v1/Services/ZS00000000000000000000000000000000/Functions?PageSize=50&Page=0\"}}"
));
var response = FunctionResource.Read("ZSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", client: twilioRestClient);
Assert.NotNull(response);
}
[Test]
public void TestFetchRequest()
{
var twilioRestClient = Substitute.For<ITwilioRestClient>();
var request = new Request(
HttpMethod.Get,
Twilio.Rest.Domain.Serverless,
"/v1/Services/ZSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Functions/ZHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
""
);
twilioRestClient.Request(request).Throws(new ApiException("Server Error, no content"));
try
{
FunctionResource.Fetch("ZSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", "ZHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", client: twilioRestClient);
Assert.Fail("Expected TwilioException to be thrown for 500");
}
catch (ApiException) {}
twilioRestClient.Received().Request(request);
}
[Test]
public void TestFetchResponse()
{
var twilioRestClient = Substitute.For<ITwilioRestClient>();
twilioRestClient.AccountSid.Returns("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX");
twilioRestClient.Request(Arg.Any<Request>())
.Returns(new Response(
System.Net.HttpStatusCode.OK,
"{\"sid\": \"ZH00000000000000000000000000000000\",\"account_sid\": \"ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"service_sid\": \"ZS00000000000000000000000000000000\",\"friendly_name\": \"test-function\",\"date_created\": \"2018-11-10T20:00:00Z\",\"date_updated\": \"2018-11-10T20:00:00Z\",\"url\": \"https://serverless.twilio.com/v1/Services/ZS00000000000000000000000000000000/Functions/ZH00000000000000000000000000000000\",\"links\": {\"function_versions\": \"https://serverless.twilio.com/v1/Services/ZS00000000000000000000000000000000/Functions/ZH00000000000000000000000000000000/Versions\"}}"
));
var response = FunctionResource.Fetch("ZSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", "ZHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", client: twilioRestClient);
Assert.NotNull(response);
}
[Test]
public void TestDeleteRequest()
{
var twilioRestClient = Substitute.For<ITwilioRestClient>();
var request = new Request(
HttpMethod.Delete,
Twilio.Rest.Domain.Serverless,
"/v1/Services/ZSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Functions/ZHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
""
);
twilioRestClient.Request(request).Throws(new ApiException("Server Error, no content"));
try
{
FunctionResource.Delete("ZSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", "ZHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", client: twilioRestClient);
Assert.Fail("Expected TwilioException to be thrown for 500");
}
catch (ApiException) {}
twilioRestClient.Received().Request(request);
}
[Test]
public void TestDeleteResponse()
{
var twilioRestClient = Substitute.For<ITwilioRestClient>();
twilioRestClient.AccountSid.Returns("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX");
twilioRestClient.Request(Arg.Any<Request>())
.Returns(new Response(
System.Net.HttpStatusCode.NoContent,
"null"
));
var response = FunctionResource.Delete("ZSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", "ZHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", client: twilioRestClient);
Assert.NotNull(response);
}
[Test]
public void TestCreateRequest()
{
var twilioRestClient = Substitute.For<ITwilioRestClient>();
var request = new Request(
HttpMethod.Post,
Twilio.Rest.Domain.Serverless,
"/v1/Services/ZSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Functions",
""
);
request.AddPostParam("FriendlyName", Serialize("friendly_name"));
twilioRestClient.Request(request).Throws(new ApiException("Server Error, no content"));
try
{
FunctionResource.Create("ZSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", "friendly_name", client: twilioRestClient);
Assert.Fail("Expected TwilioException to be thrown for 500");
}
catch (ApiException) {}
twilioRestClient.Received().Request(request);
}
[Test]
public void TestCreateResponse()
{
var twilioRestClient = Substitute.For<ITwilioRestClient>();
twilioRestClient.AccountSid.Returns("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX");
twilioRestClient.Request(Arg.Any<Request>())
.Returns(new Response(
System.Net.HttpStatusCode.Created,
"{\"sid\": \"ZH00000000000000000000000000000000\",\"account_sid\": \"ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"service_sid\": \"ZS00000000000000000000000000000000\",\"friendly_name\": \"function-friendly\",\"date_created\": \"2018-11-10T20:00:00Z\",\"date_updated\": \"2018-11-10T20:00:00Z\",\"url\": \"https://serverless.twilio.com/v1/Services/ZS00000000000000000000000000000000/Functions/ZH00000000000000000000000000000000\",\"links\": {\"function_versions\": \"https://serverless.twilio.com/v1/Services/ZS00000000000000000000000000000000/Functions/ZH00000000000000000000000000000000/Versions\"}}"
));
var response = FunctionResource.Create("ZSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", "friendly_name", client: twilioRestClient);
Assert.NotNull(response);
}
[Test]
public void TestUpdateRequest()
{
var twilioRestClient = Substitute.For<ITwilioRestClient>();
var request = new Request(
HttpMethod.Post,
Twilio.Rest.Domain.Serverless,
"/v1/Services/ZSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Functions/ZHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
""
);
request.AddPostParam("FriendlyName", Serialize("friendly_name"));
twilioRestClient.Request(request).Throws(new ApiException("Server Error, no content"));
try
{
FunctionResource.Update("ZSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", "ZHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", "friendly_name", client: twilioRestClient);
Assert.Fail("Expected TwilioException to be thrown for 500");
}
catch (ApiException) {}
twilioRestClient.Received().Request(request);
}
[Test]
public void TestUpdateResponse()
{
var twilioRestClient = Substitute.For<ITwilioRestClient>();
twilioRestClient.AccountSid.Returns("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX");
twilioRestClient.Request(Arg.Any<Request>())
.Returns(new Response(
System.Net.HttpStatusCode.OK,
"{\"sid\": \"ZH00000000000000000000000000000000\",\"account_sid\": \"ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"service_sid\": \"ZS00000000000000000000000000000000\",\"friendly_name\": \"function-friendly-update\",\"date_created\": \"2018-11-10T20:00:00Z\",\"date_updated\": \"2018-11-10T20:00:00Z\",\"url\": \"https://serverless.twilio.com/v1/Services/ZS00000000000000000000000000000000/Functions/ZH00000000000000000000000000000000\",\"links\": {\"function_versions\": \"https://serverless.twilio.com/v1/Services/ZS00000000000000000000000000000000/Functions/ZH00000000000000000000000000000000/Versions\"}}"
));
var response = FunctionResource.Update("ZSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", "ZHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", "friendly_name", client: twilioRestClient);
Assert.NotNull(response);
}
}
}
| |
// 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 sys = System;
namespace Google.Ads.GoogleAds.V9.Resources
{
/// <summary>Resource name for the <c>Asset</c> resource.</summary>
public sealed partial class AssetName : gax::IResourceName, sys::IEquatable<AssetName>
{
/// <summary>The possible contents of <see cref="AssetName"/>.</summary>
public enum ResourceNameType
{
/// <summary>An unparsed resource name.</summary>
Unparsed = 0,
/// <summary>A resource name with pattern <c>customers/{customer_id}/assets/{asset_id}</c>.</summary>
CustomerAsset = 1,
}
private static gax::PathTemplate s_customerAsset = new gax::PathTemplate("customers/{customer_id}/assets/{asset_id}");
/// <summary>Creates a <see cref="AssetName"/> 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="AssetName"/> containing the provided <paramref name="unparsedResourceName"/>.
/// </returns>
public static AssetName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) =>
new AssetName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName)));
/// <summary>
/// Creates a <see cref="AssetName"/> with the pattern <c>customers/{customer_id}/assets/{asset_id}</c>.
/// </summary>
/// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="assetId">The <c>Asset</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>A new instance of <see cref="AssetName"/> constructed from the provided ids.</returns>
public static AssetName FromCustomerAsset(string customerId, string assetId) =>
new AssetName(ResourceNameType.CustomerAsset, customerId: gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), assetId: gax::GaxPreconditions.CheckNotNullOrEmpty(assetId, nameof(assetId)));
/// <summary>
/// Formats the IDs into the string representation of this <see cref="AssetName"/> with pattern
/// <c>customers/{customer_id}/assets/{asset_id}</c>.
/// </summary>
/// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="assetId">The <c>Asset</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="AssetName"/> with pattern
/// <c>customers/{customer_id}/assets/{asset_id}</c>.
/// </returns>
public static string Format(string customerId, string assetId) => FormatCustomerAsset(customerId, assetId);
/// <summary>
/// Formats the IDs into the string representation of this <see cref="AssetName"/> with pattern
/// <c>customers/{customer_id}/assets/{asset_id}</c>.
/// </summary>
/// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="assetId">The <c>Asset</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="AssetName"/> with pattern
/// <c>customers/{customer_id}/assets/{asset_id}</c>.
/// </returns>
public static string FormatCustomerAsset(string customerId, string assetId) =>
s_customerAsset.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), gax::GaxPreconditions.CheckNotNullOrEmpty(assetId, nameof(assetId)));
/// <summary>Parses the given resource name string into a new <see cref="AssetName"/> instance.</summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item><description><c>customers/{customer_id}/assets/{asset_id}</c></description></item>
/// </list>
/// </remarks>
/// <param name="assetName">The resource name in string form. Must not be <c>null</c>.</param>
/// <returns>The parsed <see cref="AssetName"/> if successful.</returns>
public static AssetName Parse(string assetName) => Parse(assetName, false);
/// <summary>
/// Parses the given resource name string into a new <see cref="AssetName"/> 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>customers/{customer_id}/assets/{asset_id}</c></description></item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="assetName">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="AssetName"/> if successful.</returns>
public static AssetName Parse(string assetName, bool allowUnparsed) =>
TryParse(assetName, allowUnparsed, out AssetName 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="AssetName"/> instance.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item><description><c>customers/{customer_id}/assets/{asset_id}</c></description></item>
/// </list>
/// </remarks>
/// <param name="assetName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="result">
/// When this method returns, the parsed <see cref="AssetName"/>, 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 assetName, out AssetName result) => TryParse(assetName, false, out result);
/// <summary>
/// Tries to parse the given resource name string into a new <see cref="AssetName"/> 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>customers/{customer_id}/assets/{asset_id}</c></description></item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="assetName">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="AssetName"/>, 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 assetName, bool allowUnparsed, out AssetName result)
{
gax::GaxPreconditions.CheckNotNull(assetName, nameof(assetName));
gax::TemplatedResourceName resourceName;
if (s_customerAsset.TryParseName(assetName, out resourceName))
{
result = FromCustomerAsset(resourceName[0], resourceName[1]);
return true;
}
if (allowUnparsed)
{
if (gax::UnparsedResourceName.TryParse(assetName, out gax::UnparsedResourceName unparsedResourceName))
{
result = FromUnparsed(unparsedResourceName);
return true;
}
}
result = null;
return false;
}
private AssetName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string assetId = null, string customerId = null)
{
Type = type;
UnparsedResource = unparsedResourceName;
AssetId = assetId;
CustomerId = customerId;
}
/// <summary>
/// Constructs a new instance of a <see cref="AssetName"/> class from the component parts of pattern
/// <c>customers/{customer_id}/assets/{asset_id}</c>
/// </summary>
/// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="assetId">The <c>Asset</c> ID. Must not be <c>null</c> or empty.</param>
public AssetName(string customerId, string assetId) : this(ResourceNameType.CustomerAsset, customerId: gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), assetId: gax::GaxPreconditions.CheckNotNullOrEmpty(assetId, nameof(assetId)))
{
}
/// <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>Asset</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string AssetId { get; }
/// <summary>
/// The <c>Customer</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string CustomerId { 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.CustomerAsset: return s_customerAsset.Expand(CustomerId, AssetId);
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 AssetName);
/// <inheritdoc/>
public bool Equals(AssetName other) => ToString() == other?.ToString();
/// <inheritdoc/>
public static bool operator ==(AssetName a, AssetName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false);
/// <inheritdoc/>
public static bool operator !=(AssetName a, AssetName b) => !(a == b);
}
public partial class Asset
{
/// <summary>
/// <see cref="gagvr::AssetName"/>-typed view over the <see cref="ResourceName"/> resource name property.
/// </summary>
internal AssetName ResourceNameAsAssetName
{
get => string.IsNullOrEmpty(ResourceName) ? null : gagvr::AssetName.Parse(ResourceName, allowUnparsed: true);
set => ResourceName = value?.ToString() ?? "";
}
/// <summary>
/// <see cref="gagvr::AssetName"/>-typed view over the <see cref="Name"/> resource name property.
/// </summary>
internal AssetName AssetName
{
get => string.IsNullOrEmpty(Name) ? null : gagvr::AssetName.Parse(Name, allowUnparsed: true);
set => Name = value?.ToString() ?? "";
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using FluentAssertions;
using JsonApiDotNetCore.Serialization.Objects;
using Microsoft.EntityFrameworkCore;
using TestBuildingBlocks;
using Xunit;
namespace JsonApiDotNetCoreTests.IntegrationTests.AtomicOperations.Updating.Resources
{
public sealed class AtomicReplaceToManyRelationshipTests : IClassFixture<IntegrationTestContext<TestableStartup<OperationsDbContext>, OperationsDbContext>>
{
private readonly IntegrationTestContext<TestableStartup<OperationsDbContext>, OperationsDbContext> _testContext;
private readonly OperationsFakers _fakers = new();
public AtomicReplaceToManyRelationshipTests(IntegrationTestContext<TestableStartup<OperationsDbContext>, OperationsDbContext> testContext)
{
_testContext = testContext;
testContext.UseController<OperationsController>();
}
[Fact]
public async Task Can_clear_OneToMany_relationship()
{
// Arrange
MusicTrack existingTrack = _fakers.MusicTrack.Generate();
existingTrack.Performers = _fakers.Performer.Generate(2);
await _testContext.RunOnDatabaseAsync(async dbContext =>
{
await dbContext.ClearTableAsync<Performer>();
dbContext.MusicTracks.Add(existingTrack);
await dbContext.SaveChangesAsync();
});
var requestBody = new
{
atomic__operations = new[]
{
new
{
op = "update",
data = new
{
type = "musicTracks",
id = existingTrack.StringId,
relationships = new
{
performers = new
{
data = Array.Empty<object>()
}
}
}
}
}
};
const string route = "/operations";
// Act
(HttpResponseMessage httpResponse, string responseDocument) = await _testContext.ExecutePostAtomicAsync<string>(route, requestBody);
// Assert
httpResponse.Should().HaveStatusCode(HttpStatusCode.NoContent);
responseDocument.Should().BeEmpty();
await _testContext.RunOnDatabaseAsync(async dbContext =>
{
MusicTrack trackInDatabase = await dbContext.MusicTracks.Include(musicTrack => musicTrack.Performers).FirstWithIdAsync(existingTrack.Id);
trackInDatabase.Performers.Should().BeEmpty();
List<Performer> performersInDatabase = await dbContext.Performers.ToListAsync();
performersInDatabase.Should().HaveCount(2);
});
}
[Fact]
public async Task Can_clear_ManyToMany_relationship()
{
// Arrange
Playlist existingPlaylist = _fakers.Playlist.Generate();
existingPlaylist.Tracks = _fakers.MusicTrack.Generate(2);
await _testContext.RunOnDatabaseAsync(async dbContext =>
{
await dbContext.ClearTableAsync<MusicTrack>();
dbContext.Playlists.Add(existingPlaylist);
await dbContext.SaveChangesAsync();
});
var requestBody = new
{
atomic__operations = new[]
{
new
{
op = "update",
data = new
{
type = "playlists",
id = existingPlaylist.StringId,
relationships = new
{
tracks = new
{
data = Array.Empty<object>()
}
}
}
}
}
};
const string route = "/operations";
// Act
(HttpResponseMessage httpResponse, string responseDocument) = await _testContext.ExecutePostAtomicAsync<string>(route, requestBody);
// Assert
httpResponse.Should().HaveStatusCode(HttpStatusCode.NoContent);
responseDocument.Should().BeEmpty();
await _testContext.RunOnDatabaseAsync(async dbContext =>
{
Playlist playlistInDatabase = await dbContext.Playlists.Include(playlist => playlist.Tracks).FirstWithIdAsync(existingPlaylist.Id);
playlistInDatabase.Tracks.Should().BeEmpty();
List<MusicTrack> tracksInDatabase = await dbContext.MusicTracks.ToListAsync();
tracksInDatabase.Should().HaveCount(2);
});
}
[Fact]
public async Task Can_replace_OneToMany_relationship()
{
// Arrange
MusicTrack existingTrack = _fakers.MusicTrack.Generate();
existingTrack.Performers = _fakers.Performer.Generate(1);
List<Performer> existingPerformers = _fakers.Performer.Generate(2);
await _testContext.RunOnDatabaseAsync(async dbContext =>
{
await dbContext.ClearTableAsync<Performer>();
dbContext.MusicTracks.Add(existingTrack);
dbContext.Performers.AddRange(existingPerformers);
await dbContext.SaveChangesAsync();
});
var requestBody = new
{
atomic__operations = new[]
{
new
{
op = "update",
data = new
{
type = "musicTracks",
id = existingTrack.StringId,
relationships = new
{
performers = new
{
data = new[]
{
new
{
type = "performers",
id = existingPerformers[0].StringId
},
new
{
type = "performers",
id = existingPerformers[1].StringId
}
}
}
}
}
}
}
};
const string route = "/operations";
// Act
(HttpResponseMessage httpResponse, string responseDocument) = await _testContext.ExecutePostAtomicAsync<string>(route, requestBody);
// Assert
httpResponse.Should().HaveStatusCode(HttpStatusCode.NoContent);
responseDocument.Should().BeEmpty();
await _testContext.RunOnDatabaseAsync(async dbContext =>
{
MusicTrack trackInDatabase = await dbContext.MusicTracks.Include(musicTrack => musicTrack.Performers).FirstWithIdAsync(existingTrack.Id);
trackInDatabase.Performers.Should().HaveCount(2);
trackInDatabase.Performers.Should().ContainSingle(performer => performer.Id == existingPerformers[0].Id);
trackInDatabase.Performers.Should().ContainSingle(performer => performer.Id == existingPerformers[1].Id);
List<Performer> performersInDatabase = await dbContext.Performers.ToListAsync();
performersInDatabase.Should().HaveCount(3);
});
}
[Fact]
public async Task Can_replace_ManyToMany_relationship()
{
// Arrange
Playlist existingPlaylist = _fakers.Playlist.Generate();
existingPlaylist.Tracks = _fakers.MusicTrack.Generate(1);
List<MusicTrack> existingTracks = _fakers.MusicTrack.Generate(2);
await _testContext.RunOnDatabaseAsync(async dbContext =>
{
await dbContext.ClearTableAsync<MusicTrack>();
dbContext.Playlists.Add(existingPlaylist);
dbContext.MusicTracks.AddRange(existingTracks);
await dbContext.SaveChangesAsync();
});
var requestBody = new
{
atomic__operations = new[]
{
new
{
op = "update",
data = new
{
type = "playlists",
id = existingPlaylist.StringId,
relationships = new
{
tracks = new
{
data = new[]
{
new
{
type = "musicTracks",
id = existingTracks[0].StringId
},
new
{
type = "musicTracks",
id = existingTracks[1].StringId
}
}
}
}
}
}
}
};
const string route = "/operations";
// Act
(HttpResponseMessage httpResponse, string responseDocument) = await _testContext.ExecutePostAtomicAsync<string>(route, requestBody);
// Assert
httpResponse.Should().HaveStatusCode(HttpStatusCode.NoContent);
responseDocument.Should().BeEmpty();
await _testContext.RunOnDatabaseAsync(async dbContext =>
{
Playlist playlistInDatabase = await dbContext.Playlists.Include(playlist => playlist.Tracks).FirstWithIdAsync(existingPlaylist.Id);
playlistInDatabase.Tracks.Should().HaveCount(2);
playlistInDatabase.Tracks.Should().ContainSingle(musicTrack => musicTrack.Id == existingTracks[0].Id);
playlistInDatabase.Tracks.Should().ContainSingle(musicTrack => musicTrack.Id == existingTracks[1].Id);
List<MusicTrack> tracksInDatabase = await dbContext.MusicTracks.ToListAsync();
tracksInDatabase.Should().HaveCount(3);
});
}
[Fact]
public async Task Cannot_replace_for_null_relationship_data()
{
// Arrange
MusicTrack existingTrack = _fakers.MusicTrack.Generate();
await _testContext.RunOnDatabaseAsync(async dbContext =>
{
dbContext.MusicTracks.Add(existingTrack);
await dbContext.SaveChangesAsync();
});
var requestBody = new
{
atomic__operations = new[]
{
new
{
op = "update",
data = new
{
type = "musicTracks",
id = existingTrack.StringId,
relationships = new
{
performers = new
{
data = (object)null
}
}
}
}
}
};
const string route = "/operations";
// Act
(HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecutePostAtomicAsync<Document>(route, requestBody);
// Assert
httpResponse.Should().HaveStatusCode(HttpStatusCode.UnprocessableEntity);
responseDocument.Errors.Should().HaveCount(1);
ErrorObject error = responseDocument.Errors[0];
error.StatusCode.Should().Be(HttpStatusCode.UnprocessableEntity);
error.Title.Should().Be("Failed to deserialize request body: Expected data[] element for to-many relationship.");
error.Detail.Should().Be("Expected data[] element for 'performers' relationship.");
error.Source.Pointer.Should().Be("/atomic:operations[0]");
}
[Fact]
public async Task Cannot_replace_for_missing_type_in_relationship_data()
{
// Arrange
var requestBody = new
{
atomic__operations = new[]
{
new
{
op = "update",
data = new
{
type = "playlists",
id = Unknown.StringId.For<Playlist, long>(),
relationships = new
{
tracks = new
{
data = new[]
{
new
{
id = Unknown.StringId.For<MusicTrack, Guid>()
}
}
}
}
}
}
}
};
const string route = "/operations";
// Act
(HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecutePostAtomicAsync<Document>(route, requestBody);
// Assert
httpResponse.Should().HaveStatusCode(HttpStatusCode.UnprocessableEntity);
responseDocument.Errors.Should().HaveCount(1);
ErrorObject error = responseDocument.Errors[0];
error.StatusCode.Should().Be(HttpStatusCode.UnprocessableEntity);
error.Title.Should().Be("Failed to deserialize request body: Request body must include 'type' element.");
error.Detail.Should().Be("Expected 'type' element in 'tracks' relationship.");
error.Source.Pointer.Should().Be("/atomic:operations[0]");
}
[Fact]
public async Task Cannot_replace_for_unknown_type_in_relationship_data()
{
// Arrange
var requestBody = new
{
atomic__operations = new[]
{
new
{
op = "update",
data = new
{
type = "musicTracks",
id = Unknown.StringId.For<MusicTrack, Guid>(),
relationships = new
{
performers = new
{
data = new[]
{
new
{
type = Unknown.ResourceType,
id = Unknown.StringId.For<Performer, int>()
}
}
}
}
}
}
}
};
const string route = "/operations";
// Act
(HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecutePostAtomicAsync<Document>(route, requestBody);
// Assert
httpResponse.Should().HaveStatusCode(HttpStatusCode.UnprocessableEntity);
responseDocument.Errors.Should().HaveCount(1);
ErrorObject error = responseDocument.Errors[0];
error.StatusCode.Should().Be(HttpStatusCode.UnprocessableEntity);
error.Title.Should().Be("Failed to deserialize request body: Request body includes unknown resource type.");
error.Detail.Should().Be($"Resource type '{Unknown.ResourceType}' does not exist.");
error.Source.Pointer.Should().Be("/atomic:operations[0]");
}
[Fact]
public async Task Cannot_replace_for_missing_ID_in_relationship_data()
{
// Arrange
var requestBody = new
{
atomic__operations = new[]
{
new
{
op = "update",
data = new
{
type = "musicTracks",
id = Unknown.StringId.For<MusicTrack, Guid>(),
relationships = new
{
performers = new
{
data = new[]
{
new
{
type = "performers"
}
}
}
}
}
}
}
};
const string route = "/operations";
// Act
(HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecutePostAtomicAsync<Document>(route, requestBody);
// Assert
httpResponse.Should().HaveStatusCode(HttpStatusCode.UnprocessableEntity);
responseDocument.Errors.Should().HaveCount(1);
ErrorObject error = responseDocument.Errors[0];
error.StatusCode.Should().Be(HttpStatusCode.UnprocessableEntity);
error.Title.Should().Be("Failed to deserialize request body: Request body must include 'id' or 'lid' element.");
error.Detail.Should().Be("Expected 'id' or 'lid' element in 'performers' relationship.");
error.Source.Pointer.Should().Be("/atomic:operations[0]");
}
[Fact]
public async Task Cannot_replace_for_ID_and_local_ID_relationship_in_data()
{
// Arrange
var requestBody = new
{
atomic__operations = new[]
{
new
{
op = "update",
data = new
{
type = "musicTracks",
id = Unknown.StringId.For<MusicTrack, Guid>(),
relationships = new
{
performers = new
{
data = new[]
{
new
{
type = "performers",
id = Unknown.StringId.For<Performer, int>(),
lid = "local-1"
}
}
}
}
}
}
}
};
const string route = "/operations";
// Act
(HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecutePostAtomicAsync<Document>(route, requestBody);
// Assert
httpResponse.Should().HaveStatusCode(HttpStatusCode.UnprocessableEntity);
responseDocument.Errors.Should().HaveCount(1);
ErrorObject error = responseDocument.Errors[0];
error.StatusCode.Should().Be(HttpStatusCode.UnprocessableEntity);
error.Title.Should().Be("Failed to deserialize request body: Request body must include 'id' or 'lid' element.");
error.Detail.Should().Be("Expected 'id' or 'lid' element in 'performers' relationship.");
error.Source.Pointer.Should().Be("/atomic:operations[0]");
}
[Fact]
public async Task Cannot_replace_for_unknown_IDs_in_relationship_data()
{
// Arrange
RecordCompany existingCompany = _fakers.RecordCompany.Generate();
string[] trackIds =
{
Unknown.StringId.For<MusicTrack, Guid>(),
Unknown.StringId.AltFor<MusicTrack, Guid>()
};
await _testContext.RunOnDatabaseAsync(async dbContext =>
{
dbContext.RecordCompanies.Add(existingCompany);
await dbContext.SaveChangesAsync();
});
var requestBody = new
{
atomic__operations = new[]
{
new
{
op = "update",
data = new
{
type = "recordCompanies",
id = existingCompany.StringId,
relationships = new
{
tracks = new
{
data = new[]
{
new
{
type = "musicTracks",
id = trackIds[0]
},
new
{
type = "musicTracks",
id = trackIds[1]
}
}
}
}
}
}
}
};
const string route = "/operations";
// Act
(HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecutePostAtomicAsync<Document>(route, requestBody);
// Assert
httpResponse.Should().HaveStatusCode(HttpStatusCode.NotFound);
responseDocument.Errors.Should().HaveCount(2);
ErrorObject error1 = responseDocument.Errors[0];
error1.StatusCode.Should().Be(HttpStatusCode.NotFound);
error1.Title.Should().Be("A related resource does not exist.");
error1.Detail.Should().Be($"Related resource of type 'musicTracks' with ID '{trackIds[0]}' in relationship 'tracks' does not exist.");
error1.Source.Pointer.Should().Be("/atomic:operations[0]");
ErrorObject error2 = responseDocument.Errors[1];
error2.StatusCode.Should().Be(HttpStatusCode.NotFound);
error2.Title.Should().Be("A related resource does not exist.");
error2.Detail.Should().Be($"Related resource of type 'musicTracks' with ID '{trackIds[1]}' in relationship 'tracks' does not exist.");
error2.Source.Pointer.Should().Be("/atomic:operations[0]");
}
[Fact]
public async Task Cannot_create_for_relationship_mismatch()
{
// Arrange
MusicTrack existingTrack = _fakers.MusicTrack.Generate();
await _testContext.RunOnDatabaseAsync(async dbContext =>
{
dbContext.MusicTracks.Add(existingTrack);
await dbContext.SaveChangesAsync();
});
var requestBody = new
{
atomic__operations = new[]
{
new
{
op = "update",
data = new
{
type = "musicTracks",
id = existingTrack.StringId,
relationships = new
{
performers = new
{
data = new[]
{
new
{
type = "playlists",
id = Unknown.StringId.For<Playlist, long>()
}
}
}
}
}
}
}
};
const string route = "/operations";
// Act
(HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecutePostAtomicAsync<Document>(route, requestBody);
// Assert
httpResponse.Should().HaveStatusCode(HttpStatusCode.UnprocessableEntity);
responseDocument.Errors.Should().HaveCount(1);
ErrorObject error = responseDocument.Errors[0];
error.StatusCode.Should().Be(HttpStatusCode.UnprocessableEntity);
error.Title.Should().Be("Failed to deserialize request body: Relationship contains incompatible resource type.");
error.Detail.Should().Be("Relationship 'performers' contains incompatible resource type 'playlists'.");
error.Source.Pointer.Should().Be("/atomic:operations[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 Xunit;
public class VersionTests
{
[Theory]
[MemberData(nameof(Parse_Valid_TestData))]
public static void TestCtor_String(string input, Version expected)
{
Assert.Equal(expected, new Version(input));
}
[Theory]
[MemberData(nameof(Parse_Invalid_TestData))]
public static void TestCtor_String_Invalid(string input, Type exceptionType)
{
Assert.Throws(exceptionType, () => new Version(input)); // Input is invalid
}
[Theory]
[InlineData(0, 0)]
[InlineData(2, 3)]
[InlineData(int.MaxValue, int.MaxValue)]
public static void TestCtor_Int_Int(int major, int minor)
{
VerifyVersion(new Version(major, minor), major, minor, -1, -1);
}
[Fact]
public static void TestCtor_Int_Int_Invalid()
{
Assert.Throws<ArgumentOutOfRangeException>("major", () => new Version(-1, 0)); // Major < 0
Assert.Throws<ArgumentOutOfRangeException>("minor", () => new Version(0, -1)); // Minor < 0
}
[Theory]
[InlineData(0, 0, 0)]
[InlineData(2, 3, 4)]
[InlineData(int.MaxValue, int.MaxValue, int.MaxValue)]
public static void TestCtor_Int_Int_Int(int major, int minor, int build)
{
VerifyVersion(new Version(major, minor, build), major, minor, build, -1);
}
[Fact]
public static void TestCtor_Int_Int_Int_Invalid()
{
Assert.Throws<ArgumentOutOfRangeException>("major", () => new Version(-1, 0, 0)); // Major < 0
Assert.Throws<ArgumentOutOfRangeException>("minor", () => new Version(0, -1, 0)); // Minor < 0
Assert.Throws<ArgumentOutOfRangeException>("build", () => new Version(0, 0, -1)); // Build < 0
}
[Theory]
[InlineData(0, 0, 0, 0)]
[InlineData(2, 3, 4, 7)]
[InlineData(2, 3, 4, 32767)]
[InlineData(2, 3, 4, 32768)]
[InlineData(2, 3, 4, 65535)]
[InlineData(2, 3, 4, 65536)]
[InlineData(2, 3, 4, 2147483647)]
[InlineData(2, 3, 4, 2147450879)]
[InlineData(2, 3, 4, 2147418112)]
[InlineData(int.MaxValue, int.MaxValue, int.MaxValue, int.MaxValue)]
public static void TestCtor_Int_Int_Int_Int(int major, int minor, int build, int revision)
{
VerifyVersion(new Version(major, minor, build, revision), major, minor, build, revision);
}
[Fact]
public static void TestCtor_Int_Int_Int_Int_Invalid()
{
Assert.Throws<ArgumentOutOfRangeException>("major", () => new Version(-1, 0, 0, 0)); // Major < 0
Assert.Throws<ArgumentOutOfRangeException>("minor", () => new Version(0, -1, 0, 0)); // Minor < 0
Assert.Throws<ArgumentOutOfRangeException>("build", () => new Version(0, 0, -1, 0)); // Build < 0
Assert.Throws<ArgumentOutOfRangeException>("revision", () => new Version(0, 0, 0, -1)); // Revision < 0
}
public static IEnumerable<object[]> CompareToTestData()
{
yield return new object[] { new Version(1, 2), null, 1 };
yield return new object[] { new Version(1, 2), new Version(1, 2), 0 };
yield return new object[] { new Version(1, 2), new Version(1, 3), -1 };
yield return new object[] { new Version(1, 2), new Version(1, 1), 1 };
yield return new object[] { new Version(1, 2), new Version(2, 0), -1 };
yield return new object[] { new Version(1, 2), new Version(1, 2, 1), -1 };
yield return new object[] { new Version(1, 2), new Version(1, 2, 0, 1), -1 };
yield return new object[] { new Version(1, 2), new Version(1, 0), 1 };
yield return new object[] { new Version(1, 2), new Version(1, 0, 1), 1 };
yield return new object[] { new Version(1, 2), new Version(1, 0, 0, 1), 1 };
yield return new object[] { new Version(1, 2, 3, 4), new Version(1, 2, 3, 4), 0 };
yield return new object[] { new Version(1, 2, 3, 4), new Version(1, 2, 3, 5), -1 };
yield return new object[] { new Version(1, 2, 3, 4), new Version(1, 2, 3, 3), 1 };
}
[Theory]
[MemberData(nameof(CompareToTestData))]
public static void TestCompareTo(Version version1, Version obj, int expectedSign)
{
Version version2 = obj as Version;
Assert.Equal(expectedSign, Math.Sign(version1.CompareTo(version2)));
if (version1 != null && version2 != null)
{
if (expectedSign >= 0)
{
Assert.True(version1 >= version2);
Assert.False(version1 < version2);
}
if (expectedSign > 0)
{
Assert.True(version1 > version2);
Assert.False(version1 <= version2);
}
if (expectedSign <= 0)
{
Assert.True(version1 <= version2);
Assert.False(version1 > version2);
}
if (expectedSign < 0)
{
Assert.True(version1 < version2);
Assert.False(version1 >= version2);
}
}
IComparable comparable = version1;
Assert.Equal(expectedSign, Math.Sign(comparable.CompareTo(obj)));
}
[Fact]
public static void TestCompareTo_Invalid()
{
IComparable comparable = new Version(1, 1);
Assert.Throws<ArgumentException>(null, () => comparable.CompareTo(1)); // Obj is not a version
Assert.Throws<ArgumentException>(null, () => comparable.CompareTo("1.1")); // Obj is not a version
Version nullVersion = null;
Version testVersion = new Version(1, 2);
Assert.Throws<ArgumentNullException>("v1", () => testVersion >= nullVersion); // V2 is null
Assert.Throws<ArgumentNullException>("v1", () => testVersion > nullVersion); // V2 is null
Assert.Throws<ArgumentNullException>("v1", () => nullVersion < testVersion); // V1 is null
Assert.Throws<ArgumentNullException>("v1", () => nullVersion <= testVersion); // V1 is null
}
private static IEnumerable<object[]> EqualsTestData()
{
yield return new object[] { new Version(2, 3), new Version(2, 3), true };
yield return new object[] { new Version(2, 3), new Version(2, 4), false };
yield return new object[] { new Version(2, 3), new Version(3, 3), false };
yield return new object[] { new Version(2, 3, 4), new Version(2, 3, 4), true };
yield return new object[] { new Version(2, 3, 4), new Version(2, 3, 5), false };
yield return new object[] { new Version(2, 3, 4), new Version(2, 3), false };
yield return new object[] { new Version(2, 3, 4, 5), new Version(2, 3, 4, 5), true };
yield return new object[] { new Version(2, 3, 4, 5), new Version(2, 3, 4, 6), false };
yield return new object[] { new Version(2, 3, 4, 5), new Version(2, 3), false };
yield return new object[] { new Version(2, 3, 4, 5), new Version(2, 3, 4), false };
yield return new object[] { new Version(2, 3, 0), new Version(2, 3), false };
yield return new object[] { new Version(2, 3, 4, 0), new Version(2, 3, 4), false };
yield return new object[] { new Version(2, 3, 4, 5), null, false };
}
[Theory]
[MemberData(nameof(EqualsTestData))]
public static void TestEquals(Version version1, object obj, bool expected)
{
Version version2 = obj as Version;
Assert.Equal(expected, version1.Equals(version2));
Assert.Equal(expected, version1.Equals(obj));
Assert.Equal(expected, version1 == version2);
Assert.Equal(!expected, version1 != version2);
if (version2 != null)
{
Assert.Equal(expected, version1.GetHashCode().Equals(version2.GetHashCode()));
}
}
private static IEnumerable<object[]> Parse_Valid_TestData()
{
yield return new object[] { "1.2", new Version(1, 2) };
yield return new object[] { "1.2.3", new Version(1, 2, 3) };
yield return new object[] { "1.2.3.4", new Version(1, 2, 3, 4) };
yield return new object[] { "2 .3. 4. \t\r\n15 ", new Version(2, 3, 4, 15) };
}
[Theory]
[MemberData(nameof(Parse_Valid_TestData))]
public static void TestParse(string input, Version expected)
{
Assert.Equal(expected, Version.Parse(input));
Version version;
Assert.True(Version.TryParse(input, out version));
Assert.Equal(expected, version);
}
private static IEnumerable<object[]> Parse_Invalid_TestData()
{
yield return new object[] { null, typeof(ArgumentNullException) }; // Input is null
yield return new object[] { "", typeof(ArgumentException) }; // Input is empty
yield return new object[] { "1,2,3,4", typeof(ArgumentException) }; // Input has fewer than 4 version components
yield return new object[] { "1", typeof(ArgumentException) }; // Input has fewer than 2 version components
yield return new object[] { "1.2.3.4.5", typeof(ArgumentException) }; // Input has more than 4 version components
yield return new object[] { "-1.2.3.4", typeof(ArgumentOutOfRangeException) }; // Input contains negative value
yield return new object[] { "1.-2.3.4", typeof(ArgumentOutOfRangeException) }; // Input contains negative value
yield return new object[] { "1.2.-3.4", typeof(ArgumentOutOfRangeException) }; // Input contains negative value
yield return new object[] { "1.2.3.-4", typeof(ArgumentOutOfRangeException) }; // Input contains negative value
yield return new object[] { "b.2.3.4", typeof(FormatException) }; // Input contains non-numeric value
yield return new object[] { "1.b.3.4", typeof(FormatException) }; // Input contains non-numeric value
yield return new object[] { "1.2.b.4", typeof(FormatException) }; // Input contains non-numeric value
yield return new object[] { "1.2.3.b", typeof(FormatException) }; // Input contains non-numeric value
yield return new object[] { "2147483648.2.3.4", typeof(OverflowException) }; // Input contains a value > int.MaxValue
yield return new object[] { "1.2147483648.3.4", typeof(OverflowException) }; // Input contains a value > int.MaxValue
yield return new object[] { "1.2.2147483648.4", typeof(OverflowException) }; // Input contains a value > int.MaxValue
yield return new object[] { "1.2.3.2147483648", typeof(OverflowException) }; // Input contains a value > int.MaxValue
}
[Theory]
[MemberData(nameof(Parse_Invalid_TestData))]
public static void TestParse_Invalid(string input, Type exceptionType)
{
Assert.Throws(exceptionType, () => Version.Parse(input));
Version version;
Assert.False(Version.TryParse(input, out version));
}
public static IEnumerable<object[]> ToStringTestData()
{
yield return new object[] { new Version(1, 2), new string[] { "", "1", "1.2" } };
yield return new object[] { new Version(1, 2, 3), new string[] { "", "1", "1.2", "1.2.3" } };
yield return new object[] { new Version(1, 2, 3, 4), new string[] { "", "1", "1.2", "1.2.3", "1.2.3.4" } };
}
[Theory]
[MemberData(nameof(ToStringTestData))]
public static void TestToString(Version version, string[] expected)
{
for (int i = 0; i < expected.Length; i++)
{
Assert.Equal(expected[i], version.ToString(i));
}
int maxFieldCount = expected.Length - 1;
Assert.Equal(expected[maxFieldCount], version.ToString());
Assert.Throws<ArgumentException>("fieldCount", () => version.ToString(-1)); // Index < 0
Assert.Throws<ArgumentException>("fieldCount", () => version.ToString(maxFieldCount + 1)); // Index > version.fieldCount
}
private static void VerifyVersion(Version version, int major, int minor, int build, int revision)
{
Assert.Equal(major, version.Major);
Assert.Equal(minor, version.Minor);
Assert.Equal(build, version.Build);
Assert.Equal(revision, version.Revision);
Assert.Equal((short)(revision >> 16), version.MajorRevision);
Assert.Equal((short)(revision & 0xFFFF), version.MinorRevision);
}
}
| |
/*
* Copyright 2013 ThirdMotion, 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.
*/
/**
* @class strange.extensions.dispatcher.eventdispatcher.impl.EventDispatcher
*
* A Dispatcher that uses IEvent to send messages.
*
* Whenever the Dispatcher executes a `Dispatch()`, observers will be
* notified of any event (Key) for which they have registered.
*
* EventDispatcher dispatches TmEvent : IEvent.
*
* The EventDispatcher is the only Dispatcher currently released with Strange
* (though by separating EventDispatcher from Dispatcher I'm obviously
* signalling that I don't think it's the only possible one).
*
* EventDispatcher is both an ITriggerProvider and an ITriggerable.
*
* @see strange.extensions.dispatcher.eventdispatcher.api.IEvent
* @see strange.extensions.dispatcher.api.ITriggerProvider
* @see strange.extensions.dispatcher.api.ITriggerable
*/
using System;
using System.Collections.Generic;
using strange.framework.api;
using strange.framework.impl;
using strange.extensions.dispatcher.api;
using strange.extensions.dispatcher.eventdispatcher.api;
using strange.extensions.pool.api;
using strange.extensions.pool.impl;
namespace strange.extensions.dispatcher.eventdispatcher.impl
{
public class EventDispatcher : Binder, IEventDispatcher, ITriggerProvider, ITriggerable
{
/// The list of clients that will be triggered as a consequence of an Event firing.
protected HashSet<ITriggerable> triggerClients;
protected HashSet<ITriggerable> triggerClientRemovals;
protected bool isTriggeringClients;
/// The eventPool is shared across all EventDispatchers for efficiency
public static IPool<TmEvent> eventPool;
public EventDispatcher ()
{
if (eventPool == null)
{
eventPool = new Pool<TmEvent> ();
eventPool.instanceProvider = new EventInstanceProvider ();
}
}
override public IBinding GetRawBinding()
{
return new EventBinding (resolver);
}
new public IEventBinding Bind(object key)
{
return base.Bind (key) as IEventBinding;
}
public void Dispatch (object eventType)
{
Dispatch (eventType, null);
}
public void Dispatch (object eventType, object data)
{
//Scrub the data to make eventType and data conform if possible
IEvent evt = conformDataToEvent (eventType, data);
if (evt is IPoolable)
{
(evt as IPoolable).Retain ();
}
bool continueDispatch = true;
if (triggerClients != null)
{
isTriggeringClients = true;
foreach (ITriggerable trigger in triggerClients)
{
try
{
if (!trigger.Trigger(evt.type, evt))
{
continueDispatch = false;
break;
}
}
catch (Exception ) //If trigger throws, we still want to cleanup!
{
internalReleaseEvent(evt);
throw;
}
}
if (triggerClientRemovals != null)
{
flushRemovals();
}
isTriggeringClients = false;
}
if (!continueDispatch)
{
internalReleaseEvent (evt);
return;
}
IEventBinding binding = GetBinding (evt.type) as IEventBinding;
if (binding == null)
{
internalReleaseEvent (evt);
return;
}
object[] callbacks = (binding.value as object[]).Clone() as object[];
if (callbacks == null)
{
internalReleaseEvent (evt);
return;
}
for(int a = 0; a < callbacks.Length; a++)
{
object callback = callbacks[a];
if(callback == null)
continue;
callbacks[a] = null;
object[] currentCallbacks = binding.value as object[];
if(Array.IndexOf(currentCallbacks, callback) == -1)
continue;
if (callback is EventCallback)
{
invokeEventCallback (evt, callback as EventCallback);
}
else if (callback is EmptyCallback)
{
(callback as EmptyCallback)();
}
}
internalReleaseEvent (evt);
}
virtual protected IEvent conformDataToEvent(object eventType, object data)
{
IEvent retv = null;
if (eventType == null)
{
throw new EventDispatcherException("Attempt to Dispatch to null.\ndata: " + data, EventDispatcherExceptionType.EVENT_KEY_NULL);
}
else if (eventType is IEvent)
{
//Client provided a full-formed event
retv = (IEvent)eventType;
}
else if (data == null)
{
//Client provided just an event ID. Create an event for injection
retv = createEvent (eventType, null);
}
else if (data is IEvent)
{
//Client provided both an evertType and a full-formed IEvent
retv = (IEvent)data;
}
else
{
//Client provided an eventType and some data which is not a IEvent.
retv = createEvent (eventType, data);
}
return retv;
}
virtual protected IEvent createEvent(object eventType, object data)
{
IEvent retv = eventPool.GetInstance();
retv.type = eventType;
retv.target = this;
retv.data = data;
return retv;
}
virtual protected void invokeEventCallback(object data, EventCallback callback)
{
try
{
callback (data as IEvent);
}
catch(InvalidCastException)
{
object tgt = callback.Target;
string methodName = (callback as Delegate).Method.Name;
string message = "An EventCallback is attempting an illegal cast. One possible reason is not typing the payload to IEvent in your callback. Another is illegal casting of the data.\nTarget class: " + tgt + " method: " + methodName;
throw new EventDispatcherException (message, EventDispatcherExceptionType.TARGET_INVOCATION);
}
}
public void AddListener(object evt, EventCallback callback)
{
IBinding binding = GetBinding (evt);
if (binding == null)
{
Bind (evt).To (callback);
}
else
{
binding.To (callback);
}
}
public void AddListener(object evt, EmptyCallback callback)
{
IBinding binding = GetBinding (evt);
if (binding == null)
{
Bind (evt).To (callback);
}
else
{
binding.To (callback);
}
}
public void RemoveListener(object evt, EventCallback callback)
{
IBinding binding = GetBinding (evt);
RemoveValue (binding, callback);
}
public void RemoveListener(object evt, EmptyCallback callback)
{
IBinding binding = GetBinding (evt);
RemoveValue (binding, callback);
}
public bool HasListener(object evt, EventCallback callback)
{
IEventBinding binding = GetBinding (evt) as IEventBinding;
if (binding == null)
{
return false;
}
return binding.TypeForCallback (callback) != EventCallbackType.NOT_FOUND;
}
public bool HasListener(object evt, EmptyCallback callback)
{
IEventBinding binding = GetBinding (evt) as IEventBinding;
if (binding == null)
{
return false;
}
return binding.TypeForCallback (callback) != EventCallbackType.NOT_FOUND;
}
public void UpdateListener(bool toAdd, object evt, EventCallback callback)
{
if (toAdd)
{
AddListener (evt, callback);
}
else
{
RemoveListener (evt, callback);
}
}
public void UpdateListener(bool toAdd, object evt, EmptyCallback callback)
{
if (toAdd)
{
AddListener (evt, callback);
}
else
{
RemoveListener (evt, callback);
}
}
public void AddTriggerable(ITriggerable target)
{
if (triggerClients == null)
{
triggerClients = new HashSet<ITriggerable>();
}
triggerClients.Add(target);
}
public void RemoveTriggerable(ITriggerable target)
{
if (triggerClients.Contains(target))
{
if (triggerClientRemovals == null)
{
triggerClientRemovals = new HashSet<ITriggerable>();
}
triggerClientRemovals.Add (target);
if (!isTriggeringClients)
{
flushRemovals();
}
}
}
public int Triggerables
{
get
{
if (triggerClients == null)
return 0;
return triggerClients.Count;
}
}
protected void flushRemovals()
{
if (triggerClientRemovals == null)
{
return;
}
foreach(ITriggerable target in triggerClientRemovals)
{
if (triggerClients.Contains(target))
{
triggerClients.Remove(target);
}
}
triggerClientRemovals = null;
}
public bool Trigger<T>(object data)
{
return Trigger (typeof(T), data);
}
public bool Trigger(object key, object data)
{
bool allow = ((data is IEvent && System.Object.ReferenceEquals((data as IEvent).target, this) == false) ||
(key is IEvent && System.Object.ReferenceEquals((data as IEvent).target, this) == false));
if (allow)
Dispatch(key, data);
return true;
}
protected void internalReleaseEvent(IEvent evt)
{
if (evt is IPoolable)
{
(evt as IPoolable).Release ();
}
}
public void ReleaseEvent(IEvent evt)
{
if ((evt as IPoolable).retain == false)
{
cleanEvent (evt);
eventPool.ReturnInstance (evt);
}
}
protected void cleanEvent(IEvent evt)
{
evt.target = null;
evt.data = null;
evt.type = null;
}
}
class EventInstanceProvider : IInstanceProvider
{
public T GetInstance<T>()
{
object instance = new TmEvent ();
T retv = (T) instance;
return retv;
}
public object GetInstance(Type key)
{
return new TmEvent ();
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Reflection;
namespace MySubModule.Web.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;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Reflection;
using System.Xml.Schema;
using System.Xml.XPath;
using System.Xml.Xsl;
using System.Xml.Xsl.Runtime;
namespace System.Xml.Xsl.Qil
{
/// <summary>
/// This class performs two functions:
/// 1. Infer XmlQueryType of Qil nodes (constant, from arguments, etc)
/// 2. Validate the arguments of Qil nodes if DEBUG is defined
/// </summary>
internal class QilTypeChecker
{
public QilTypeChecker()
{
}
public XmlQueryType Check(QilNode n)
{
#region AUTOGENERATED
return n.NodeType switch
{
QilNodeType.QilExpression => CheckQilExpression((QilExpression)n),
QilNodeType.FunctionList => CheckFunctionList((QilList)n),
QilNodeType.GlobalVariableList => CheckGlobalVariableList((QilList)n),
QilNodeType.GlobalParameterList => CheckGlobalParameterList((QilList)n),
QilNodeType.ActualParameterList => CheckActualParameterList((QilList)n),
QilNodeType.FormalParameterList => CheckFormalParameterList((QilList)n),
QilNodeType.SortKeyList => CheckSortKeyList((QilList)n),
QilNodeType.BranchList => CheckBranchList((QilList)n),
QilNodeType.OptimizeBarrier => CheckOptimizeBarrier((QilUnary)n),
QilNodeType.Unknown => CheckUnknown(n),
QilNodeType.DataSource => CheckDataSource((QilDataSource)n),
QilNodeType.Nop => CheckNop((QilUnary)n),
QilNodeType.Error => CheckError((QilUnary)n),
QilNodeType.Warning => CheckWarning((QilUnary)n),
QilNodeType.For => CheckFor((QilIterator)n),
QilNodeType.Let => CheckLet((QilIterator)n),
QilNodeType.Parameter => CheckParameter((QilParameter)n),
QilNodeType.PositionOf => CheckPositionOf((QilUnary)n),
QilNodeType.True => CheckTrue(n),
QilNodeType.False => CheckFalse(n),
QilNodeType.LiteralString => CheckLiteralString((QilLiteral)n),
QilNodeType.LiteralInt32 => CheckLiteralInt32((QilLiteral)n),
QilNodeType.LiteralInt64 => CheckLiteralInt64((QilLiteral)n),
QilNodeType.LiteralDouble => CheckLiteralDouble((QilLiteral)n),
QilNodeType.LiteralDecimal => CheckLiteralDecimal((QilLiteral)n),
QilNodeType.LiteralQName => CheckLiteralQName((QilName)n),
QilNodeType.LiteralType => CheckLiteralType((QilLiteral)n),
QilNodeType.LiteralObject => CheckLiteralObject((QilLiteral)n),
QilNodeType.And => CheckAnd((QilBinary)n),
QilNodeType.Or => CheckOr((QilBinary)n),
QilNodeType.Not => CheckNot((QilUnary)n),
QilNodeType.Conditional => CheckConditional((QilTernary)n),
QilNodeType.Choice => CheckChoice((QilChoice)n),
QilNodeType.Length => CheckLength((QilUnary)n),
QilNodeType.Sequence => CheckSequence((QilList)n),
QilNodeType.Union => CheckUnion((QilBinary)n),
QilNodeType.Intersection => CheckIntersection((QilBinary)n),
QilNodeType.Difference => CheckDifference((QilBinary)n),
QilNodeType.Average => CheckAverage((QilUnary)n),
QilNodeType.Sum => CheckSum((QilUnary)n),
QilNodeType.Minimum => CheckMinimum((QilUnary)n),
QilNodeType.Maximum => CheckMaximum((QilUnary)n),
QilNodeType.Negate => CheckNegate((QilUnary)n),
QilNodeType.Add => CheckAdd((QilBinary)n),
QilNodeType.Subtract => CheckSubtract((QilBinary)n),
QilNodeType.Multiply => CheckMultiply((QilBinary)n),
QilNodeType.Divide => CheckDivide((QilBinary)n),
QilNodeType.Modulo => CheckModulo((QilBinary)n),
QilNodeType.StrLength => CheckStrLength((QilUnary)n),
QilNodeType.StrConcat => CheckStrConcat((QilStrConcat)n),
QilNodeType.StrParseQName => CheckStrParseQName((QilBinary)n),
QilNodeType.Ne => CheckNe((QilBinary)n),
QilNodeType.Eq => CheckEq((QilBinary)n),
QilNodeType.Gt => CheckGt((QilBinary)n),
QilNodeType.Ge => CheckGe((QilBinary)n),
QilNodeType.Lt => CheckLt((QilBinary)n),
QilNodeType.Le => CheckLe((QilBinary)n),
QilNodeType.Is => CheckIs((QilBinary)n),
QilNodeType.After => CheckAfter((QilBinary)n),
QilNodeType.Before => CheckBefore((QilBinary)n),
QilNodeType.Loop => CheckLoop((QilLoop)n),
QilNodeType.Filter => CheckFilter((QilLoop)n),
QilNodeType.Sort => CheckSort((QilLoop)n),
QilNodeType.SortKey => CheckSortKey((QilSortKey)n),
QilNodeType.DocOrderDistinct => CheckDocOrderDistinct((QilUnary)n),
QilNodeType.Function => CheckFunction((QilFunction)n),
QilNodeType.Invoke => CheckInvoke((QilInvoke)n),
QilNodeType.Content => CheckContent((QilUnary)n),
QilNodeType.Attribute => CheckAttribute((QilBinary)n),
QilNodeType.Parent => CheckParent((QilUnary)n),
QilNodeType.Root => CheckRoot((QilUnary)n),
QilNodeType.XmlContext => CheckXmlContext(n),
QilNodeType.Descendant => CheckDescendant((QilUnary)n),
QilNodeType.DescendantOrSelf => CheckDescendantOrSelf((QilUnary)n),
QilNodeType.Ancestor => CheckAncestor((QilUnary)n),
QilNodeType.AncestorOrSelf => CheckAncestorOrSelf((QilUnary)n),
QilNodeType.Preceding => CheckPreceding((QilUnary)n),
QilNodeType.FollowingSibling => CheckFollowingSibling((QilUnary)n),
QilNodeType.PrecedingSibling => CheckPrecedingSibling((QilUnary)n),
QilNodeType.NodeRange => CheckNodeRange((QilBinary)n),
QilNodeType.Deref => CheckDeref((QilBinary)n),
QilNodeType.ElementCtor => CheckElementCtor((QilBinary)n),
QilNodeType.AttributeCtor => CheckAttributeCtor((QilBinary)n),
QilNodeType.CommentCtor => CheckCommentCtor((QilUnary)n),
QilNodeType.PICtor => CheckPICtor((QilBinary)n),
QilNodeType.TextCtor => CheckTextCtor((QilUnary)n),
QilNodeType.RawTextCtor => CheckRawTextCtor((QilUnary)n),
QilNodeType.DocumentCtor => CheckDocumentCtor((QilUnary)n),
QilNodeType.NamespaceDecl => CheckNamespaceDecl((QilBinary)n),
QilNodeType.RtfCtor => CheckRtfCtor((QilBinary)n),
QilNodeType.NameOf => CheckNameOf((QilUnary)n),
QilNodeType.LocalNameOf => CheckLocalNameOf((QilUnary)n),
QilNodeType.NamespaceUriOf => CheckNamespaceUriOf((QilUnary)n),
QilNodeType.PrefixOf => CheckPrefixOf((QilUnary)n),
QilNodeType.TypeAssert => CheckTypeAssert((QilTargetType)n),
QilNodeType.IsType => CheckIsType((QilTargetType)n),
QilNodeType.IsEmpty => CheckIsEmpty((QilUnary)n),
QilNodeType.XPathNodeValue => CheckXPathNodeValue((QilUnary)n),
QilNodeType.XPathFollowing => CheckXPathFollowing((QilUnary)n),
QilNodeType.XPathPreceding => CheckXPathPreceding((QilUnary)n),
QilNodeType.XPathNamespace => CheckXPathNamespace((QilUnary)n),
QilNodeType.XsltGenerateId => CheckXsltGenerateId((QilUnary)n),
QilNodeType.XsltInvokeLateBound => CheckXsltInvokeLateBound((QilInvokeLateBound)n),
QilNodeType.XsltInvokeEarlyBound => CheckXsltInvokeEarlyBound((QilInvokeEarlyBound)n),
QilNodeType.XsltCopy => CheckXsltCopy((QilBinary)n),
QilNodeType.XsltCopyOf => CheckXsltCopyOf((QilUnary)n),
QilNodeType.XsltConvert => CheckXsltConvert((QilTargetType)n),
_ => CheckUnknown(n),
};
#endregion
}
#region meta
//-----------------------------------------------
// meta
//-----------------------------------------------
public XmlQueryType CheckQilExpression(QilExpression node)
{
Check(node[0].NodeType == QilNodeType.False || node[0].NodeType == QilNodeType.True, node, "IsDebug must either be True or False");
CheckLiteralValue(node[1], typeof(XmlWriterSettings));
CheckLiteralValue(node[2], typeof(IList<WhitespaceRule>));
CheckClassAndNodeType(node[3], typeof(QilList), QilNodeType.GlobalParameterList);
CheckClassAndNodeType(node[4], typeof(QilList), QilNodeType.GlobalVariableList);
CheckLiteralValue(node[5], typeof(IList<EarlyBoundInfo>));
CheckClassAndNodeType(node[6], typeof(QilList), QilNodeType.FunctionList);
return XmlQueryTypeFactory.ItemS;
}
public XmlQueryType CheckFunctionList(QilList node)
{
foreach (QilNode child in node)
CheckClassAndNodeType(child, typeof(QilFunction), QilNodeType.Function);
return node.XmlType;
}
public XmlQueryType CheckGlobalVariableList(QilList node)
{
foreach (QilNode child in node)
CheckClassAndNodeType(child, typeof(QilIterator), QilNodeType.Let);
return node.XmlType;
}
public XmlQueryType CheckGlobalParameterList(QilList node)
{
foreach (QilNode child in node)
{
CheckClassAndNodeType(child, typeof(QilParameter), QilNodeType.Parameter);
Check(((QilParameter)child).Name != null, child, "Global parameter's name is null");
}
return node.XmlType;
}
public XmlQueryType CheckActualParameterList(QilList node)
{
return node.XmlType;
}
public XmlQueryType CheckFormalParameterList(QilList node)
{
foreach (QilNode child in node)
CheckClassAndNodeType(child, typeof(QilParameter), QilNodeType.Parameter);
return node.XmlType;
}
public XmlQueryType CheckSortKeyList(QilList node)
{
foreach (QilNode child in node)
CheckClassAndNodeType(child, typeof(QilSortKey), QilNodeType.SortKey);
return node.XmlType;
}
public XmlQueryType CheckBranchList(QilList node)
{
return node.XmlType;
}
public XmlQueryType CheckOptimizeBarrier(QilUnary node)
{
return node.Child.XmlType;
}
public XmlQueryType CheckUnknown(QilNode node)
{
return node.XmlType;
}
#endregion // meta
#region specials
//-----------------------------------------------
// specials
//-----------------------------------------------
public XmlQueryType CheckDataSource(QilDataSource node)
{
CheckXmlType(node.Name, XmlQueryTypeFactory.StringX);
CheckXmlType(node.BaseUri, XmlQueryTypeFactory.StringX);
return XmlQueryTypeFactory.NodeNotRtfQ;
}
public XmlQueryType CheckNop(QilUnary node)
{
return node.Child.XmlType;
}
public XmlQueryType CheckError(QilUnary node)
{
CheckXmlType(node.Child, XmlQueryTypeFactory.StringX);
return XmlQueryTypeFactory.None;
}
public XmlQueryType CheckWarning(QilUnary node)
{
CheckXmlType(node.Child, XmlQueryTypeFactory.StringX);
return XmlQueryTypeFactory.Empty;
}
#endregion // specials
#region variables
//-----------------------------------------------
// variables
//-----------------------------------------------
public XmlQueryType CheckFor(QilIterator node)
{
return node.Binding.XmlType.Prime;
}
public XmlQueryType CheckLet(QilIterator node)
{
return node.Binding.XmlType;
}
public XmlQueryType CheckParameter(QilParameter node)
{
Check(node.Binding == null || node.Binding.XmlType.IsSubtypeOf(node.XmlType), node, "Parameter binding's xml type must be a subtype of the parameter's type");
return node.XmlType;
}
public XmlQueryType CheckPositionOf(QilUnary node)
{
return XmlQueryTypeFactory.IntX;
}
#endregion // variables
#region literals
//-----------------------------------------------
// literals
//-----------------------------------------------
public XmlQueryType CheckTrue(QilNode node)
{
return XmlQueryTypeFactory.BooleanX;
}
public XmlQueryType CheckFalse(QilNode node)
{
return XmlQueryTypeFactory.BooleanX;
}
public XmlQueryType CheckLiteralString(QilLiteral node)
{
CheckLiteralValue(node, typeof(string));
return XmlQueryTypeFactory.StringX;
}
public XmlQueryType CheckLiteralInt32(QilLiteral node)
{
CheckLiteralValue(node, typeof(int));
return XmlQueryTypeFactory.IntX;
}
public XmlQueryType CheckLiteralInt64(QilLiteral node)
{
CheckLiteralValue(node, typeof(long));
return XmlQueryTypeFactory.IntegerX;
}
public XmlQueryType CheckLiteralDouble(QilLiteral node)
{
CheckLiteralValue(node, typeof(double));
return XmlQueryTypeFactory.DoubleX;
}
public XmlQueryType CheckLiteralDecimal(QilLiteral node)
{
CheckLiteralValue(node, typeof(decimal));
return XmlQueryTypeFactory.DecimalX;
}
public XmlQueryType CheckLiteralQName(QilName node)
{
CheckLiteralValue(node, typeof(QilName));
// BUGBUG: Xslt constructs invalid QNames, so don't check this
//Check(ValidateNames.ValidateName(node.Prefix, node.LocalName, node.NamespaceUri, XPathNodeType.Element, ValidateNames.Flags.All), node, "QName is not valid");
return XmlQueryTypeFactory.QNameX;
}
public XmlQueryType CheckLiteralType(QilLiteral node)
{
CheckLiteralValue(node, typeof(XmlQueryType));
return (XmlQueryType)node;
}
public XmlQueryType CheckLiteralObject(QilLiteral node)
{
Check(node.Value != null, node, "Literal value is null");
return XmlQueryTypeFactory.ItemS;
}
#endregion // literals
#region boolean operators
//-----------------------------------------------
// boolean operators
//-----------------------------------------------
public XmlQueryType CheckAnd(QilBinary node)
{
CheckXmlType(node.Left, XmlQueryTypeFactory.BooleanX);
CheckXmlType(node.Right, XmlQueryTypeFactory.BooleanX);
return XmlQueryTypeFactory.BooleanX;
}
public XmlQueryType CheckOr(QilBinary node)
{
return CheckAnd(node);
}
public XmlQueryType CheckNot(QilUnary node)
{
CheckXmlType(node.Child, XmlQueryTypeFactory.BooleanX);
return XmlQueryTypeFactory.BooleanX;
}
#endregion // boolean operators
#region choice
//-----------------------------------------------
// choice
//-----------------------------------------------
public XmlQueryType CheckConditional(QilTernary node)
{
CheckXmlType(node.Left, XmlQueryTypeFactory.BooleanX);
return XmlQueryTypeFactory.Choice(node.Center.XmlType, node.Right.XmlType);
}
public XmlQueryType CheckChoice(QilChoice node)
{
CheckXmlType(node.Expression, XmlQueryTypeFactory.IntX);
CheckClassAndNodeType(node.Branches, typeof(QilList), QilNodeType.BranchList);
Check(node.Branches.Count > 0, node, "Choice must have at least one branch");
return node.Branches.XmlType;
}
#endregion // choice
#region collection operators
//-----------------------------------------------
// collection operators
//-----------------------------------------------
public XmlQueryType CheckLength(QilUnary node)
{
return XmlQueryTypeFactory.IntX;
}
public XmlQueryType CheckSequence(QilList node)
{
return node.XmlType;
}
public XmlQueryType CheckUnion(QilBinary node)
{
CheckXmlType(node.Left, XmlQueryTypeFactory.NodeNotRtfS);
CheckXmlType(node.Right, XmlQueryTypeFactory.NodeNotRtfS);
return DistinctType(XmlQueryTypeFactory.Sequence(node.Left.XmlType, node.Right.XmlType));
}
public XmlQueryType CheckIntersection(QilBinary node)
{
return CheckUnion(node);
}
public XmlQueryType CheckDifference(QilBinary node)
{
CheckXmlType(node.Left, XmlQueryTypeFactory.NodeNotRtfS);
CheckXmlType(node.Right, XmlQueryTypeFactory.NodeNotRtfS);
return XmlQueryTypeFactory.AtMost(node.Left.XmlType, node.Left.XmlType.Cardinality);
}
public XmlQueryType CheckAverage(QilUnary node)
{
XmlQueryType xmlType = node.Child.XmlType;
CheckNumericXS(node.Child);
return XmlQueryTypeFactory.PrimeProduct(xmlType, xmlType.MaybeEmpty ? XmlQueryCardinality.ZeroOrOne : XmlQueryCardinality.One);
}
public XmlQueryType CheckSum(QilUnary node)
{
return CheckAverage(node);
}
public XmlQueryType CheckMinimum(QilUnary node)
{
return CheckAverage(node);
}
public XmlQueryType CheckMaximum(QilUnary node)
{
return CheckAverage(node);
}
#endregion // collection operators
#region arithmetic operators
//-----------------------------------------------
// arithmetic operators
//-----------------------------------------------
public XmlQueryType CheckNegate(QilUnary node)
{
CheckNumericX(node.Child);
return node.Child.XmlType;
}
public XmlQueryType CheckAdd(QilBinary node)
{
CheckNumericX(node.Left);
CheckNumericX(node.Right);
CheckNotDisjoint(node);
return node.Left.XmlType.TypeCode == XmlTypeCode.None ? node.Right.XmlType : node.Left.XmlType;
}
public XmlQueryType CheckSubtract(QilBinary node)
{
return CheckAdd(node);
}
public XmlQueryType CheckMultiply(QilBinary node)
{
return CheckAdd(node);
}
public XmlQueryType CheckDivide(QilBinary node)
{
return CheckAdd(node);
}
public XmlQueryType CheckModulo(QilBinary node)
{
return CheckAdd(node);
}
#endregion // arithmetic operators
#region string operators
//-----------------------------------------------
// string operators
//-----------------------------------------------
public XmlQueryType CheckStrLength(QilUnary node)
{
CheckXmlType(node.Child, XmlQueryTypeFactory.StringX);
return XmlQueryTypeFactory.IntX;
}
public XmlQueryType CheckStrConcat(QilStrConcat node)
{
CheckXmlType(node.Delimiter, XmlQueryTypeFactory.StringX);
CheckXmlType(node.Values, XmlQueryTypeFactory.StringXS);
return XmlQueryTypeFactory.StringX;
}
public XmlQueryType CheckStrParseQName(QilBinary node)
{
CheckXmlType(node.Left, XmlQueryTypeFactory.StringX);
Check(node.Right.XmlType.IsSubtypeOf(XmlQueryTypeFactory.StringX) || node.Right.XmlType.IsSubtypeOf(XmlQueryTypeFactory.NamespaceS),
node, "StrParseQName must take either a string or a list of namespace as its second argument");
return XmlQueryTypeFactory.QNameX;
}
#endregion // string operators
#region value comparison operators
//-----------------------------------------------
// value comparison operators
//-----------------------------------------------
public XmlQueryType CheckNe(QilBinary node)
{
CheckAtomicX(node.Left);
CheckAtomicX(node.Right);
CheckNotDisjoint(node);
return XmlQueryTypeFactory.BooleanX;
}
public XmlQueryType CheckEq(QilBinary node)
{
return CheckNe(node);
}
public XmlQueryType CheckGt(QilBinary node)
{
return CheckNe(node);
}
public XmlQueryType CheckGe(QilBinary node)
{
return CheckNe(node);
}
public XmlQueryType CheckLt(QilBinary node)
{
return CheckNe(node);
}
public XmlQueryType CheckLe(QilBinary node)
{
return CheckNe(node);
}
#endregion // value comparison operators
#region node comparison operators
//-----------------------------------------------
// node comparison operators
//-----------------------------------------------
public XmlQueryType CheckIs(QilBinary node)
{
CheckXmlType(node.Left, XmlQueryTypeFactory.NodeNotRtf);
CheckXmlType(node.Right, XmlQueryTypeFactory.NodeNotRtf);
return XmlQueryTypeFactory.BooleanX;
}
public XmlQueryType CheckAfter(QilBinary node)
{
return CheckIs(node);
}
public XmlQueryType CheckBefore(QilBinary node)
{
return CheckIs(node);
}
#endregion // node comparison operators
#region loops
//-----------------------------------------------
// loops
//-----------------------------------------------
public XmlQueryType CheckLoop(QilLoop node)
{
CheckClass(node[0], typeof(QilIterator));
Check(node.Variable.NodeType == QilNodeType.For || node.Variable.NodeType == QilNodeType.Let, node, "Loop variable must be a For or Let iterator");
XmlQueryType bodyType = node.Body.XmlType;
XmlQueryCardinality variableCard = node.Variable.NodeType == QilNodeType.Let ? XmlQueryCardinality.One : node.Variable.Binding.XmlType.Cardinality;
// Loops do not preserve DocOrderDistinct
return XmlQueryTypeFactory.PrimeProduct(bodyType, variableCard * bodyType.Cardinality);
}
public XmlQueryType CheckFilter(QilLoop node)
{
CheckClass(node[0], typeof(QilIterator));
Check(node.Variable.NodeType == QilNodeType.For || node.Variable.NodeType == QilNodeType.Let, node, "Filter variable must be a For or Let iterator");
CheckXmlType(node.Body, XmlQueryTypeFactory.BooleanX);
// Attempt to restrict filter's type by checking condition
XmlQueryType filterType = FindFilterType(node.Variable, node.Body);
if (filterType != null)
return filterType;
return XmlQueryTypeFactory.AtMost(node.Variable.Binding.XmlType, node.Variable.Binding.XmlType.Cardinality);
}
#endregion // loops
#region sorting
//-----------------------------------------------
// sorting
//-----------------------------------------------
public XmlQueryType CheckSort(QilLoop node)
{
XmlQueryType varType = node.Variable.Binding.XmlType;
CheckClassAndNodeType(node[0], typeof(QilIterator), QilNodeType.For);
CheckClassAndNodeType(node[1], typeof(QilList), QilNodeType.SortKeyList);
// Sort does not preserve DocOrderDistinct
return XmlQueryTypeFactory.PrimeProduct(varType, varType.Cardinality);
}
public XmlQueryType CheckSortKey(QilSortKey node)
{
CheckAtomicX(node.Key);
CheckXmlType(node.Collation, XmlQueryTypeFactory.StringX);
return node.Key.XmlType;
}
public XmlQueryType CheckDocOrderDistinct(QilUnary node)
{
CheckXmlType(node.Child, XmlQueryTypeFactory.NodeNotRtfS);
return DistinctType(node.Child.XmlType);
}
#endregion // sorting
#region function definition and invocation
//-----------------------------------------------
// function definition and invocation
//-----------------------------------------------
public XmlQueryType CheckFunction(QilFunction node)
{
CheckClassAndNodeType(node[0], typeof(QilList), QilNodeType.FormalParameterList);
Check(node[2].NodeType == QilNodeType.False || node[2].NodeType == QilNodeType.True, node, "SideEffects must either be True or False");
Check(node.Definition.XmlType.IsSubtypeOf(node.XmlType), node, "Function definition's xml type must be a subtype of the function's return type");
return node.XmlType;
}
public XmlQueryType CheckInvoke(QilInvoke node)
{
#if DEBUG
CheckClassAndNodeType(node[1], typeof(QilList), QilNodeType.ActualParameterList);
QilList actualArgs = node.Arguments;
QilList formalArgs = node.Function.Arguments;
Check(actualArgs.Count == formalArgs.Count, actualArgs, "Invoke argument count must match function's argument count");
for (int i = 0; i < actualArgs.Count; i++)
Check(actualArgs[i].XmlType.IsSubtypeOf(formalArgs[i].XmlType), actualArgs[i], "Invoke argument must be a subtype of the invoked function's argument");
#endif
return node.Function.XmlType;
}
#endregion // function definition and invocation
#region XML navigation
//-----------------------------------------------
// XML navigation
//-----------------------------------------------
public XmlQueryType CheckContent(QilUnary node)
{
CheckXmlType(node.Child, XmlQueryTypeFactory.NodeNotRtf);
return XmlQueryTypeFactory.AttributeOrContentS;
}
public XmlQueryType CheckAttribute(QilBinary node)
{
CheckXmlType(node.Left, XmlQueryTypeFactory.NodeNotRtf);
CheckXmlType(node.Right, XmlQueryTypeFactory.QNameX);
return XmlQueryTypeFactory.AttributeQ;
}
public XmlQueryType CheckParent(QilUnary node)
{
CheckXmlType(node.Child, XmlQueryTypeFactory.NodeNotRtf);
return XmlQueryTypeFactory.DocumentOrElementQ;
}
public XmlQueryType CheckRoot(QilUnary node)
{
CheckXmlType(node.Child, XmlQueryTypeFactory.NodeNotRtf);
return XmlQueryTypeFactory.NodeNotRtf;
}
public XmlQueryType CheckXmlContext(QilNode node)
{
return XmlQueryTypeFactory.NodeNotRtf;
}
public XmlQueryType CheckDescendant(QilUnary node)
{
CheckXmlType(node.Child, XmlQueryTypeFactory.NodeNotRtf);
return XmlQueryTypeFactory.ContentS;
}
public XmlQueryType CheckDescendantOrSelf(QilUnary node)
{
CheckXmlType(node.Child, XmlQueryTypeFactory.NodeNotRtf);
return XmlQueryTypeFactory.Choice(node.Child.XmlType, XmlQueryTypeFactory.ContentS);
}
public XmlQueryType CheckAncestor(QilUnary node)
{
CheckXmlType(node.Child, XmlQueryTypeFactory.NodeNotRtf);
return XmlQueryTypeFactory.DocumentOrElementS;
}
public XmlQueryType CheckAncestorOrSelf(QilUnary node)
{
CheckXmlType(node.Child, XmlQueryTypeFactory.NodeNotRtf);
return XmlQueryTypeFactory.Choice(node.Child.XmlType, XmlQueryTypeFactory.DocumentOrElementS);
}
public XmlQueryType CheckPreceding(QilUnary node)
{
CheckXmlType(node.Child, XmlQueryTypeFactory.NodeNotRtf);
return XmlQueryTypeFactory.DocumentOrContentS;
}
public XmlQueryType CheckFollowingSibling(QilUnary node)
{
CheckXmlType(node.Child, XmlQueryTypeFactory.NodeNotRtf);
return XmlQueryTypeFactory.ContentS;
}
public XmlQueryType CheckPrecedingSibling(QilUnary node)
{
CheckXmlType(node.Child, XmlQueryTypeFactory.NodeNotRtf);
return XmlQueryTypeFactory.ContentS;
}
public XmlQueryType CheckNodeRange(QilBinary node)
{
CheckXmlType(node.Left, XmlQueryTypeFactory.NodeNotRtf);
CheckXmlType(node.Right, XmlQueryTypeFactory.NodeNotRtf);
return XmlQueryTypeFactory.Choice(node.Left.XmlType, XmlQueryTypeFactory.ContentS, node.Right.XmlType);
}
public XmlQueryType CheckDeref(QilBinary node)
{
CheckXmlType(node.Left, XmlQueryTypeFactory.NodeNotRtf);
CheckXmlType(node.Right, XmlQueryTypeFactory.StringX);
return XmlQueryTypeFactory.ElementS;
}
#endregion // XML navigation
#region XML construction
//-----------------------------------------------
// XML construction
//-----------------------------------------------
public XmlQueryType CheckElementCtor(QilBinary node)
{
CheckXmlType(node.Left, XmlQueryTypeFactory.QNameX);
CheckXmlType(node.Right, XmlQueryTypeFactory.NodeNotRtfS);
return XmlQueryTypeFactory.UntypedElement;
}
public XmlQueryType CheckAttributeCtor(QilBinary node)
{
CheckXmlType(node.Left, XmlQueryTypeFactory.QNameX);
CheckXmlType(node.Right, XmlQueryTypeFactory.NodeNotRtfS);
return XmlQueryTypeFactory.UntypedAttribute;
}
public XmlQueryType CheckCommentCtor(QilUnary node)
{
CheckXmlType(node.Child, XmlQueryTypeFactory.NodeNotRtfS);
return XmlQueryTypeFactory.Comment;
}
public XmlQueryType CheckPICtor(QilBinary node)
{
CheckXmlType(node.Left, XmlQueryTypeFactory.StringX);
CheckXmlType(node.Right, XmlQueryTypeFactory.NodeNotRtfS);
return XmlQueryTypeFactory.PI;
}
public XmlQueryType CheckTextCtor(QilUnary node)
{
CheckXmlType(node.Child, XmlQueryTypeFactory.StringX);
return XmlQueryTypeFactory.Text;
}
public XmlQueryType CheckRawTextCtor(QilUnary node)
{
CheckXmlType(node.Child, XmlQueryTypeFactory.StringX);
return XmlQueryTypeFactory.Text;
}
public XmlQueryType CheckDocumentCtor(QilUnary node)
{
CheckXmlType(node.Child, XmlQueryTypeFactory.NodeNotRtfS);
return XmlQueryTypeFactory.UntypedDocument;
}
public XmlQueryType CheckNamespaceDecl(QilBinary node)
{
CheckXmlType(node.Left, XmlQueryTypeFactory.StringX);
CheckXmlType(node.Right, XmlQueryTypeFactory.StringX);
return XmlQueryTypeFactory.Namespace;
}
public XmlQueryType CheckRtfCtor(QilBinary node)
{
CheckXmlType(node.Left, XmlQueryTypeFactory.NodeNotRtfS);
CheckClassAndNodeType(node.Right, typeof(QilLiteral), QilNodeType.LiteralString);
return XmlQueryTypeFactory.Node;
}
#endregion // XML construction
#region Node properties
//-----------------------------------------------
// Node properties
//-----------------------------------------------
public XmlQueryType CheckNameOf(QilUnary node)
{
CheckXmlType(node.Child, XmlQueryTypeFactory.Node);
return XmlQueryTypeFactory.QNameX;
}
public XmlQueryType CheckLocalNameOf(QilUnary node)
{
CheckXmlType(node.Child, XmlQueryTypeFactory.Node);
return XmlQueryTypeFactory.StringX;
}
public XmlQueryType CheckNamespaceUriOf(QilUnary node)
{
CheckXmlType(node.Child, XmlQueryTypeFactory.Node);
return XmlQueryTypeFactory.StringX;
}
public XmlQueryType CheckPrefixOf(QilUnary node)
{
CheckXmlType(node.Child, XmlQueryTypeFactory.Node);
return XmlQueryTypeFactory.StringX;
}
#endregion // Node properties
#region Copy operators
#endregion // Copy operators
#region Type operators
//-----------------------------------------------
// Type operators
//-----------------------------------------------
public XmlQueryType CheckTypeAssert(QilTargetType node)
{
CheckClassAndNodeType(node[1], typeof(QilLiteral), QilNodeType.LiteralType);
return node.TargetType;
}
public XmlQueryType CheckIsType(QilTargetType node)
{
CheckClassAndNodeType(node[1], typeof(QilLiteral), QilNodeType.LiteralType);
return XmlQueryTypeFactory.BooleanX;
}
public XmlQueryType CheckIsEmpty(QilUnary node)
{
return XmlQueryTypeFactory.BooleanX;
}
#endregion // Type operators
#region XPath operators
//-----------------------------------------------
// XPath operators
//-----------------------------------------------
public XmlQueryType CheckXPathNodeValue(QilUnary node)
{
CheckXmlType(node.Child, XmlQueryTypeFactory.NodeS);
return XmlQueryTypeFactory.StringX;
}
public XmlQueryType CheckXPathFollowing(QilUnary node)
{
CheckXmlType(node.Child, XmlQueryTypeFactory.NodeNotRtf);
return XmlQueryTypeFactory.ContentS;
}
public XmlQueryType CheckXPathPreceding(QilUnary node)
{
CheckXmlType(node.Child, XmlQueryTypeFactory.NodeNotRtf);
return XmlQueryTypeFactory.ContentS;
}
public XmlQueryType CheckXPathNamespace(QilUnary node)
{
CheckXmlType(node.Child, XmlQueryTypeFactory.NodeNotRtf);
return XmlQueryTypeFactory.NamespaceS;
}
#endregion // XPath operators
#region XSLT
//-----------------------------------------------
// XSLT
//-----------------------------------------------
public XmlQueryType CheckXsltGenerateId(QilUnary node)
{
CheckXmlType(node.Child, XmlQueryTypeFactory.NodeNotRtfS);
return XmlQueryTypeFactory.StringX;
}
public XmlQueryType CheckXsltInvokeLateBound(QilInvokeLateBound node)
{
CheckLiteralValue(node[0], typeof(QilName));
CheckClassAndNodeType(node[1], typeof(QilList), QilNodeType.ActualParameterList);
return XmlQueryTypeFactory.ItemS;
}
public XmlQueryType CheckXsltInvokeEarlyBound(QilInvokeEarlyBound node)
{
#if DEBUG
CheckLiteralValue(node[0], typeof(QilName));
CheckLiteralValue(node[1], typeof(MethodInfo));
CheckClassAndNodeType(node[2], typeof(QilList), QilNodeType.ActualParameterList);
XmlExtensionFunction extFunc = new XmlExtensionFunction(node.Name.LocalName, node.Name.NamespaceUri, node.ClrMethod);
QilList actualArgs = node.Arguments;
Check(actualArgs.Count == extFunc.Method.GetParameters().Length, actualArgs, "InvokeEarlyBound argument count must match function's argument count");
for (int i = 0; i < actualArgs.Count; i++)
{
Check(actualArgs[i].XmlType.IsSubtypeOf(extFunc.GetXmlArgumentType(i)), actualArgs[i], "InvokeEarlyBound argument must be a subtype of the invoked function's argument type");
}
#endif
return node.XmlType;
}
public XmlQueryType CheckXsltCopy(QilBinary node)
{
CheckXmlType(node.Left, XmlQueryTypeFactory.NodeNotRtf);
CheckXmlType(node.Right, XmlQueryTypeFactory.NodeS);
return XmlQueryTypeFactory.Choice(node.Left.XmlType, node.Right.XmlType);
}
public XmlQueryType CheckXsltCopyOf(QilUnary node)
{
CheckXmlType(node.Child, XmlQueryTypeFactory.Node);
if ((node.Child.XmlType.NodeKinds & XmlNodeKindFlags.Document) != 0)
return XmlQueryTypeFactory.NodeNotRtfS;
return node.Child.XmlType;
}
public XmlQueryType CheckXsltConvert(QilTargetType node)
{
CheckClassAndNodeType(node[1], typeof(QilLiteral), QilNodeType.LiteralType);
return node.TargetType;
}
#endregion // Xslt operators
//-----------------------------------------------
// Helper functions
//-----------------------------------------------
[Conditional("DEBUG")]
private void Check(bool value, QilNode node, string message)
{
if (!value)
QilValidationVisitor.SetError(node, message);
}
[Conditional("DEBUG")]
private void CheckLiteralValue(QilNode node, Type clrTypeValue)
{
Check(node is QilLiteral, node, "Node must be instance of QilLiteral");
Type clrType = ((QilLiteral)node).Value.GetType();
Check(clrTypeValue.IsAssignableFrom(clrType), node, "Literal value must be of type " + clrTypeValue.Name);
}
[Conditional("DEBUG")]
private void CheckClass(QilNode node, Type clrTypeClass)
{
Check(clrTypeClass.IsAssignableFrom(node.GetType()), node, "Node must be instance of " + clrTypeClass.Name);
}
[Conditional("DEBUG")]
private void CheckClassAndNodeType(QilNode node, Type clrTypeClass, QilNodeType nodeType)
{
CheckClass(node, clrTypeClass);
Check(node.NodeType == nodeType, node, "Node must have QilNodeType." + nodeType);
}
[Conditional("DEBUG")]
private void CheckXmlType(QilNode node, XmlQueryType xmlType)
{
Check(node.XmlType.IsSubtypeOf(xmlType), node, "Node's type " + node.XmlType + " is not a subtype of " + xmlType);
}
[Conditional("DEBUG")]
private void CheckNumericX(QilNode node)
{
Check(node.XmlType.IsNumeric && node.XmlType.IsSingleton && node.XmlType.IsStrict, node, "Node's type " + node.XmlType + " must be a strict singleton numeric type");
}
[Conditional("DEBUG")]
private void CheckNumericXS(QilNode node)
{
Check(node.XmlType.IsNumeric && node.XmlType.IsStrict, node, "Node's type " + node.XmlType + " must be a strict numeric type");
}
[Conditional("DEBUG")]
private void CheckAtomicX(QilNode node)
{
Check(node.XmlType.IsAtomicValue && node.XmlType.IsStrict, node, "Node's type " + node.XmlType + " must be a strict atomic value type");
}
[Conditional("DEBUG")]
private void CheckNotDisjoint(QilBinary node)
{
Check(node.Left.XmlType.IsSubtypeOf(node.Right.XmlType) || node.Right.XmlType.IsSubtypeOf(node.Left.XmlType), node,
"Node must not have arguments with disjoint types " + node.Left.XmlType + " and " + node.Right.XmlType);
}
private XmlQueryType DistinctType(XmlQueryType type)
{
if (type.Cardinality == XmlQueryCardinality.More)
return XmlQueryTypeFactory.PrimeProduct(type, XmlQueryCardinality.OneOrMore);
if (type.Cardinality == XmlQueryCardinality.NotOne)
return XmlQueryTypeFactory.PrimeProduct(type, XmlQueryCardinality.ZeroOrMore);
return type;
}
private XmlQueryType FindFilterType(QilIterator variable, QilNode body)
{
XmlQueryType leftType;
QilBinary binary;
if (body.XmlType.TypeCode == XmlTypeCode.None)
return XmlQueryTypeFactory.None;
switch (body.NodeType)
{
case QilNodeType.False:
return XmlQueryTypeFactory.Empty;
case QilNodeType.IsType:
// If testing the type of "variable", then filter type can be restricted
if ((object)((QilTargetType)body).Source == (object)variable)
return XmlQueryTypeFactory.AtMost(((QilTargetType)body).TargetType, variable.Binding.XmlType.Cardinality);
break;
case QilNodeType.And:
// Both And conditions can be used to restrict filter's type
leftType = FindFilterType(variable, ((QilBinary)body).Left);
if (leftType != null)
return leftType;
return FindFilterType(variable, ((QilBinary)body).Right);
case QilNodeType.Eq:
// Restrict cardinality if position($iterator) = $pos is found
binary = (QilBinary)body;
if (binary.Left.NodeType == QilNodeType.PositionOf)
{
if ((object)((QilUnary)binary.Left).Child == (object)variable)
return XmlQueryTypeFactory.AtMost(variable.Binding.XmlType, XmlQueryCardinality.ZeroOrOne);
}
break;
}
return null;
}
}
}
| |
// 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.Collections.Generic;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using Microsoft.Build.Framework;
using Microsoft.Build.BuildEngine.Shared;
namespace Microsoft.Build.BuildEngine
{
/// <summary>
/// This class is a container for node status
/// </summary>
internal class NodeStatus
{
#region Constructors
/// <summary>
/// Default constructor creating a NodeStatus
/// </summary>
internal NodeStatus
(
int requestId,
bool isActive,
int queueDepth,
long lastTaskActivityTimeStamp,
long lastEngineActivityTimeStamp,
bool isLaunchInProgress
)
{
this.requestId = requestId;
this.isActive = isActive;
this.queueDepth = queueDepth;
this.lastTaskActivityTimeStamp = lastTaskActivityTimeStamp;
this.lastEngineActivityTimeStamp = lastEngineActivityTimeStamp;
this.isLaunchInProgress = isLaunchInProgress;
this.unhandledException = null;
this.statusTimeStamp = DateTime.Now.Ticks;
}
/// <summary>
/// Create a node status describing an unhandled error
/// </summary>
internal NodeStatus
(
Exception unhandledException
)
{
this.requestId = UnrequestedStatus;
this.isActive = true;
this.isLaunchInProgress = false;
this.unhandledException = unhandledException;
this.statusTimeStamp = DateTime.Now.Ticks;
}
/// <summary>
/// Create a node status indicating that breadth first traversal should be used
/// </summary>
internal NodeStatus
(
bool useBreadthFirstTraversal
)
{
this.requestId = UnrequestedStatus;
this.isActive = true;
this.isLaunchInProgress = false;
this.unhandledException = null;
this.traversalType = useBreadthFirstTraversal;
}
/// <summary>
/// Create a node status indicating that node process has exited
/// </summary>
internal NodeStatus
(
int requestId
)
{
this.requestId = requestId;
this.isActive = true;
this.isLaunchInProgress = false;
this.unhandledException = null;
this.hasExited = true;
}
#endregion
#region Properties
/// <summary>
/// The time period for which the node has been idle when the status report was filled out
/// </summary>
internal long TimeSinceLastTaskActivity
{
get
{
return (statusTimeStamp - lastTaskActivityTimeStamp);
}
}
/// <summary>
/// The time period for which the node has been idle when the status report was filled out
/// </summary>
internal long TimeSinceLastLoopActivity
{
get
{
return (statusTimeStamp - lastEngineActivityTimeStamp);
}
}
/// <summary>
/// The time stamp at which the node was last active
/// </summary>
internal long LastTaskActivity
{
get
{
return lastTaskActivityTimeStamp;
}
}
/// <summary>
/// The time stamp at which there was activity in the node's build loop
/// </summary>
internal long LastLoopActivity
{
get
{
return lastEngineActivityTimeStamp;
}
}
/// <summary>
/// True if the node is active (i.e. has been launched and can accept commands)
/// </summary>
internal bool IsActive
{
get
{
return this.isActive;
}
}
/// <summary>
/// True if the node process is no longer alive
/// </summary>
internal bool HasExited
{
get
{
return this.hasExited;
}
}
/// <summary>
/// The token of the request to which this is a response (-1 if status is unrequested)
/// </summary>
internal int RequestId
{
get
{
return this.requestId;
}
}
/// <summary>
/// The number of requests that need to be processed
/// </summary>
internal int QueueDepth
{
get
{
return this.queueDepth;
}
}
/// <summary>
/// The state of the targets which are in progress on the node
/// </summary>
internal TargetInProgessState [] StateOfInProgressTargets
{
get
{
return this.stateOfInProgressTargets;
}
set
{
this.stateOfInProgressTargets = value;
}
}
/// <summary>
/// True if the node is in the process of being launched, but is not yet active
/// </summary>
internal bool IsLaunchInProgress
{
get
{
return isLaunchInProgress;
}
}
/// <summary>
/// Returns the exception that occured on the node
/// </summary>
internal Exception UnhandledException
{
get
{
return unhandledException;
}
}
internal bool TraversalType
{
get
{
return traversalType;
}
}
#endregion
#region Data
private long statusTimeStamp; // the timestamp indicating when this status structure was filled out
private int requestId; // the token of the request to which this is a response (-1 if status is unrequested)
private bool isActive; // is the node active
private bool isLaunchInProgress; // is the node in the process of being launched
private int queueDepth; // the number of build request in the node's queue
private long lastTaskActivityTimeStamp; // the time stamp of the last task activity
private long lastEngineActivityTimeStamp; // the time stamp of the last engine activity
private TargetInProgessState[] stateOfInProgressTargets;
private Exception unhandledException; // unhandled exception
private bool traversalType; // if true use breadth first traversal
private bool hasExited; // if true the node process is no longer alive
private static BinaryFormatter formatter = new BinaryFormatter();
internal const int UnrequestedStatus = -1; // used to indicate that the node is generating status without request
#endregion
#region CustomSerializationToStream
internal void WriteToStream(BinaryWriter writer)
{
writer.Write(traversalType);
writer.Write((Int64)statusTimeStamp);
writer.Write((Int32)requestId);
writer.Write(isActive);
writer.Write(isLaunchInProgress);
writer.Write((Int32)queueDepth);
writer.Write((Int64)lastTaskActivityTimeStamp);
writer.Write((Int64)lastEngineActivityTimeStamp);
if (stateOfInProgressTargets == null)
{
writer.Write((byte)0);
}
else
{
writer.Write((byte)1);
writer.Write((Int32)stateOfInProgressTargets.Length);
for (int i = 0; i < stateOfInProgressTargets.Length; i++)
{
if (stateOfInProgressTargets[i] == null)
{
writer.Write((byte)0);
}
else
{
writer.Write((byte)1);
stateOfInProgressTargets[i].WriteToStream(writer);
}
}
}
if (unhandledException == null)
{
writer.Write((byte)0);
}
else
{
writer.Write((byte)1);
formatter.Serialize(writer.BaseStream, unhandledException);
}
}
internal static NodeStatus CreateFromStream(BinaryReader reader)
{
NodeStatus status = new NodeStatus(null);
status.traversalType = reader.ReadBoolean();
status.statusTimeStamp = reader.ReadInt64();
status.requestId = reader.ReadInt32();
status.isActive = reader.ReadBoolean();
status.isLaunchInProgress = reader.ReadBoolean();
status.queueDepth = reader.ReadInt32();
status.lastTaskActivityTimeStamp = reader.ReadInt64();
status.lastEngineActivityTimeStamp = reader.ReadInt64();
if (reader.ReadByte() == 0)
{
status.stateOfInProgressTargets = null;
}
else
{
int numberOfInProgressTargets = reader.ReadInt32();
status.stateOfInProgressTargets = new TargetInProgessState[numberOfInProgressTargets];
for (int i = 0; i < numberOfInProgressTargets; i++)
{
if (reader.ReadByte() == 0)
{
status.stateOfInProgressTargets[i] = null;
}
else
{
TargetInProgessState state = new TargetInProgessState();
state.CreateFromStream(reader);
status.stateOfInProgressTargets[i] = state;
}
}
}
if (reader.ReadByte() == 0)
{
status.unhandledException = null;
}
else
{
status.unhandledException = (Exception)formatter.Deserialize(reader.BaseStream);
}
return status;
}
#endregion
}
}
| |
//
// AdjustTimeDialog.cs
//
// Author:
// Ruben Vermeersch <ruben@savanne.be>
// Larry Ewing <lewing@novell.com>
// Stephane Delcroix <stephane@delcroix.org>
//
// Copyright (C) 2006-2010 Novell, Inc.
// Copyright (C) 2010 Ruben Vermeersch
// Copyright (C) 2006 Larry Ewing
// Copyright (C) 2006-2009 Stephane Delcroix
//
// 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 Gtk;
using Mono.Unix;
using FSpot.Core;
using FSpot.Database;
using FSpot.Widgets;
using Hyena;
namespace FSpot.UI.Dialog
{
public class AdjustTimeDialog : BuilderDialog
{
#pragma warning disable 649
[GtkBeans.Builder.Object] ScrolledWindow view_scrolled;
[GtkBeans.Builder.Object] ScrolledWindow tray_scrolled;
[GtkBeans.Builder.Object] Button ok_button;
[GtkBeans.Builder.Object] Button cancel_button;
[GtkBeans.Builder.Object] SpinButton photo_spin;
[GtkBeans.Builder.Object] Label name_label;
[GtkBeans.Builder.Object] Label old_label;
[GtkBeans.Builder.Object] Label count_label;
//[GtkBeans.Builder.Object] Gnome.DateEdit date_edit;
[GtkBeans.Builder.Object] Frame tray_frame;
[GtkBeans.Builder.Object] Gtk.Entry offset_entry;
[GtkBeans.Builder.Object] Gtk.CheckButton difference_check;
[GtkBeans.Builder.Object] Gtk.Frame action_frame;
[GtkBeans.Builder.Object] Gtk.Entry spacing_entry;
[GtkBeans.Builder.Object] Gtk.Label starting_label;
#pragma warning restore 649
IBrowsableCollection collection;
BrowsablePointer item;
CollectionGridView tray;
PhotoImageView view;
Db db;
TimeSpan gnome_dateedit_sucks;
public AdjustTimeDialog (Db db, IBrowsableCollection collection) : base ("AdjustTimeDialog.ui", "time_dialog")
{
this.db = db;
this.collection = collection;
view = new PhotoImageView (collection);
view_scrolled.Add (view);
item = view.Item;
item.Changed += HandleItemChanged;
item.MoveFirst ();
tray = new BrowseablePointerGridView (view.Item) {
MaxColumns = 1,
DisplayRatings = false,
DisplayTags = false,
DisplayDates = true
};
tray_scrolled.Add (tray);
//forward_button.Clicked += HandleForwardClicked;
//back_button.Clicked += HandleBackClicked;
ok_button.Clicked += HandleOkClicked;
cancel_button.Clicked += HandleCancelClicked;
photo_spin.ValueChanged += HandleSpinChanged;
photo_spin.SetIncrements (1.0, 1.0);
photo_spin.Adjustment.StepIncrement = 1.0;
photo_spin.Wrap = true;
//date_edit.TimeChanged += HandleTimeChanged;
//date_edit.DateChanged += HandleTimeChanged;
//Gtk.Entry entry = (Gtk.Entry)date_edit.Children[0];
//entry.Changed += HandleTimeChanged;
//entry = (Gtk.Entry)date_edit.Children[2];
//entry.Changed += HandleTimeChanged;
offset_entry.Changed += HandleOffsetChanged;
ShowAll ();
HandleCollectionChanged (collection);
spacing_entry.Changed += HandleSpacingChanged;
spacing_entry.Sensitive = !difference_check.Active;
difference_check.Toggled += HandleActionToggled;
}
//DateTime EditTime {
// get { return date_edit.Time - gnome_dateedit_sucks; }
//}
//TimeSpan Offset {
// get {
// Log.Debug ($"{date_time.Time} - {item.Current.Time} = {date_edit.Time - item.Current.Time}");
// return EditTime - item.Current.Time;
// }
// set {
// date_edit.Time = item.Current.Time - gnome_dateedit_sucks + value;
// }
//}
void HandleTimeChanged (object sender, EventArgs args)
{
//TimeSpan span = Offset;
//Log.Debug ($"time changed {span}");
//if (!offset_entry.HasFocus)
// offset_entry.Text = span.ToString ();
//starting_label.Text = "min.";
//difference_check.Label = string.Format (Catalog.GetString ("Shift all photos by {0}"), Offset);
}
void HandleItemChanged (object sender, BrowsablePointerChangedEventArgs args)
{
//back_button.Sensitive = (Item.Index > 0 && collection.Count > 0);
//forward_button.Sensitive = (Item.Index < collection.Count - 1);
//if (item.IsValid) {
// IPhoto curr_item = item.Current;
// name_label.Text = Uri.UnescapeDataString (curr_item.Name);
// old_label.Text = (curr_item.Time).ToString ();
// int i = collection.Count > 0 ? item.Index + 1 : 0;
// // Note for translators: This indicates the current photo is photo {0} of {1} out of photos
// count_label.Text = string.Format (Catalog.GetString ("{0} of {1}"), i, collection.Count);
// DateTime actual = curr_item.Time;
// date_edit.Time = actual;
// gnome_dateedit_sucks = date_edit.Time - actual;
//}
//HandleTimeChanged (this, EventArgs.Empty);
//photo_spin.Value = item.Index + 1;
}
void ShiftByDifference ()
{
//TimeSpan span = Offset;
//Photo[] photos = new Photo[collection.Count];
//for (int i = 0; i < collection.Count; i++) {
// Photo p = (Photo)collection[i];
// DateTime time = p.Time;
// p.Time = time + span;
// photos[i] = p;
// Log.Debug ($"XXXXX old: {time} new: {p.Time} span: {span}");
//}
//db.Photos.Commit (photos);
}
void SpaceByInterval ()
{
//DateTime date = EditTime;
//long ticks = (long)(double.Parse (spacing_entry.Text) * TimeSpan.TicksPerMinute);
//TimeSpan span = new TimeSpan (ticks);
//Photo[] photos = new Photo[collection.Count];
//for (int i = 0; i < collection.Count; i++) {
// photos[i] = (Photo)collection[i];
//}
//TimeSpan accum = new TimeSpan (0);
//for (int j = item.Index; j > 0; j--) {
// date -= span;
//}
//for (int i = 0; i < photos.Length; i++) {
// photos[i].Time = date + accum;
// accum += span;
//}
//db.Photos.Commit (photos);
}
void HandleSpinChanged (object sender, EventArgs args)
{
item.Index = photo_spin.ValueAsInt - 1;
}
void HandleOkClicked (object sender, EventArgs args)
{
if (!item.IsValid)
throw new ApplicationException ("invalid item selected");
Sensitive = false;
if (difference_check.Active)
ShiftByDifference ();
else
SpaceByInterval ();
Destroy ();
}
void HandleOffsetChanged (object sender, EventArgs args)
{
//Log.DebugFormat ("offset = {0}", Offset);
//TimeSpan current = Offset;
//try {
// TimeSpan span = TimeSpan.Parse (offset_entry.Text);
// if (span != current)
// Offset = span;
//} catch (Exception) {
// Log.Warning ($"unparsable span {offset_entry.Text}");
//}
}
void HandleSpacingChanged (object sender, EventArgs args)
{
if (!spacing_entry.Sensitive)
return;
try {
double.Parse (spacing_entry.Text);
ok_button.Sensitive = true;
} catch {
ok_button.Sensitive = false;
}
}
void HandleActionToggled (object sender, EventArgs args)
{
spacing_entry.Sensitive = !difference_check.Active;
HandleSpacingChanged (sender, args);
}
void HandleCancelClicked (object sender, EventArgs args)
{
Destroy ();
}
void HandleForwardClicked (object sender, EventArgs args)
{
view.Item.MoveNext ();
}
void HandleBackClicked (object sender, EventArgs args)
{
view.Item.MovePrevious ();
}
void HandleCollectionChanged (IBrowsableCollection collection)
{
bool multiple = collection.Count > 1;
tray_frame.Visible = multiple;
//forward_button.Visible = multiple;
//back_button.Visible = multiple;
count_label.Visible = multiple;
photo_spin.Visible = multiple;
action_frame.Visible = multiple;
photo_spin.SetRange (1.0, (double)collection.Count);
}
}
}
| |
// 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.Runtime.Remoting;
using System.Runtime.Serialization;
using System.Reflection;
using System.Globalization;
using System.Runtime.Versioning;
using System.Collections.Generic;
using System.Diagnostics.Contracts;
namespace System {
[Serializable]
// Holds classes (Empty, Null, Missing) for which we guarantee that there is only ever one instance of.
internal class UnitySerializationHolder : ISerializable, IObjectReference
{
#region Internal Constants
internal const int EmptyUnity = 0x0001;
internal const int NullUnity = 0x0002;
internal const int MissingUnity = 0x0003;
internal const int RuntimeTypeUnity = 0x0004;
internal const int ModuleUnity = 0x0005;
internal const int AssemblyUnity = 0x0006;
internal const int GenericParameterTypeUnity = 0x0007;
internal const int PartialInstantiationTypeUnity = 0x0008;
internal const int Pointer = 0x0001;
internal const int Array = 0x0002;
internal const int SzArray = 0x0003;
internal const int ByRef = 0x0004;
#endregion
#region Internal Static Members
internal static void GetUnitySerializationInfo(SerializationInfo info, Missing missing)
{
info.SetType(typeof(UnitySerializationHolder));
info.AddValue("UnityType", MissingUnity);
}
internal static RuntimeType AddElementTypes(SerializationInfo info, RuntimeType type)
{
List<int> elementTypes = new List<int>();
while(type.HasElementType)
{
if (type.IsSzArray)
{
elementTypes.Add(SzArray);
}
else if (type.IsArray)
{
elementTypes.Add(type.GetArrayRank());
elementTypes.Add(Array);
}
else if (type.IsPointer)
{
elementTypes.Add(Pointer);
}
else if (type.IsByRef)
{
elementTypes.Add(ByRef);
}
type = (RuntimeType)type.GetElementType();
}
info.AddValue("ElementTypes", elementTypes.ToArray(), typeof(int[]));
return type;
}
internal Type MakeElementTypes(Type type)
{
for (int i = m_elementTypes.Length - 1; i >= 0; i --)
{
if (m_elementTypes[i] == SzArray)
{
type = type.MakeArrayType();
}
else if (m_elementTypes[i] == Array)
{
type = type.MakeArrayType(m_elementTypes[--i]);
}
else if ((m_elementTypes[i] == Pointer))
{
type = type.MakePointerType();
}
else if ((m_elementTypes[i] == ByRef))
{
type = type.MakeByRefType();
}
}
return type;
}
internal static void GetUnitySerializationInfo(SerializationInfo info, RuntimeType type)
{
if (type.GetRootElementType().IsGenericParameter)
{
type = AddElementTypes(info, type);
info.SetType(typeof(UnitySerializationHolder));
info.AddValue("UnityType", GenericParameterTypeUnity);
info.AddValue("GenericParameterPosition", type.GenericParameterPosition);
info.AddValue("DeclaringMethod", type.DeclaringMethod, typeof(MethodBase));
info.AddValue("DeclaringType", type.DeclaringType, typeof(Type));
return;
}
int unityType = RuntimeTypeUnity;
if (!type.IsGenericTypeDefinition && type.ContainsGenericParameters)
{
// Partial instantiation
unityType = PartialInstantiationTypeUnity;
type = AddElementTypes(info, type);
info.AddValue("GenericArguments", type.GetGenericArguments(), typeof(Type[]));
type = (RuntimeType)type.GetGenericTypeDefinition();
}
GetUnitySerializationInfo(info, unityType, type.FullName, type.GetRuntimeAssembly());
}
internal static void GetUnitySerializationInfo(
SerializationInfo info, int unityType, String data, RuntimeAssembly assembly)
{
// A helper method that returns the SerializationInfo that a class utilizing
// UnitySerializationHelper should return from a call to GetObjectData. It contains
// the unityType (defined above) and any optional data (used only for the reflection
// types.)
info.SetType(typeof(UnitySerializationHolder));
info.AddValue("Data", data, typeof(String));
info.AddValue("UnityType", unityType);
String assemName;
if (assembly == null)
{
assemName = String.Empty;
}
else
{
assemName = assembly.FullName;
}
info.AddValue("AssemblyName", assemName);
}
#endregion
#region Private Data Members
private Type[] m_instantiation;
private int[] m_elementTypes;
private int m_genericParameterPosition;
private Type m_declaringType;
private MethodBase m_declaringMethod;
private String m_data;
private String m_assemblyName;
private int m_unityType;
#endregion
#region Constructor
internal UnitySerializationHolder(SerializationInfo info, StreamingContext context)
{
if (info == null)
throw new ArgumentNullException(nameof(info));
Contract.EndContractBlock();
m_unityType = info.GetInt32("UnityType");
if (m_unityType == MissingUnity)
return;
if (m_unityType == GenericParameterTypeUnity)
{
m_declaringMethod = info.GetValue("DeclaringMethod", typeof(MethodBase)) as MethodBase;
m_declaringType = info.GetValue("DeclaringType", typeof(Type)) as Type;
m_genericParameterPosition = info.GetInt32("GenericParameterPosition");
m_elementTypes = info.GetValue("ElementTypes", typeof(int[])) as int[];
return;
}
if (m_unityType == PartialInstantiationTypeUnity)
{
m_instantiation = info.GetValue("GenericArguments", typeof(Type[])) as Type[];
m_elementTypes = info.GetValue("ElementTypes", typeof(int[])) as int[];
}
m_data = info.GetString("Data");
m_assemblyName = info.GetString("AssemblyName");
}
#endregion
#region Private Methods
private void ThrowInsufficientInformation(string field)
{
throw new SerializationException(
Environment.GetResourceString("Serialization_InsufficientDeserializationState", field));
}
#endregion
#region ISerializable
[System.Security.SecurityCritical] // auto-generated
public virtual void GetObjectData(SerializationInfo info, StreamingContext context)
{
throw new NotSupportedException(Environment.GetResourceString("NotSupported_UnitySerHolder"));
}
#endregion
#region IObjectReference
[System.Security.SecurityCritical] // auto-generated
public virtual Object GetRealObject(StreamingContext context)
{
// GetRealObject uses the data we have in m_data and m_unityType to do a lookup on the correct
// object to return. We have specific code here to handle the different types which we support.
// The reflection types (Assembly, Module, and Type) have to be looked up through their static
// accessors by name.
Assembly assembly;
switch (m_unityType)
{
case EmptyUnity:
{
return Empty.Value;
}
case NullUnity:
{
return DBNull.Value;
}
case MissingUnity:
{
return Missing.Value;
}
case PartialInstantiationTypeUnity:
{
m_unityType = RuntimeTypeUnity;
Type definition = GetRealObject(context) as Type;
m_unityType = PartialInstantiationTypeUnity;
if (m_instantiation[0] == null)
return null;
return MakeElementTypes(definition.MakeGenericType(m_instantiation));
}
case GenericParameterTypeUnity:
{
if (m_declaringMethod == null && m_declaringType == null)
ThrowInsufficientInformation("DeclaringMember");
if (m_declaringMethod != null)
return m_declaringMethod.GetGenericArguments()[m_genericParameterPosition];
return MakeElementTypes(m_declaringType.GetGenericArguments()[m_genericParameterPosition]);
}
case RuntimeTypeUnity:
{
if (m_data == null || m_data.Length == 0)
ThrowInsufficientInformation("Data");
if (m_assemblyName == null)
ThrowInsufficientInformation("AssemblyName");
if (m_assemblyName.Length == 0)
return Type.GetType(m_data, true, false);
assembly = Assembly.Load(m_assemblyName);
Type t = assembly.GetType(m_data, true, false);
return t;
}
case ModuleUnity:
{
if (m_data == null || m_data.Length == 0)
ThrowInsufficientInformation("Data");
if (m_assemblyName == null)
ThrowInsufficientInformation("AssemblyName");
assembly = Assembly.Load(m_assemblyName);
Module namedModule = assembly.GetModule(m_data);
if (namedModule == null)
throw new SerializationException(
Environment.GetResourceString("Serialization_UnableToFindModule", m_data, m_assemblyName));
return namedModule;
}
case AssemblyUnity:
{
if (m_data == null || m_data.Length == 0)
ThrowInsufficientInformation("Data");
if (m_assemblyName == null)
ThrowInsufficientInformation("AssemblyName");
assembly = Assembly.Load(m_assemblyName);
return assembly;
}
default:
throw new ArgumentException(Environment.GetResourceString("Argument_InvalidUnity"));
}
}
#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.
using System.Diagnostics;
using Internal.Runtime.Augments;
namespace System.Threading
{
internal static partial class WaitSubsystem
{
/// <summary>
/// Contains thread-specific information for the wait subsystem. There is one instance per thread that is registered
/// using <see cref="WaitedListNode"/>s with each <see cref="WaitableObject"/> that the thread is waiting upon.
///
/// Used by the wait subsystem on Unix, so this class cannot have any dependencies on the wait subsystem.
/// </summary>
public sealed class ThreadWaitInfo
{
private readonly RuntimeThread _thread;
/// <summary>
/// The monitor the thread would wait upon when the wait needs to be interruptible
/// </summary>
private readonly LowLevelMonitor _waitMonitor;
////////////////////////////////////////////////////////////////
/// Thread wait state. The following members indicate the waiting state of the thread, and convery information from
/// a signaler to the waiter. They are synchronized with <see cref="_waitMonitor"/>.
private WaitSignalState _waitSignalState;
/// <summary>
/// Index of the waitable object in <see cref="_waitedObjects"/>, which got signaled and satisfied the wait. -1 if
/// the wait has not yet been satisfied.
/// </summary>
private int _waitedObjectIndexThatSatisfiedWait;
////////////////////////////////////////////////////////////////
/// Information about the current wait, including the type of wait, the <see cref="WaitableObject"/>s involved in
/// the wait, etc. They are synchronized with <see cref="s_lock"/>.
private bool _isWaitForAll;
/// <summary>
/// Number of <see cref="WaitableObject"/>s the thread is waiting upon
/// </summary>
private int _waitedCount;
/// <summary>
/// - <see cref="WaitableObject"/>s that are waited upon by the thread. This array is also used for temporarily
/// storing <see cref="WaitableObject"/>s corresponding to <see cref="WaitHandle"/>s when the thread is not
/// waiting.
/// - The count of this array is a power of 2, the filled count is <see cref="_waitedCount"/>
/// - Indexes in all arrays that use <see cref="_waitedCount"/> correspond
/// </summary>
private WaitHandleArray<WaitableObject> _waitedObjects;
/// <summary>
/// - Nodes used for registering a thread's wait on each <see cref="WaitableObject"/>, in the
/// <see cref="WaitableObject.WaitersHead"/> linked list
/// - The count of this array is a power of 2, the filled count is <see cref="_waitedCount"/>
/// - Indexes in all arrays that use <see cref="_waitedCount"/> correspond
/// </summary>
private WaitHandleArray<WaitedListNode> _waitedListNodes;
private int _isPendingInterrupt;
////////////////////////////////////////////////////////////////
/// <summary>
/// Linked list of mutex <see cref="WaitableObject"/>s that are owned by the thread and need to be abandoned before
/// the thread exits. The linked list has only a head and no tail, which means acquired mutexes are prepended and
/// mutexes are abandoned in reverse order.
/// </summary>
private WaitableObject _lockedMutexesHead;
public ThreadWaitInfo(RuntimeThread thread)
{
Debug.Assert(thread != null);
_thread = thread;
_waitMonitor = new LowLevelMonitor();
_waitedObjectIndexThatSatisfiedWait = -1;
_waitedObjects = new WaitHandleArray<WaitableObject>(elementInitializer: null);
_waitedListNodes = new WaitHandleArray<WaitedListNode>(i => new WaitedListNode(this, i));
}
public RuntimeThread Thread => _thread;
/// <summary>
/// Callers must ensure to clear the array after use. Once <see cref="RegisterWait(int, bool)"/> is called (followed
/// by a call to <see cref="Wait(int, bool, out int)"/>, the array will be cleared automatically.
/// </summary>
public WaitableObject[] GetWaitedObjectArray(int requiredCapacity)
{
Debug.Assert(_thread == RuntimeThread.CurrentThread);
Debug.Assert(_waitedCount == 0);
_waitedObjects.VerifyElementsAreDefault();
_waitedObjects.EnsureCapacity(requiredCapacity);
return _waitedObjects.Items;
}
private WaitedListNode[] GetWaitedListNodeArray(int requiredCapacity)
{
Debug.Assert(_thread == RuntimeThread.CurrentThread);
Debug.Assert(_waitedCount == 0);
_waitedListNodes.EnsureCapacity(requiredCapacity, i => new WaitedListNode(this, i));
return _waitedListNodes.Items;
}
/// <summary>
/// The caller is expected to populate <see cref="WaitedObjects"/> and pass in the number of objects filled
/// </summary>
public void RegisterWait(int waitedCount, bool isWaitForAll)
{
s_lock.VerifyIsLocked();
Debug.Assert(_thread == RuntimeThread.CurrentThread);
Debug.Assert(waitedCount > (isWaitForAll ? 1 : 0));
Debug.Assert(waitedCount <= _waitedObjects.Items.Length);
Debug.Assert(_waitedCount == 0);
WaitableObject[] waitedObjects = _waitedObjects.Items;
#if DEBUG
for (int i = 0; i < waitedCount; ++i)
{
Debug.Assert(waitedObjects[i] != null);
}
for (int i = waitedCount; i < waitedObjects.Length; ++i)
{
Debug.Assert(waitedObjects[i] == null);
}
#endif
bool success = false;
WaitedListNode[] waitedListNodes;
try
{
waitedListNodes = GetWaitedListNodeArray(waitedCount);
success = true;
}
finally
{
if (!success)
{
// Once this function is called, the caller is effectively transferring ownership of the waited objects
// to this and the wait functions. On exception, clear the array.
for (int i = 0; i < waitedCount; ++i)
{
waitedObjects[i] = null;
}
}
}
_isWaitForAll = isWaitForAll;
_waitedCount = waitedCount;
for (int i = 0; i < waitedCount; ++i)
{
waitedListNodes[i].RegisterWait(waitedObjects[i]);
}
}
public void UnregisterWait()
{
s_lock.VerifyIsLocked();
Debug.Assert(_waitedCount > (_isWaitForAll ? 1 : 0));
for (int i = 0; i < _waitedCount; ++i)
{
_waitedListNodes.Items[i].UnregisterWait(_waitedObjects.Items[i]);
_waitedObjects.Items[i] = null;
}
_waitedCount = 0;
}
private int ProcessSignaledWaitState(WaitHandle[] waitHandlesForAbandon, out Exception exception)
{
s_lock.VerifyIsNotLocked();
_waitMonitor.VerifyIsLocked();
Debug.Assert(_thread == RuntimeThread.CurrentThread);
switch (_waitSignalState)
{
case WaitSignalState.Waiting:
exception = null;
return WaitHandle.WaitTimeout;
case WaitSignalState.Waiting_SignaledToSatisfyWait:
{
Debug.Assert(_waitedObjectIndexThatSatisfiedWait >= 0);
int waitedObjectIndexThatSatisfiedWait = _waitedObjectIndexThatSatisfiedWait;
_waitedObjectIndexThatSatisfiedWait = -1;
exception = null;
return waitedObjectIndexThatSatisfiedWait;
}
case WaitSignalState.Waiting_SignaledToSatisfyWaitWithAbandonedMutex:
Debug.Assert(_waitedObjectIndexThatSatisfiedWait >= 0);
if (waitHandlesForAbandon == null)
{
_waitedObjectIndexThatSatisfiedWait = -1;
exception = new AbandonedMutexException();
}
else
{
int waitedObjectIndexThatSatisfiedWait = _waitedObjectIndexThatSatisfiedWait;
_waitedObjectIndexThatSatisfiedWait = -1;
exception =
new AbandonedMutexException(
waitedObjectIndexThatSatisfiedWait,
waitHandlesForAbandon[waitedObjectIndexThatSatisfiedWait]);
}
return 0;
case WaitSignalState.Waiting_SignaledToAbortWaitDueToMaximumMutexReacquireCount:
Debug.Assert(_waitedObjectIndexThatSatisfiedWait < 0);
exception = new OverflowException(SR.Overflow_MutexReacquireCount);
return 0;
default:
Debug.Assert(_waitSignalState == WaitSignalState.Waiting_SignaledToInterruptWait);
Debug.Assert(_waitedObjectIndexThatSatisfiedWait < 0);
exception = new ThreadInterruptedException();
return 0;
}
}
public int Wait(int timeoutMilliseconds, WaitHandle[] waitHandlesForAbandon, bool isSleep)
{
if (!isSleep)
{
s_lock.VerifyIsLocked();
}
Debug.Assert(_thread == RuntimeThread.CurrentThread);
Debug.Assert(timeoutMilliseconds >= -1);
Debug.Assert(timeoutMilliseconds != 0); // caller should have taken care of it
_thread.SetWaitSleepJoinState();
/// <see cref="_waitMonitor"/> must be acquired before <see cref="s_lock"/> is released, to ensure that there is
/// no gap during which a waited object may be signaled to satisfy the wait but the thread may not yet be in a
/// wait state to accept the signal
_waitMonitor.Acquire();
if (!isSleep)
{
s_lock.Release();
}
Debug.Assert(_waitedObjectIndexThatSatisfiedWait < 0);
Debug.Assert(_waitSignalState == WaitSignalState.NotWaiting);
/// A signaled state may be set only when the thread is in the
/// <see cref="WaitSignalState.Waiting"/> state
_waitSignalState = WaitSignalState.Waiting;
int waitResult;
Exception exception;
try
{
if (timeoutMilliseconds < 0)
{
do
{
_waitMonitor.Wait();
} while (_waitSignalState == WaitSignalState.Waiting);
waitResult = ProcessSignaledWaitState(waitHandlesForAbandon, out exception);
Debug.Assert(exception != null || waitResult != WaitHandle.WaitTimeout);
}
else
{
int elapsedMilliseconds = 0;
int startTimeMilliseconds = Environment.TickCount;
while (true)
{
bool monitorWaitResult = _waitMonitor.Wait(timeoutMilliseconds - elapsedMilliseconds);
// It's possible for the wait to have timed out, but before the monitor could reacquire the lock, a
// signaler could have acquired it and signaled to satisfy the wait or interrupt the thread. Accept the
// signal and ignore the wait timeout.
waitResult = ProcessSignaledWaitState(waitHandlesForAbandon, out exception);
if (exception != null || waitResult != WaitHandle.WaitTimeout)
{
break;
}
if (monitorWaitResult)
{
elapsedMilliseconds = Environment.TickCount - startTimeMilliseconds;
if (elapsedMilliseconds < timeoutMilliseconds)
{
continue;
}
}
// Timeout
Debug.Assert(_waitedObjectIndexThatSatisfiedWait < 0);
break;
}
}
}
finally
{
_waitSignalState = WaitSignalState.NotWaiting;
_waitMonitor.Release();
_thread.ClearWaitSleepJoinState();
}
if (exception != null)
{
throw exception;
}
if (waitResult != WaitHandle.WaitTimeout)
{
return waitResult;
}
/// Timeout. It's ok to read <see cref="_waitedCount"/> without acquiring <see cref="s_lock"/> here, because it
/// is initially set by this thread, and another thread cannot unregister this thread's wait without first
/// signaling this thread, in which case this thread wouldn't be timing out.
Debug.Assert(isSleep == (_waitedCount == 0));
if (!isSleep)
{
s_lock.Acquire();
try
{
UnregisterWait();
}
finally
{
s_lock.Release();
}
}
return waitResult;
}
public static void UninterruptibleSleep0()
{
// On Unix, a thread waits on a condition variable. The timeout time will have already elapsed at the time
// of the call. The documentation does not state whether the thread yields or does nothing before returning
// an error, and in some cases, suggests that doing nothing is acceptable. The behavior could also be
// different between distributions. Yield directly here.
RuntimeThread.Yield();
}
public void Sleep(int timeoutMilliseconds)
{
s_lock.VerifyIsNotLocked();
Debug.Assert(_thread == RuntimeThread.CurrentThread);
Debug.Assert(timeoutMilliseconds >= -1);
if (timeoutMilliseconds == 0)
{
UninterruptibleSleep0();
return;
}
int waitResult = Wait(timeoutMilliseconds, waitHandlesForAbandon: null, isSleep: true);
Debug.Assert(waitResult == WaitHandle.WaitTimeout);
}
public bool TrySignalToSatisfyWait(WaitedListNode registeredListNode, bool isAbandonedMutex)
{
s_lock.VerifyIsLocked();
Debug.Assert(_thread != RuntimeThread.CurrentThread);
Debug.Assert(registeredListNode != null);
Debug.Assert(registeredListNode.WaitInfo == this);
Debug.Assert(registeredListNode.WaitedObjectIndex >= 0);
Debug.Assert(registeredListNode.WaitedObjectIndex < _waitedCount);
Debug.Assert(_waitedCount > (_isWaitForAll ? 1 : 0));
int signaledWaitedObjectIndex = registeredListNode.WaitedObjectIndex;
bool isWaitForAll = _isWaitForAll;
int waitedCount = 0;
WaitableObject[] waitedObjects = null;
bool wouldAnyMutexReacquireCountOverflow = false;
if (isWaitForAll)
{
// Determine if all waits would be satisfied
waitedCount = _waitedCount;
waitedObjects = _waitedObjects.Items;
if (!WaitableObject.WouldWaitForAllBeSatisfiedOrAborted(
_thread,
waitedObjects,
waitedCount,
signaledWaitedObjectIndex,
ref wouldAnyMutexReacquireCountOverflow,
ref isAbandonedMutex))
{
return false;
}
}
// The wait would be satisfied. Before making changes to satisfy the wait, acquire the monitor and verify that
// the thread can accept a signal.
_waitMonitor.Acquire();
if (_waitSignalState != WaitSignalState.Waiting)
{
_waitMonitor.Release();
return false;
}
if (isWaitForAll && !wouldAnyMutexReacquireCountOverflow)
{
// All waits would be satisfied, accept the signals
WaitableObject.SatisfyWaitForAll(this, waitedObjects, waitedCount, signaledWaitedObjectIndex);
}
UnregisterWait();
Debug.Assert(_waitedObjectIndexThatSatisfiedWait < 0);
if (wouldAnyMutexReacquireCountOverflow)
{
_waitSignalState = WaitSignalState.Waiting_SignaledToAbortWaitDueToMaximumMutexReacquireCount;
}
else
{
_waitedObjectIndexThatSatisfiedWait = signaledWaitedObjectIndex;
_waitSignalState =
isAbandonedMutex
? WaitSignalState.Waiting_SignaledToSatisfyWaitWithAbandonedMutex
: WaitSignalState.Waiting_SignaledToSatisfyWait;
}
_waitMonitor.Signal_Release();
return !wouldAnyMutexReacquireCountOverflow;
}
public void TrySignalToInterruptWaitOrRecordPendingInterrupt()
{
s_lock.VerifyIsLocked();
_waitMonitor.Acquire();
if (_waitSignalState != WaitSignalState.Waiting)
{
_waitMonitor.Release();
RecordPendingInterrupt();
return;
}
if (_waitedCount != 0)
{
UnregisterWait();
}
Debug.Assert(_waitedObjectIndexThatSatisfiedWait < 0);
_waitSignalState = WaitSignalState.Waiting_SignaledToInterruptWait;
_waitMonitor.Signal_Release();
}
private void RecordPendingInterrupt() => Interlocked.Exchange(ref _isPendingInterrupt, 1);
public bool CheckAndResetPendingInterrupt => Interlocked.CompareExchange(ref _isPendingInterrupt, 0, 1) != 0;
public WaitableObject LockedMutexesHead
{
get
{
s_lock.VerifyIsLocked();
return _lockedMutexesHead;
}
set
{
s_lock.VerifyIsLocked();
_lockedMutexesHead = value;
}
}
public void OnThreadExiting()
{
// Abandon locked mutexes. Acquired mutexes are prepended to the linked list, so the mutexes are abandoned in
// last-acquired-first-abandoned order.
s_lock.Acquire();
try
{
while (true)
{
WaitableObject waitableObject = LockedMutexesHead;
if (waitableObject == null)
{
break;
}
waitableObject.AbandonMutex();
Debug.Assert(LockedMutexesHead != waitableObject);
}
}
finally
{
s_lock.Release();
}
}
public sealed class WaitedListNode
{
/// <summary>
/// For <see cref="WaitedListNode"/>s registered with <see cref="WaitableObject"/>s, this provides information
/// about the thread that is waiting and the <see cref="WaitableObject"/>s it is waiting upon
/// </summary>
private readonly ThreadWaitInfo _waitInfo;
/// <summary>
/// Index of the waited object corresponding to this node
/// </summary>
private readonly int _waitedObjectIndex;
/// <summary>
/// Link in the <see cref="WaitableObject.WaitersHead"/> linked list
/// </summary>
private WaitedListNode _previous, _next;
public WaitedListNode(ThreadWaitInfo waitInfo, int waitedObjectIndex)
{
Debug.Assert(waitInfo != null);
Debug.Assert(waitedObjectIndex >= 0);
Debug.Assert(waitedObjectIndex < WaitHandle.MaxWaitHandles);
_waitInfo = waitInfo;
_waitedObjectIndex = waitedObjectIndex;
}
public ThreadWaitInfo WaitInfo
{
get
{
s_lock.VerifyIsLocked();
return _waitInfo;
}
}
public int WaitedObjectIndex
{
get
{
s_lock.VerifyIsLocked();
return _waitedObjectIndex;
}
}
public WaitedListNode Previous
{
get
{
s_lock.VerifyIsLocked();
return _previous;
}
}
public WaitedListNode Next
{
get
{
s_lock.VerifyIsLocked();
return _next;
}
}
public void RegisterWait(WaitableObject waitableObject)
{
s_lock.VerifyIsLocked();
Debug.Assert(_waitInfo.Thread == RuntimeThread.CurrentThread);
Debug.Assert(waitableObject != null);
Debug.Assert(_previous == null);
Debug.Assert(_next == null);
WaitedListNode tail = waitableObject.WaitersTail;
if (tail != null)
{
_previous = tail;
tail._next = this;
}
else
{
waitableObject.WaitersHead = this;
}
waitableObject.WaitersTail = this;
}
public void UnregisterWait(WaitableObject waitableObject)
{
s_lock.VerifyIsLocked();
Debug.Assert(waitableObject != null);
WaitedListNode previous = _previous;
WaitedListNode next = _next;
if (previous != null)
{
previous._next = next;
_previous = null;
}
else
{
Debug.Assert(waitableObject.WaitersHead == this);
waitableObject.WaitersHead = next;
}
if (next != null)
{
next._previous = previous;
_next = null;
}
else
{
Debug.Assert(waitableObject.WaitersTail == this);
waitableObject.WaitersTail = previous;
}
}
}
private enum WaitSignalState : byte
{
NotWaiting,
Waiting,
Waiting_SignaledToSatisfyWait,
Waiting_SignaledToSatisfyWaitWithAbandonedMutex,
Waiting_SignaledToAbortWaitDueToMaximumMutexReacquireCount,
Waiting_SignaledToInterruptWait
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections;
using System.IO;
using System.Text;
using System.Web.UI;
/*
* This class accumulates the information about the tested server,
* and produces the report.
*/
class Report
{
/*
* Connection name (server name).
*/
internal string ConnName
{
get
{
return connName;
}
set
{
connName = value;
}
}
/*
* Connection port.
*/
internal int ConnPort
{
get
{
return connPort;
}
set
{
connPort = value;
}
}
/*
* Server name sent in the SNI extension. This may be null if
* no SNI extension was sent.
*/
internal string SNI
{
get
{
return sni;
}
set
{
sni = value;
}
}
/*
* List of supported SSLv2 cipher suites, in the order returned
* by the server (which is purely advisory, since selection is
* done by the client). It is null if SSLv2 is not supported.
*/
internal int[] SSLv2CipherSuites
{
get
{
return ssl2Suites;
}
set
{
ssl2Suites = value;
}
}
/*
* Certificate sent by the server if SSLv2 is supported (null
* otherwise). It is reported as a chain of length 1.
*/
internal X509Chain SSLv2Chain
{
get
{
return ssl2Chain;
}
}
/*
* List of supported cipher suites, indexed by protocol version.
* This map contains information for version SSL 3.0 and more.
*/
internal IDictionary<int, SupportedCipherSuites> CipherSuites
{
get
{
return suites;
}
}
/*
* Support for SSLv3+ with a SSLv2 ClientHello format.
*/
internal bool SupportsV2Hello
{
get
{
return helloV2;
}
set
{
helloV2 = value;
}
}
/*
* Set to true if we had to shorten our ClientHello messages
* (this indicates a server with a fixed, small buffer for
* incoming ClientHello).
*/
internal bool NeedsShortHello
{
get
{
return shortHello;
}
set
{
shortHello = value;
}
}
/*
* Set to true if we had to suppress extensions from our
* ClientHello (flawed server that does not support extensions).
*/
internal bool NoExtensions
{
get
{
return noExts;
}
set
{
noExts = value;
}
}
/*
* Set to true if the server, at some point, agreed to use
* Deflate compression.
*/
internal bool DeflateCompress
{
get
{
return compress;
}
set
{
compress = value;
}
}
/*
* Set to true if the server appears to support secure
* renegotiation (at least, it understands and returns an empty
* extension; this does not demonstrate that the server would
* accept an actual renegotiation, but if it does, then chances
* are that it will tag it with the proper extension value).
*/
internal bool SupportsSecureRenegotiation
{
get
{
return doesRenego;
}
set
{
doesRenego = value;
}
}
/*
* Set to true if the server appears to support the Encrypt-then-MAC
* extension (RFC 7366). This is only about the extension, _not_
* cipher suites that are "natively" in Encrypt-then-MAC mode (e.g.
* AES/GCM and ChaCha20+Poly1305 cipher suites).
*/
internal bool SupportsEncryptThenMAC
{
get
{
return doesEtM;
}
set
{
doesEtM = value;
}
}
/*
* Set the server time offset (serverTime - clientTime), in
* milliseconds.
*
* Int64.MinValue means that the server sends 0 (the standard
* method to indicate that the clock is not available).
*
* Int64.MaxValue means that the server sends random bytes
* in the time field (non-standard, but widespread because
* OpenSSL does that by default since September 2013).
*/
internal long ServerTimeOffset
{
get
{
return serverTimeOffset;
}
set
{
serverTimeOffset = value;
}
}
/*
* Minimal size (in bits) of DH parameters sent by server. If
* server never used DHE or SRP, then this is 0.
*/
internal int MinDHSize
{
get
{
return minDHSize;
}
set
{
minDHSize = value;
}
}
/*
* Get all certificate chains gathered so far.
*/
internal X509Chain[] AllChains
{
get
{
return M.ToValueArray(chains);
}
}
string connName;
int connPort;
string sni;
int[] ssl2Suites;
X509Chain ssl2Chain;
bool helloV2;
bool shortHello;
bool noExts;
IDictionary<int, SupportedCipherSuites> suites;
IDictionary<string, X509Chain> chains;
bool compress;
long serverTimeOffset;
bool doesRenego;
bool doesEtM;
int minDHSize;
/*
* Create an empty report instance.
*/
internal Report()
{
suites = new SortedDictionary<int, SupportedCipherSuites>();
chains = new SortedDictionary<string, X509Chain>(
StringComparer.Ordinal);
serverTimeOffset = Int64.MinValue;
}
/*
* Set the cipher suites supported for a specific protocol version
* (SSLv3+).
*/
internal void SetCipherSuites(int version, SupportedCipherSuites scs)
{
suites[version] = scs;
}
/*
* Record a certificate sent by a SSLv2 server. The certificate
* is alone.
*/
internal void SetSSLv2Certificate(byte[] ssl2Cert)
{
if (ssl2Cert == null)
{
ssl2Chain = null;
}
else
{
ssl2Chain = X509Chain.Make(
new byte[][] { ssl2Cert }, true);
}
}
/*
* Record a new certificate chain sent by the server. Duplicates
* are merged.
*/
internal void AddServerChain(byte[][] chain)
{
X509Chain xc = X509Chain.Make(chain, true);
chains[xc.Hash] = xc;
}
/*
* Print the report on the provided writer (text version for
* humans).
*/
internal void Print(TextWriter w)
{
w.WriteLine("Connection: {0}:{1}", connName, connPort);
if (sni == null)
{
w.WriteLine("No SNI sent");
}
else
{
w.WriteLine("SNI: {0}", sni);
}
if (ssl2Suites != null && ssl2Suites.Length > 0)
{
w.WriteLine(" {0}", M.VersionString(M.SSLv20));
foreach (int s in ssl2Suites)
{
w.WriteLine(" {0}",
CipherSuite.ToNameV2(s));
}
}
int protocolCount = 0;
foreach (int v in suites.Keys)
{
if (String.Compare(M.VersionString(v), "TLSv1.0") == 0 ||
String.Compare(M.VersionString(v), "SSLv2") == 0 ||
String.Compare(M.VersionString(v), "SSLv3") == 0)
{
w.WriteLine(" {0} is Not Approved - please remove", M.VersionString(v));
protocolCount = protocolCount + 1;
if (suites.Keys.Count == protocolCount)
{
w.WriteLine(" Please add at least one approved SSL/TSL protocol");
}
}
else
{
w.Write(" Testing on {0}:", M.VersionString(v));
SupportedCipherSuites scs = suites[v];
w.WriteLine();
w.WriteLine();
if (!(scs.PrefServer))
{
w.Write(" Server Selection: ");
w.Write("Not Approved");
if (scs.PrefClient)
{
w.WriteLine(" - Uses client preferences - Needs to support server preferences");
}
else
{
w.WriteLine(" - uses complex preferences - Needs to support server preferences");
}
w.WriteLine();
}
List<String> notApproved = new List<String>();
List<String> approved = new List<String>();
if (String.Compare(M.VersionString(v), "TLSv1.0") != 0)
{
bool correctOrdering = true;
foreach (int s in scs.Suites)
{
String cipher = CipherSuite.ToName(s);
if (cipher.Contains("APPROVED"))
{
approved.Add(cipher.Substring(0, cipher.Length - 9));
}
else
{
correctOrdering = false;
notApproved.Add(cipher);
}
}
List<String> temp = cipherOrdering(approved);
if (correctOrdering)
{
for (int i = 0; i < temp.Count; i++)
{
if (!(temp[i].Equals(approved[i])))
{
correctOrdering = false;
}
}
}
if (correctOrdering)
{
w.WriteLine(" Cipher Ordering Approved");
}
else
{
w.WriteLine(" Cipher Ordering Not Approved");
w.WriteLine(" Here is the recommended ordering");
approved = cipherOrdering(approved);
foreach (String s in approved)
{
w.WriteLine(" {0}", s);
}
if (notApproved.Count > 0)
{
w.WriteLine(" Remove these ciphers - Not Approved");
foreach (String s in notApproved)
{
w.WriteLine(" {0}", s);
if (s.Contains("RC4"))
{
w.WriteLine(" - RC4 is a broken cipher suite");
}
if (s.Contains("3DES"))
{
w.WriteLine(" - 3DES is a weak cipher suite");
}
}
}
}
approved.Clear();
notApproved.Clear();
w.WriteLine();
}
}
}
w.WriteLine();
w.WriteLine("=========================================");
if (minDHSize < 2048 && minDHSize > 0)
{
w.WriteLine("DH size is {0}", minDHSize);
w.WriteLine("DH should be 2048 or above.");
}
if (ssl2Chain != null)
{
if (checkKeySize(ssl2Chain, 0))
{
w.WriteLine("+++++ SSLv2 certificate - Not Approved");
PrintCert(w, ssl2Chain, 0);
}
}
String chainCount = "+++++ SSLv3/TLS: certificate chain(s) - Not Approved";
foreach (X509Chain xchain in chains.Values)
{
int n = xchain.Elements.Length;
for (int i = 0; i < n; i++)
{
bool flag = true;
if (checkKeySize(xchain, i))
{
if (flag) // I'm not sure what this is needed for. Do further testing.
{
w.WriteLine(chainCount);
flag = false;
}
PrintCert(w, xchain, i);
}
}
}
}
bool checkKeySize(X509Chain xchain, int num)
{
X509Cert xc = xchain.ElementsRev[num];
if (xc == null)
return true;
else if (xc.KeySize < 2048 && xc.KeyType.Contains("RSA"))
return true;
else if (xc.KeySize < 1024 && xc.KeyType.Contains("DSA"))
return true;
else if (xc.KeySize < 256)
return true;
return false;
}
void PrintCert(TextWriter w, X509Chain xchain, int num)
{
X509Cert xc = xchain.ElementsRev[num];
if (xc == null)
{
w.WriteLine("thumprint: {0}", xchain.ThumbprintsRev[num]);
w.WriteLine("UNDECODABLE: {0}",
xchain.DecodingIssuesRev[num]);
}
else
{
if (xc.KeySize < 2048)
{
if (xc.KeyType.Contains("EC") && xc.KeySize < 256)
{
w.WriteLine("Key size should be 256 or larger for {0}", xc.KeyType);
}
else if (xc.KeyType.Contains("DSA") && xc.KeySize < 1024)
{
w.WriteLine("Key size should be 1024 or larger for {0}", xc.KeyType);
}
else if (xc.KeyType.Contains("RSA"))
{
w.WriteLine("Key size should be 2048 or larger for {0}", xc.KeyType);
}
else
{
return;
}
w.WriteLine(" thumprint: {0}", xchain.ThumbprintsRev[num]);
w.WriteLine("Current key size: {0}", xc.KeySize);
}
}
}
void PrintCertHtml(HtmlTextWriter w, X509Chain xchain, int num)
{
X509Cert xc = xchain.ElementsRev[num];
if (xc == null)
{
w.WriteBeginTag("p");
w.Write(HtmlTextWriter.TagRightChar);
w.WriteLine("thumprint: {0}", xchain.ThumbprintsRev[num]);
w.WriteEndTag("p");
w.WriteBeginTag("li");
w.Write(HtmlTextWriter.TagRightChar);
w.WriteBeginTag("ul");
w.Write(HtmlTextWriter.TagRightChar);
w.WriteLine("UNDECODABLE: {0}",
xchain.DecodingIssuesRev[num]);
w.WriteEndTag("ul");
w.WriteEndTag("li");
}
else
{
if (xc.KeySize < 2048)
{
if (xc.KeyType.Contains("EC") && xc.KeySize < 256)
{
w.WriteBeginTag("p");
w.Write(HtmlTextWriter.TagRightChar);
w.WriteLine("Key size should be 256 or larger for {0}", xc.KeyType);
w.WriteEndTag("p");
}
else if (xc.KeyType.Contains("DSA") && xc.KeySize < 1024)
{
w.WriteBeginTag("p");
w.Write(HtmlTextWriter.TagRightChar);
w.WriteLine("Key size should be 1024 or larger for {0}", xc.KeyType);
w.WriteEndTag("p");
}
else if (xc.KeyType.Contains("RSA"))
{
w.WriteBeginTag("p");
w.Write(HtmlTextWriter.TagRightChar);
w.WriteLine("Key size should be 2048 or larger for {0}", xc.KeyType);
w.WriteEndTag("p");
}
else
{
return;
}
w.WriteBeginTag("p");
w.Write(HtmlTextWriter.TagRightChar);
w.WriteLine(" thumprint: {0}", xchain.ThumbprintsRev[num]);
w.WriteLine("Current key size: {0}", xc.KeySize);
w.WriteEndTag("p");
}
}
}
/*
* The ordering functions
* recursively seperate and order
* the ciphersuites.
*/
internal List<String> cipherOrdering(List<String> ciphers)
{
List<String> AES = new List<string>();
List<String> noAES = new List<string>();
foreach (String c in ciphers)
{
if (hasAES(c))
{
AES.Add(c);
}
else
{
noAES.Add(c);
}
}
AES = GCMOrdering(AES);
AES.AddRange(GCMOrdering(noAES));
return AES;
}
internal List<String> GCMOrdering(List<String> GCM)
{
List<String> GCMs = new List<string>();
List<String> noGCM = new List<string>();
foreach (String c in GCM)
{
if (hasGCM(c))
{
GCMs.Add(c);
}
else
{
noGCM.Add(c);
}
}
GCMs = ECOrdering(GCMs);
GCMs.AddRange(ECOrdering(noGCM));
return GCMs;
}
internal List<String> ECOrdering(List<String> EC)
{
List<String> noEc = new List<string>();
List<String> ec = new List<string>();
foreach (String c in EC)
{
if (hasEC(c))
{
ec.Add(c);
}
else
{
noEc.Add(c);
}
}
ec = EphemOrdering(ec);
ec.AddRange(EphemOrdering(noEc));
return ec;
}
internal List<String> EphemOrdering(List<String> Ephem)
{
List<String> noEphem = new List<string>();
List<String> ephem = new List<string>();
foreach (String c in Ephem)
{
if (hasEphem(c))
{
ephem.Add(c);
}
else
{
noEphem.Add(c);
}
}
ephem = DHOrdering(ephem);
ephem.AddRange(DHOrdering(noEphem));
return ephem;
}
internal List<String> DHOrdering(List<String> DH)
{
List<String> noDh = new List<string>();
List<String> dh = new List<string>();
foreach (String c in DH)
{
if (hasDH(c))
{
dh.Add(c);
}
else
{
noDh.Add(c);
}
}
dh = RSAOrdering(dh);
dh.AddRange(RSAOrdering(noDh));
return dh;
}
/*
* Now we enter into the RSA,ECDSA,DSA ordering
*/
internal List<String> RSAOrdering(List<String> RSA)
{
List<String> noRsa = new List<string>();
List<String> rsa = new List<string>();
foreach (String c in RSA)
{
if (hasRSA(c))
{
rsa.Add(c);
}
else
{
noRsa.Add(c);
}
}
rsa = ECDSAOrdering(rsa);
rsa.AddRange(ECDSAOrdering(noRsa));
return rsa;
}
internal List<String> ECDSAOrdering(List<String> ECDSA)
{
List<String> noEc = new List<string>();
List<String> ec = new List<string>();
foreach (String c in ECDSA)
{
if (hasECDSA(c))
{
ec.Add(c);
}
else
{
noEc.Add(c);
}
}
ec.AddRange(noEc);
return ec;
}
/*
* the 'has' functions check for each cipher,
* created to make code more readable
*/
internal bool hasRSA(String cipher)
{
if (cipher.Substring(1, 3).Contains("RSA"))
{
if (cipher.Substring(3, cipher.Length).Contains("RSA"))
{
return true;
}
else
{
return false;
}
}
else
{
if (cipher.Contains("RSA"))
{
return true;
}
else
{
return false;
}
}
}
internal bool hasECDSA(String cipher)
{
if (cipher.Contains("ECDSA"))
{
return true;
}
return false;
}
internal bool hasAES(String cipher)
{
if (cipher.Contains("AES"))
{
return true;
}
return false;
}
internal bool hasGCM(String cipher)
{
if (cipher.Contains("GCM"))
{
return true;
}
return false;
}
internal bool hasEC(String cipher)
{
if (cipher.Contains("EC"))
{
return true;
}
return false;
}
internal bool hasEphem(String cipher)
{
if (cipher.Contains("DHE"))
{
return true;
}
return false;
}
internal bool hasDH(String cipher)
{
if (cipher.Contains("DH"))
{
return true;
}
return false;
}
/*
* Print the report as HTML
*/
internal void PrintHtml(TextWriter w)
{
HtmlTextWriter htw = new HtmlTextWriter(w);
w.WriteLine("<!DOCTYPE html>");
w.WriteLine("<html>");
w.WriteLine("<head>");
htw.Write("Connection: {0}:{1}", connName, connPort);
w.WriteLine("</head>");
htw.WriteBeginTag("body");
htw.Write(HtmlTextWriter.TagRightChar);
if (ssl2Suites != null && ssl2Suites.Length > 0)
{
htw.WriteBeginTag("script");
htw.Write(" type='text/javascript'");
htw.Write(HtmlTextWriter.TagRightChar);
htw.WriteLine("function newPopup(url) {");
htw.WriteLine("popupWindow = window.open(");
htw.WriteLine("url,'popUpWindow'," +
"'height=500,width=500,left=10,top=10,resizable=yes," +
"scrollbars=yes,toolbar=yes,menubar=no,location=no," +
"directories=no,status=yes')}");
htw.WriteEndTag("script");
htw.WriteBeginTag("p");
htw.Write(HtmlTextWriter.TagRightChar);
htw.WriteBeginTag("a");
htw.Write(" href=");
htw.Write(" 'JavaScript: newPopup(\"htmlPages/brokenProtocols/SSL.html\");'");
htw.Write(HtmlTextWriter.TagRightChar);
htw.WriteLine(" {0} is Not Approved - please remove", M.VersionString(M.SSLv20));
htw.WriteEndTag("a");
htw.WriteEndTag("p");
}
int protocolCount = 0;
foreach (int v in suites.Keys)
{
if (String.Compare(M.VersionString(v), "TLSv1.0") == 0 ||
String.Compare(M.VersionString(v), "SSLv3") == 0)
{
htw.WriteBeginTag("script");
htw.Write(" type='text/javascript'");
htw.Write(HtmlTextWriter.TagRightChar);
htw.WriteLine("function newPopup(url) {");
htw.WriteLine("popupWindow = window.open(");
htw.WriteLine("url,'popUpWindow'," +
"'height=500,width=500,left=10,top=10,resizable=yes," +
"scrollbars=yes,toolbar=yes,menubar=no,location=no," +
"directories=no,status=yes')}");
htw.WriteEndTag("script");
htw.WriteBeginTag("p");
htw.Write(HtmlTextWriter.TagRightChar);
htw.WriteBeginTag("a");
htw.Write(" href=");
if (String.Compare(M.VersionString(v), "TLSv1.0") == 0)
{
htw.Write(" 'JavaScript: newPopup(\"htmlPages/brokenProtocols/TLS1.html\");'");
}
else
{
htw.Write(" 'JavaScript: newPopup(\"htmlPages/brokenProtocols/SSL.html\");'");
}
htw.Write(HtmlTextWriter.TagRightChar);
htw.Write(" {0} is Not Approved - please remove</p>", M.VersionString(v));
htw.WriteEndTag("a");
htw.WriteEndTag("p");
protocolCount = protocolCount + 1;
if (suites.Keys.Count == protocolCount)
{
htw.WriteBeginTag("p");
htw.Write(HtmlTextWriter.TagRightChar);
w.WriteLine(" Please add at least one approved SSL/TSL protocol");
htw.WriteEndTag("p");
}
}
else
{
htw.WriteBeginTag("p");
htw.Write(HtmlTextWriter.TagRightChar);
htw.Write(" Testing on {0}:", M.VersionString(v));
htw.WriteEndTag("p");
SupportedCipherSuites scs = suites[v];
htw.WriteLine();
htw.WriteLine();
if (!(scs.PrefServer))
{
htw.WriteBeginTag("p");
htw.Write(HtmlTextWriter.TagRightChar);
htw.Write(" Server Selection: Not Approved");
if (scs.PrefClient)
{
htw.WriteLine(" - Uses client preferences - Needs to support server preferences");
}
else
{
htw.WriteLine(" - uses complex preferences - Needs to support server preferences");
}
htw.WriteLine();
htw.WriteEndTag("p");
}
List<String> notApproved = new List<String>();
List<String> approved = new List<String>();
if (String.Compare(M.VersionString(v), "TLSv1.0") != 0)
{
bool correctOrdering = true;
foreach (int s in scs.Suites)
{
String cipher = CipherSuite.ToName(s);
if (cipher.Contains("APPROVED"))
{
approved.Add(cipher.Substring(0, cipher.Length - 9));
}
else
{
correctOrdering = false;
notApproved.Add(cipher);
}
}
List<String> temp = cipherOrdering(approved);
if (correctOrdering)
{
for (int i = 0; i < temp.Count; i++)
{
if (!(temp[i].Equals(approved[i])))
{
correctOrdering = false;
}
}
}
if (correctOrdering)
{
htw.WriteBeginTag("p");
htw.Write(HtmlTextWriter.TagRightChar);
htw.WriteLine(" Cipher Ordering Approved");
htw.WriteEndTag("p");
}
else
{
approved = cipherOrdering(approved);
if (approved.Count > 0)
{
htw.WriteBeginTag("p");
htw.Write(HtmlTextWriter.TagRightChar);
htw.WriteLine(" Cipher Ordering Approved");
htw.WriteLine(" Here is the recommended ordering");
htw.WriteEndTag("p");
htw.WriteBeginTag("ol");
htw.Write(HtmlTextWriter.TagRightChar);
foreach (String s in approved)
{
htw.WriteBeginTag("li");
htw.Write(HtmlTextWriter.TagRightChar);
htw.WriteLine(" {0}", s);
htw.WriteEndTag("li");
}
htw.WriteEndTag("ol");
}
else
{
htw.WriteBeginTag("p");
htw.Write(HtmlTextWriter.TagRightChar);
htw.Write("Please add at least one approved CipherSuite");
htw.WriteEndTag("p");
}
if (notApproved.Count > 0)
{
htw.WriteBeginTag("p");
htw.Write(HtmlTextWriter.TagRightChar);
htw.WriteLine(" Remove these ciphers - Not Approved");
htw.WriteEndTag("p");
htw.WriteBeginTag("script");
htw.Write(" type='text/javascript'");
htw.Write(HtmlTextWriter.TagRightChar);
htw.WriteLine("function newPopup(url) {");
htw.WriteLine("popupWindow = window.open(");
htw.WriteLine("url,'popUpWindow'," +
"'height=500,width=500,left=10,top=10,resizable=yes," +
"scrollbars=yes,toolbar=yes,menubar=no,location=no," +
"directories=no,status=yes')}");
htw.WriteEndTag("script");
htw.WriteBeginTag("ul");
htw.Write(HtmlTextWriter.TagRightChar);
foreach (String s in notApproved)
{
htw.WriteBeginTag("li");
htw.Write(HtmlTextWriter.TagRightChar);
htw.WriteBeginTag("a");
htw.Write(" href=");
if (s.Contains("RC4"))
{
htw.Write(" 'JavaScript: newPopup(\"htmlPages/brokenCiphers/RC4.html\");'");
}
else if (s.Contains("3DES"))
{
htw.Write(" 'JavaScript: newPopup(\"htmlPages/brokenCiphers/3DES.html\");'");
}
else if (s.Contains("AES_128"))
{
htw.Write(" 'JavaScript: newPopup(\"htmlPages/brokenCiphers/AES.html\");'");
}
else
{
htw.Write(" 'JavaScript: newPopup(\"htmlPages/brokenCiphers/other.html\");'");
}
htw.Write(HtmlTextWriter.TagRightChar);
htw.WriteBeginTag("p");
htw.Write(HtmlTextWriter.TagRightChar);
htw.WriteLine(" {0}", s);
htw.WriteEndTag("p");
htw.WriteEndTag("a");
htw.WriteEndTag("li");
}
htw.WriteEndTag("ul");
}
}
approved.Clear();
notApproved.Clear();
htw.WriteLine();
}
}
}
htw.WriteBeginTag("p");
htw.Write(HtmlTextWriter.TagRightChar);
htw.WriteLine("=========================================");
htw.WriteEndTag("p");
if (ssl2Chain != null)
{
if (checkKeySize(ssl2Chain, 0))
{
htw.WriteBeginTag("p");
htw.Write(HtmlTextWriter.TagRightChar);
htw.WriteLine("+++++ SSLv2 certificate - Not Approved");
htw.WriteEndTag("p");
htw.WriteBeginTag("p");
htw.Write(HtmlTextWriter.TagRightChar);
PrintCertHtml(htw, ssl2Chain, 0);
htw.WriteEndTag("p");
}
}
String chainCount = "+++++ SSLv3/TLS: certificate chain(s) - Not Approved";
foreach (X509Chain xchain in chains.Values)
{
int n = xchain.Elements.Length;
for (int i = 0; i < n; i++)
{
bool flag = true;
if (checkKeySize(xchain, i))
{
if (flag)
{
htw.WriteBeginTag("p");
htw.Write(HtmlTextWriter.TagRightChar);
htw.WriteLine(chainCount);
htw.WriteEndTag("p");
flag = false;
}
htw.WriteBeginTag("p");
htw.Write(HtmlTextWriter.TagRightChar);
PrintCertHtml(htw, xchain, i);
htw.WriteEndTag("p");
}
}
}
htw.WriteEndTag("body");
htw.WriteEndTag("html");
}
/*
* Encode the report as JSON.
*/
internal void Print(JSON js)
{
js.OpenInit(false);
js.AddPair("connectionName", connName);
js.AddPair("connectionPort", connPort);
js.AddPair("SNI", sni);
if (ssl2Suites != null && ssl2Suites.Length > 0)
{
js.OpenPairObject("SSLv2");
js.AddPair("approvalStatus", "notApproved");
js.Close();
}
foreach (int v in suites.Keys)
{
js.OpenPairObject(M.VersionString(v));
SupportedCipherSuites scs = suites[v];
string sel;
if (scs.PrefClient)
{
sel = "client - Not Approved";
}
else if (scs.PrefServer)
{
sel = "server";
}
else
{
sel = "complex - Not Approved";
}
js.AddPair("suiteSelection", sel);
List<String> approved = new List<String>();
List<String> notApproved = new List<String>();
bool ordering = true;
foreach (int s in scs.Suites)
{
String cipher = CipherSuite.ToName(s);
if (cipher.Contains("APPROVED"))
{
approved.Add(cipher.Substring(0, cipher.Length - 9));
}
else
{
notApproved.Add(cipher);
ordering = false;
}
}
List<String> properOrdering = cipherOrdering(approved);
if(ordering)
{
for(int i=0;i<approved.Count;i++)
{
if(ordering == false)
{
break;
}
if(!(properOrdering[i].Equals(approved[i])))
{
ordering = false;
}
}
}
js.AddPair("Correct Ordering", ordering);
if(!ordering)
{
js.OpenPairArray("Proper Cipher Ordering");
foreach(String s in properOrdering)
{
js.AddElement(s);
}
js.Close();
js.OpenPairArray("Not Approved Ciphers");
foreach(String s in notApproved)
{
js.AddElement(s);
}
js.Close();
}
js.Close();
}
if (ssl2Chain != null)
{
js.OpenPairObject("ssl2Cert");
PrintCert(js, ssl2Chain, 0);
js.Close();
}
js.OpenPairObject("certificates");
foreach (X509Chain xchain in chains.Values)
{
int n = xchain.Elements.Length;
for (int i = 0; i < n; i++)
{
PrintCert(js, xchain, i);
js.Close();
}
}
if (minDHSize > 0)
{
js.AddPair("minDHSize", minDHSize);
}
js.Close();
}
/*
* Add certificate to output. The caller is responsible for
* opening the certificate object.
*/
void PrintCert(JSON js, X509Chain xchain, int num)
{
js.OpenPairObject("thumbprint:"+xchain.ThumbprintsRev[num]);
//js.AddPair("thumbprint", xchain.ThumbprintsRev[num]);
X509Cert xc = xchain.ElementsRev[num];
if (xc == null)
{
js.AddPair("decodeError",
xchain.DecodingIssuesRev[num]);
}
else
{
if (xc.KeyType.Contains("EC") && xc.KeySize < 256)
{
js.AddPair("Size", "Less than 256 not approved");
}
else if (xc.KeyType.Contains("DSA") && xc.KeySize < 1024)
{
js.AddPair("Size", "Less than 1024 not approved");
}
else if (xc.KeyType.Contains("RSA") && (xc.KeySize<2048))
{
js.AddPair("Size", "Less than 2048 not approved");
}
else
{
js.AddPair("Size", "Approved");
}
js.AddPair("keyType", xc.KeyType);
js.AddPair("keySize", xc.KeySize);
}
}
}
| |
using Signum.Engine.Basics;
using Signum.Engine.Cache;
using Signum.Engine.DynamicQuery;
using Signum.Engine.Maps;
using Signum.Engine.Operations;
using Signum.Entities;
using Signum.Entities.Basics;
using Signum.Entities.Dynamic;
using Signum.Utilities;
using Signum.Utilities.ExpressionTrees;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Reflection;
using System.Text;
namespace Signum.Engine.Dynamic
{
public static class DynamicTypeLogic
{
public static ResetLazy<HashSet<Type>> AvailableEmbeddedEntities = null!;
public static ResetLazy<HashSet<Type>> AvailableModelEntities = null!;
public static void Start(SchemaBuilder sb)
{
if (sb.NotDefined(MethodInfo.GetCurrentMethod()))
{
sb.Include<DynamicTypeEntity>()
.WithQuery(() => e => new
{
Entity = e,
e.Id,
e.TypeName,
e.BaseType,
});
AvailableEmbeddedEntities = sb.GlobalLazy(() =>
{
var namespaces = DynamicCode.GetNamespaces().ToHashSet();
return DynamicCode.AssemblyTypes
.Select(t => t.Assembly)
.Distinct()
.SelectMany(a => a.GetTypes())
.Where(t => typeof(EmbeddedEntity).IsAssignableFrom(t) && namespaces.Contains(t.Namespace!))
.ToHashSet();
}, new InvalidateWith(typeof(TypeEntity)));
AvailableModelEntities = sb.GlobalLazy(() =>
{
var namespaces = DynamicCode.GetNamespaces().ToHashSet();
return DynamicCode.AssemblyTypes
.Select(t => t.Assembly)
.Distinct()
.SelectMany(a => a.GetTypes())
.Where(t => typeof(ModelEntity).IsAssignableFrom(t) && namespaces.Contains(t.Namespace!))
.ToHashSet();
}, new InvalidateWith(typeof(TypeEntity)));
DynamicTypeGraph.Register();
DynamicLogic.GetCodeFiles += GetCodeFiles;
DynamicLogic.OnWriteDynamicStarter += WriteDynamicStarter;
DynamicCode.RegisteredDynamicTypes.Add(typeof(DynamicTypeEntity));
}
}
public class DynamicTypeGraph : Graph<DynamicTypeEntity>
{
public static void Register()
{
new Construct(DynamicTypeOperation.Create)
{
Construct = (_) => new DynamicTypeEntity { BaseType = DynamicBaseType.Entity },
}.Register();
new ConstructFrom<DynamicTypeEntity>(DynamicTypeOperation.Clone)
{
Construct = (e, _) =>
{
var def = e.GetDefinition();
var result = new DynamicTypeEntity { TypeName = null!, BaseType = e.BaseType };
result.SetDefinition(def);
return result;
},
}.Register();
new Execute(DynamicTypeOperation.Save)
{
CanBeNew = true,
CanBeModified = true,
Execute = (e, _) =>
{
var newDef = e.GetDefinition();
var duplicatePropertyNames = newDef.Properties
.GroupToDictionary(a => a.Name.ToLower())
.Where(a => a.Value.Count() > 1)
.ToList();
if (duplicatePropertyNames.Any())
throw new InvalidOperationException(ValidationMessage._0HasSomeRepeatedElements1.NiceToString(e.TypeName, duplicatePropertyNames.Select(a => a.Key.FirstUpper()).Comma(", ")));
if (!e.IsNew)
{
var old = e.ToLite().RetrieveAndRemember();
if (e.TypeName != old.TypeName)
DynamicSqlMigrationLogic.AddDynamicRename(TypeNameKey, old.TypeName, e.TypeName);
if (e.BaseType == DynamicBaseType.ModelEntity)
return;
var oldDef = old.GetDefinition();
var newName = GetTableName(e, newDef);
var oldName = GetTableName(old, oldDef);
if (newName != oldName)
DynamicSqlMigrationLogic.AddDynamicRename(Replacements.KeyTables, oldName, newName);
var pairs = newDef.Properties
.Join(oldDef.Properties, n => n.UID, o => o.UID, (n, o) => new { n, o })
.Where(a => a.n!.Type == a.o!.Type); /*CSBUG*/
{
string ColName(DynamicProperty dp) => dp.ColumnName ?? dp.Name;
string replacementKey = (e.BaseType != DynamicBaseType.Entity || old.BaseType != DynamicBaseType.Entity) ? UnknownColumnKey : Replacements.KeyColumnsForTable(oldName);
foreach (var a in pairs.Where(a => ColName(a.n!) != ColName(a.o!)))
{
DynamicSqlMigrationLogic.AddDynamicRename(replacementKey, ColName(a.o!), ColName(a.n!));
}
}
{
string replacementKey = (e.BaseType != DynamicBaseType.Entity || old.BaseType != DynamicBaseType.Entity) ? UnknownPropertyKey : PropertyRouteLogic.PropertiesFor.FormatWith(old.TypeName);
foreach (var a in pairs.Where(a => a.n!.Name != a.o!.Name))
{
DynamicSqlMigrationLogic.AddDynamicRename(replacementKey, a.o!.Name, a.n!.Name);
}
}
}
},
}.Register();
new Delete(DynamicTypeOperation.Delete)
{
Delete = (e, _) =>
{
e.Delete();
}
}.Register();
}
}
public const string UnknownPropertyKey = "UnknownProperty";
public const string UnknownColumnKey = "UnknownColumn";
public const string TypeNameKey = "TypeName";
public static Func<DynamicTypeEntity, DynamicTypeDefinition, string> GetTableName = (dt, def) => def.TableName ?? ("codegen." + dt.TypeName);
public static string GetPropertyType(DynamicProperty property)
{
var generator = new DynamicTypeCodeGenerator(DynamicCode.CodeGenEntitiesNamespace, null!, DynamicBaseType.Entity, null!, new HashSet<string>());
return generator.GetPropertyType(property);
}
internal static List<DynamicTypeEntity> GetTypes()
{
CacheLogic.GloballyDisabled = true;
try
{
if (!Administrator.ExistsTable<DynamicTypeEntity>())
return new List<DynamicTypeEntity>();
return ExecutionMode.Global().Using(a => Database.Query<DynamicTypeEntity>().ToList());
}
finally
{
CacheLogic.GloballyDisabled = false;
}
}
public static void WriteDynamicStarter(StringBuilder sb, int indent)
{
var types = GetTypes();
foreach (var item in types)
sb.AppendLine($"{item}Logic.Start(sb);".Indent(indent));
}
public static Func<Dictionary<string, Dictionary<string, string>>>? GetAlreadyTranslatedExpressions;
public static Func<Dictionary<string, Dictionary<string, FormatUnit>>>? GetFormattedExpressions;
public static List<CodeFile> GetCodeFiles()
{
List<DynamicTypeEntity> types = GetTypes();
var alreadyTranslatedExpressions = GetAlreadyTranslatedExpressions?.Invoke();
var formattedExpressions = GetFormattedExpressions?.Invoke();
var result = new List<CodeFile>();
var entities = types.Select(dt =>
{
var def = dt.GetDefinition();
var dcg = new DynamicTypeCodeGenerator(DynamicCode.CodeGenEntitiesNamespace, dt.TypeName, dt.BaseType, def, DynamicCode.Namespaces);
var content = dcg.GetFileCode();
return new CodeFile(dt.TypeName + ".cs", content);
}).ToList();
result.AddRange(entities);
var logics = types.Select(dt =>
{
var def = dt.GetDefinition();
var dlg = new DynamicTypeLogicGenerator(DynamicCode.CodeGenEntitiesNamespace, dt.TypeName, dt.BaseType, def, DynamicCode.Namespaces)
{
AlreadyTranslated = alreadyTranslatedExpressions?.TryGetC(dt.TypeName + "Entity"),
Formatted = formattedExpressions?.TryGetC(dt.TypeName + "Entity"),
};
var content = dlg.GetFileCode();
return new CodeFile(dt.TypeName + "Logic.cs", content);
}).ToList();
result.AddRange(logics);
var bs = new DynamicBeforeSchemaGenerator(DynamicCode.CodeGenEntitiesNamespace, types.Select(a => a.GetDefinition().CustomBeforeSchema).NotNull().ToList(), DynamicCode.Namespaces);
result.Add(new CodeFile("CodeGenBeforeSchema.cs", bs.GetFileCode()));
return result;
}
}
public class DynamicTypeCodeGenerator
{
public HashSet<string> Usings { get; private set; }
public string Namespace { get; private set; }
public string TypeName { get; private set; }
public DynamicBaseType BaseType { get; private set; }
public DynamicTypeDefinition Def { get; private set; }
public bool IsTreeEntity { get; private set; }
public DynamicTypeCodeGenerator(string @namespace, string typeName, DynamicBaseType baseType, DynamicTypeDefinition def, HashSet<string> usings)
{
this.Usings = usings;
this.Namespace = @namespace;
this.TypeName = typeName;
this.BaseType = baseType;
this.Def = def;
this.IsTreeEntity = def != null && def.CustomInheritance != null && def.CustomInheritance.Code.Contains("TreeEntity");
}
public string GetFileCode()
{
StringBuilder sb = new StringBuilder();
foreach (var item in this.Usings)
sb.AppendLine("using {0};".FormatWith(item));
sb.AppendLine();
sb.AppendLine("namespace " + this.Namespace);
sb.AppendLine("{");
sb.Append(GetEntityCode().Indent(4));
if (this.BaseType == DynamicBaseType.Entity)
{
var ops = GetEntityOperation();
if (ops != null)
{
sb.AppendLine();
sb.Append(ops.Indent(4));
}
}
if (this.Def!.CustomTypes != null)
sb.AppendLine(this.Def.CustomTypes.Code);
sb.AppendLine("}");
return sb.ToString();
}
public string GetEntityCode()
{
StringBuilder sb = new StringBuilder();
foreach (var gr in GetEntityAttributes().GroupsOf(a => a.Length, 100))
{
sb.AppendLine("[" + gr.ToString(", ") + "]");
}
sb.AppendLine($"public class {this.GetTypeNameWithSuffix()} : {GetEntityBaseClass(this.BaseType)}");
sb.AppendLine("{");
if (this.BaseType == DynamicBaseType.MixinEntity)
sb.AppendLine($"{this.GetTypeNameWithSuffix()}(ModifiableEntity mainEntity, MixinEntity next): base(mainEntity, next) {{ }}".Indent(4));
foreach (var prop in Def.Properties)
{
string field = WriteProperty(prop);
if (field != null)
{
sb.Append(field.Indent(4));
sb.AppendLine();
}
}
if (this.Def.CustomEntityMembers != null)
sb.AppendLine(this.Def.CustomEntityMembers.Code.Indent(4));
string? toString = GetToString();
if (toString != null)
{
sb.Append(toString.Indent(4));
sb.AppendLine();
}
sb.AppendLine("}");
sb.AppendLine();
return sb.ToString();
}
public string? GetEntityOperation()
{
if (this.IsTreeEntity)
return null;
if (this.Def.OperationCreate == null &&
this.Def.OperationSave == null &&
this.Def.OperationDelete == null &&
this.Def.OperationClone == null)
return null;
StringBuilder sb = new StringBuilder();
sb.AppendLine($"[AutoInit]"); //Only for ReflectionServer
sb.AppendLine($"public static class {this.TypeName}Operation");
sb.AppendLine("{");
if (this.Def.OperationCreate != null)
sb.AppendLine($" public static readonly ConstructSymbol<{this.TypeName}Entity>.Simple Create = OperationSymbol.Construct<{this.TypeName}Entity>.Simple(typeof({ this.TypeName}Operation), \"Create\");");
var requiresSaveOperation = (this.Def.EntityKind != null && EntityKindAttribute.CalculateRequiresSaveOperation(this.Def.EntityKind.Value));
if ((this.Def.OperationSave != null) && !requiresSaveOperation)
throw new InvalidOperationException($"DynamicType '{this.TypeName}' defines Save but has EntityKind = '{this.Def.EntityKind}'");
else if (this.Def.OperationSave == null && requiresSaveOperation)
throw new InvalidOperationException($"DynamicType '{this.TypeName}' does not define Save but has EntityKind = '{this.Def.EntityKind}'");
if (this.Def.OperationSave != null)
sb.AppendLine($" public static readonly ExecuteSymbol<{this.TypeName}Entity> Save = OperationSymbol.Execute<{this.TypeName}Entity>(typeof({ this.TypeName}Operation), \"Save\");");
if (this.Def.OperationDelete != null)
sb.AppendLine($" public static readonly DeleteSymbol<{this.TypeName}Entity> Delete = OperationSymbol.Delete<{this.TypeName}Entity>(typeof({ this.TypeName}Operation), \"Delete\");");
if (this.Def.OperationClone != null)
sb.AppendLine($" public static readonly ConstructSymbol<{this.TypeName}Entity>.From<{this.TypeName}Entity> Clone = OperationSymbol.Construct<{this.TypeName}Entity>.From<{this.TypeName}Entity>(typeof({ this.TypeName}Operation), \"Clone\");");
sb.AppendLine("}");
return sb.ToString();
}
private string GetEntityBaseClass(DynamicBaseType baseType)
{
if (this.Def.CustomInheritance != null)
return this.Def.CustomInheritance.Code;
return baseType.ToString();
}
protected virtual string? GetToString()
{
if (Def.ToStringExpression == null)
return null;
StringBuilder sb = new StringBuilder();
sb.AppendLine($"static Expression<Func<{this.GetTypeNameWithSuffix()}, string>> ToStringExpression = e => {Def.ToStringExpression};");
sb.AppendLine("[ExpressionField(\"ToStringExpression\")]");
sb.AppendLine("public override string ToString()");
sb.AppendLine("{");
sb.AppendLine(" return ToStringExpression.Evaluate(this);");
sb.AppendLine("}");
return sb.ToString();
}
public virtual string GetTypeNameWithSuffix()
{
return this.TypeName + (this.BaseType == DynamicBaseType.MixinEntity ? "Mixin" :
this.BaseType == DynamicBaseType.EmbeddedEntity ? "Embedded":
this.BaseType == DynamicBaseType.ModelEntity ? "Model" : "Entity");
}
private List<string> GetEntityAttributes()
{
List<string> atts = new List<string> { "Serializable" };
if (this.BaseType == DynamicBaseType.Entity)
{
atts.Add("EntityKind(EntityKind." + Def.EntityKind!.Value + ", EntityData." + Def.EntityData!.Value + ")");
if (Def.TableName.HasText())
{
var parts = ParseTableName(Def.TableName);
atts.Add("TableName(" + parts + ")");
}
if (Def.PrimaryKey != null)
{
var name = Def.PrimaryKey.Name ?? "ID";
var type = Def.PrimaryKey.Type ?? "int";
var identity = Def.PrimaryKey.Identity;
atts.Add($"PrimaryKey(typeof({type}), {Literal(name)}, Identity = {identity.ToString().ToLower()})");
}
if (Def.Ticks != null)
{
var hasTicks = Def.Ticks.HasTicks;
var name = Def.Ticks.Name ?? "Ticks";
var type = Def.Ticks.Type ?? "int";
if (!hasTicks)
atts.Add("TicksColumn(false)");
else
atts.Add($"TicksColumn(true, Name = {Literal(name)}, Type = typeof({type}))");
}
}
return atts;
}
string Literal(object obj)
{
return CSharpRenderer.Value(obj);
}
protected virtual string WriteProperty(DynamicProperty property)
{
string type = GetPropertyType(property);
StringBuilder sb = new StringBuilder();
string? inititalizer = (property.IsMList != null) ? $" = new {type}()" : null;
string fieldName = GetFieldName(property);
WriteAttributeTag(sb, GetFieldAttributes(property));
sb.AppendLine($"{type} {fieldName}{inititalizer};");
WriteAttributeTag(sb, GetPropertyAttributes(property));
sb.AppendLine($"public {type} {property.Name}");
sb.AppendLine("{");
sb.AppendLine($" get {{ return this.Get({fieldName}); }}");
sb.AppendLine($" set {{ this.Set(ref {fieldName}, value); }}");
sb.AppendLine("}");
return sb.ToString();
}
private static string GetFieldName(DynamicProperty property)
{
var fn = property.Name.FirstLower();
return CSharpRenderer.EscapeIdentifier(fn);
}
private IEnumerable<string> GetPropertyAttributes(DynamicProperty property)
{
var atts = property.Validators.EmptyIfNull().Select(v => GetValidatorAttribute(v)).ToList();
if (property.IsNullable == Entities.Dynamic.IsNullable.OnlyInMemory && !property.Validators.EmptyIfNull().Any(v => v.Type == "NotNull"))
atts.Add(GetValidatorAttribute(new DynamicValidator.NotNull { Type = "NotNull" }));
if (property.Unit != null)
atts.Add($"Unit(\"{property.Unit}\")");
if (property.Format != null)
atts.Add($"Format(\"{property.Format}\")");
if (property.NotifyChanges == true)
{
if (property.IsMList != null)
atts.Add("NotifyCollectionChanged");
if (property.Type.EndsWith("Embedded") || property.Type.EndsWith("Entity") && property.IsLite != true)
atts.Add("NotifyChildProperty");
}
if (property.CustomPropertyAttributes.HasText())
atts.Add(property.CustomPropertyAttributes);
return atts;
}
private string GetValidatorAttribute(DynamicValidator v)
{
var name = v.Type + "Validator";
var extra = v.ExtraArguments();
if (extra == null)
return name;
return $"{name}({extra})";
}
protected virtual void WriteAttributeTag(StringBuilder sb, IEnumerable<string> attributes)
{
foreach (var gr in attributes.GroupsOf(a => a.Length, 100))
{
sb.AppendLine("[" + gr.ToString(", ") + "]");
}
}
private List<string> GetFieldAttributes(DynamicProperty property)
{
List<string> atts = new List<string>();
if (property.IsNullable == Entities.Dynamic.IsNullable.OnlyInMemory)
atts.Add("ForceNotNullable");
if (property.Size != null || property.Scale != null || property.ColumnType.HasText())
{
var props = new[]
{
property.Size != null ? "Size = " + Literal(property.Size) : null,
property.Scale != null ? "Scale = " + Literal(property.Scale) : null,
property.ColumnType.HasText() ? "SqlDbType = " + Literal(Enum.TryParse(property.ColumnType, out SqlDbType dbType) ? dbType : SqlDbType.Udt) : null,
property.ColumnType.HasText() && !Enum.TryParse<SqlDbType>(property.ColumnType, out var _) ? "UserDefinedTypeName = " + Literal(property.ColumnType) : null,
}.NotNull().ToString(", ");
atts.Add($"DbType({props})");
}
if (property.ColumnName.HasText())
atts.Add("ColumnName(" + Literal(property.ColumnName) + ")");
switch (property.UniqueIndex)
{
case Entities.Dynamic.UniqueIndex.No: break;
case Entities.Dynamic.UniqueIndex.Yes: atts.Add("UniqueIndex"); break;
case Entities.Dynamic.UniqueIndex.YesAllowNull: atts.Add("UniqueIndex(AllowMultipleNulls = true)"); break;
}
if (property.IsMList != null)
{
var mlist = property.IsMList;
if (mlist.PreserveOrder)
atts.Add("PreserveOrder" + (mlist.OrderName.HasText() ? "(" + Literal(mlist.OrderName) + ")" : ""));
if (mlist.TableName.HasText())
{
var parts = ParseTableName(mlist.TableName);
atts.Add("TableName(" + parts + ")");
}
if (mlist.BackReferenceName.HasText())
atts.Add($"BackReferenceColumnName({Literal(mlist.BackReferenceName)})");
}
if (property.CustomFieldAttributes.HasText())
atts.Add(property.CustomFieldAttributes);
return atts;
}
private string ParseTableName(string value)
{
var isPostgres = Schema.Current.Settings.IsPostgres;
var objName = ObjectName.Parse(value, isPostgres);
return new List<string?>
{
Literal(objName.Name),
!objName.Schema.IsDefault() ? "SchemaName =" + Literal(objName.Schema.Name) : null,
objName.Schema.Database != null ? "DatabaseName =" + Literal(objName.Schema.Database.Name) : null,
objName.Schema.Database?.Server != null ? "ServerName =" + Literal(objName.Schema.Database.Server.Name) : null,
}.NotNull().ToString(", ");
}
public virtual string GetPropertyType(DynamicProperty property)
{
if (string.IsNullOrEmpty(property.Type))
return "";
string result = SimplifyType(property.Type);
if (property.IsLite == true)
result = "Lite<" + result + ">";
if (property.IsMList != null)
return "MList<" + result + ">";
var isNullable = (property.IsNullable == Entities.Dynamic.IsNullable.Yes ||
property.IsNullable == Entities.Dynamic.IsNullable.OnlyInMemory);
return result + (isNullable ? "?" : "");
}
private bool IsValueType(DynamicProperty property)
{
var t = TryResolveType(property.Type);
if (t != null)
return t.IsValueType;
var tn = property.Type;
if (tn.EndsWith("Embedded") || tn.EndsWith("Entity") || tn.EndsWith("Mixin") || tn.EndsWith("Symbol"))
{
return false;
}
else
{
return true; // Assume Enum
}
}
private string SimplifyType(string type)
{
var ns = type.TryBeforeLast(".");
if (ns == null)
return type;
if (this.Namespace == ns || this.Usings.Contains(ns))
return type.AfterLast(".");
return type;
}
public Type? TryResolveType(string typeName)
{
switch (typeName)
{
case "bool": return typeof(bool);
case "byte": return typeof(byte);
case "char": return typeof(char);
case "decimal": return typeof(decimal);
case "double": return typeof(double);
case "short": return typeof(short);
case "int": return typeof(int);
case "long": return typeof(long);
case "sbyte": return typeof(sbyte);
case "float": return typeof(float);
case "string": return typeof(string);
case "ushort": return typeof(ushort);
case "uint": return typeof(uint);
case "ulong": return typeof(ulong);
}
var result = Type.GetType("System." + typeName);
if (result != null)
return result;
var type = TypeLogic.TryGetType(typeName);
if (type != null)
return EnumEntity.Extract(type) ?? type;
return null;
}
}
public class DynamicTypeLogicGenerator
{
public HashSet<string> Usings { get; private set; }
public string Namespace { get; private set; }
public string TypeName { get; private set; }
public DynamicBaseType BaseType { get; private set; }
public DynamicTypeDefinition Def { get; private set; }
public bool IsTreeEntity { get; private set; }
public Dictionary<string, string>? AlreadyTranslated { get; set; }
public Dictionary<string, FormatUnit>? Formatted { get; set; }
public DynamicTypeLogicGenerator(string @namespace, string typeName, DynamicBaseType baseType, DynamicTypeDefinition def, HashSet<string> usings)
{
this.Usings = usings;
this.Namespace = @namespace;
this.TypeName = typeName;
this.BaseType = baseType;
this.Def = def;
this.IsTreeEntity = def != null && def.CustomInheritance != null && def.CustomInheritance.Code.Contains("TreeEntity");
}
public string GetFileCode()
{
StringBuilder sb = new StringBuilder();
foreach (var item in this.Usings)
sb.AppendLine("using {0};".FormatWith(item));
sb.AppendLine();
sb.AppendLine($"namespace {this.Namespace}");
sb.AppendLine($"{{");
var complexFields = this.Def.QueryFields.EmptyIfNull().Select(a => GetComplexQueryField(a)).NotNull().ToList();
var complexNotTranslated = complexFields.Where(a => this.AlreadyTranslated?.TryGetC(a) == null).ToList();
if (complexNotTranslated.Any())
{
sb.AppendLine($" public enum CodeGenQuery{this.TypeName}Message");
sb.AppendLine($" {{");
foreach (var item in complexNotTranslated)
sb.AppendLine($" " + item + ",");
sb.AppendLine($" }}");
}
sb.AppendLine($" public static class {this.TypeName}Logic");
sb.AppendLine($" {{");
sb.AppendLine($" public static void Start(SchemaBuilder sb)");
sb.AppendLine($" {{");
sb.AppendLine($" if (sb.NotDefined(MethodInfo.GetCurrentMethod()))");
sb.AppendLine($" {{");
if (this.BaseType == DynamicBaseType.Entity)
{
sb.AppendLine(GetInclude().Indent(16));
}
if (this.Def.CustomStartCode != null)
sb.AppendLine(this.Def.CustomStartCode.Code.Indent(16));
if (this.BaseType == DynamicBaseType.Entity)
{
if (complexFields.HasItems())
sb.AppendLine(RegisterComplexQuery(complexFields).Indent(16));
var complexOperations = RegisterComplexOperations();
if (complexOperations != null)
sb.AppendLine(complexOperations.Indent(16));
}
sb.AppendLine($" }}");
sb.AppendLine($" }}");
if (this.Def.CustomLogicMembers != null)
sb.AppendLine(this.Def.CustomLogicMembers.Code.Indent(8));
sb.AppendLine($" }}");
sb.AppendLine($"}}");
return sb.ToString();
}
private string GetInclude()
{
StringBuilder sb = new StringBuilder();
sb.AppendLine($"var fi = sb.Include<{this.TypeName}Entity>()");
if (!this.IsTreeEntity)
{
if (this.Def.OperationSave != null && string.IsNullOrWhiteSpace(this.Def.OperationSave.Execute.Trim()))
sb.AppendLine($" .WithSave({this.TypeName}Operation.Save)");
if (this.Def.OperationDelete != null && string.IsNullOrWhiteSpace(this.Def.OperationDelete.Delete.Trim()))
sb.AppendLine($" .WithDelete({this.TypeName}Operation.Delete)");
}
var mcui = this.Def.MultiColumnUniqueIndex;
if (mcui != null)
sb.AppendLine($" .WithUniqueIndex(e => new {{{ mcui.Fields.ToString(", ")}}}{(mcui.Where.HasText() ? ", e => " + mcui.Where : "")})");
var queryFields = this.Def.QueryFields.EmptyIfNull();
if (queryFields.EmptyIfNull().Any() && queryFields.All(a => GetComplexQueryField(a) == null))
{
var lines = new[] { "Entity = e" }.Concat(queryFields);
sb.AppendLine($@" .WithQuery(() => e => new
{{
{ lines.ToString(",\r\n").Indent(8)}
}})");
}
sb.Insert(sb.Length - 2, ';');
return sb.ToString();
}
public static string? GetComplexQueryField(string field)
{
var fieldName = field.TryBefore("=")?.Trim();
if (fieldName == null)
return null;
if (!IdentifierValidatorAttribute.International.IsMatch(fieldName))
return null;
var lastProperty = field.After("=").TryAfterLast(".")?.Trim();
if (lastProperty == null || fieldName != lastProperty)
return fieldName;
return null;
}
public string RegisterComplexQuery(List<string> complexQueryFields)
{
StringBuilder sb = new StringBuilder();
var lines = new[] { "Entity = e" }.Concat(this.Def.QueryFields);
sb.AppendLine($@"QueryLogic.Queries.Register(typeof({this.TypeName}Entity), () => DynamicQueryCore.Auto(
from e in Database.Query<{this.TypeName}Entity>()
select new
{{
{ lines.ToString(",\r\n").Indent(8)}
}})
{complexQueryFields.Select(f => $".ColumnDisplayName(a => a.{f}, {this.AlreadyTranslated?.TryGetC(f) ?? $"CodeGenQuery{this.TypeName}Message.{f}"})").ToString("\r\n").Indent(4)}
{complexQueryFields.Where(f => this.Formatted?.TryGetS(f) != null).Select(f =>
{
var fu = this.Formatted?.TryGetS(f);
var formatText = fu != null && fu.Value.Format.HasText() ? $"c.Format = \"{fu.Value.Format}\";" : "";
var unitText = fu != null && fu.Value.Unit.HasText() ? $"c.Unit = \"{fu.Value.Unit}\";" : "";
return $".Column(a => a.{f}, c => {{ {formatText} {unitText} }})";
}).ToString("\r\n").Indent(4)}
);");
sb.AppendLine();
return sb.ToString();
}
private string RegisterComplexOperations()
{
StringBuilder sb = new StringBuilder();
var operationConstruct = this.Def.OperationCreate?.Construct.Trim();
if (operationConstruct.HasText())
{
sb.AppendLine();
if (this.IsTreeEntity)
{
sb.AppendLine("Graph<{0}Entity>.Construct.Untyped(TreeOperation.CreateRoot).Do(g => ".FormatWith(this.TypeName));
sb.AppendLine(" g.Construct = (args) => {\r\n" + operationConstruct.Indent(8) + "\r\n}");
sb.AppendLine(").Register(replace: true);");
}
else
{
sb.AppendLine("new Graph<{0}Entity>.Construct({0}Operation.Create)".FormatWith(this.TypeName));
sb.AppendLine("{");
sb.AppendLine(" Construct = (args) => {\r\n" + operationConstruct.Indent(8) + "\r\n}");
sb.AppendLine("}.Register();");
}
}
var operationExecute = this.Def.OperationSave?.Execute.Trim();
var operationCanExecute = this.Def.OperationSave?.CanExecute?.Trim();
if (!string.IsNullOrWhiteSpace(operationExecute) || !string.IsNullOrWhiteSpace(operationCanExecute))
{
sb.AppendLine();
sb.AppendLine("new Graph<{0}Entity>.Execute({1}Operation.Save)".FormatWith(this.TypeName, (this.IsTreeEntity ? "Tree" : this.TypeName)));
sb.AppendLine("{");
if (!string.IsNullOrWhiteSpace(operationCanExecute))
sb.AppendLine($" CanExecute = e => {operationCanExecute},");
sb.AppendLine(" CanBeNew = true,");
sb.AppendLine(" CanBeModified = true,");
sb.AppendLine(" Execute = (e, args) => {\r\n" + operationExecute?.Indent(8) + "\r\n}");
sb.AppendLine("}." + (this.IsTreeEntity ? "Register(replace: true)" : "Register()") + ";");
}
var operationDelete = this.Def.OperationDelete?.Delete.Trim();
var operationCanDelete = this.Def.OperationDelete?.CanDelete?.Trim();
if (!string.IsNullOrWhiteSpace(operationDelete) || !string.IsNullOrEmpty(operationCanDelete))
{
sb.AppendLine();
sb.AppendLine("new Graph<{0}Entity>.Delete({1}Operation.Delete)".FormatWith(this.TypeName, (this.IsTreeEntity ? "Tree" : this.TypeName)));
sb.AppendLine("{");
if (!string.IsNullOrWhiteSpace(operationCanDelete))
sb.AppendLine($" CanDelete = e => {operationCanDelete},");
sb.AppendLine(" Delete = (e, args) => {\r\n" + (operationDelete.DefaultText("e.Delete();")).Indent(8) + "\r\n}");
sb.AppendLine("}." + (this.IsTreeEntity ? "Register(replace: true)" : "Register()") + ";");
}
var operationClone = this.Def.OperationClone?.Construct.Trim();
var operationCanClone = this.Def.OperationClone?.CanConstruct?.Trim();
if (!string.IsNullOrWhiteSpace(operationClone) || !string.IsNullOrEmpty(operationCanClone))
{
sb.AppendLine();
sb.AppendLine("new Graph<{0}Entity>.ConstructFrom<{0}Entity>({1}Operation.Clone)".FormatWith(this.TypeName, (this.IsTreeEntity ? "Tree" : this.TypeName)));
sb.AppendLine("{");
if (!string.IsNullOrWhiteSpace(operationCanClone))
sb.AppendLine($" CanConstruct = e => {operationCanClone},");
sb.AppendLine(" Construct = (e, args) => {\r\n" + (operationClone.DefaultText($"return new {this.TypeName}Entity();")).Indent(8) + "\r\n}");
sb.AppendLine("}." + (this.IsTreeEntity ? "Register(replace: true)" : "Register()") + ";");
}
return sb.ToString();
}
}
public struct FormatUnit
{
public string? Format { get; set; }
public string? Unit { get; set; }
public FormatUnit(string? format, string? unit)
{
Format = format;
Unit = unit;
}
}
public class DynamicBeforeSchemaGenerator
{
public HashSet<string> Usings { get; private set; }
public string Namespace { get; private set; }
public List<DynamicTypeCustomCode> BeforeSchema { get; private set; }
public DynamicBeforeSchemaGenerator(string @namespace, List<DynamicTypeCustomCode> beforeSchema, HashSet<string> usings)
{
this.Usings = usings;
this.Namespace = @namespace;
this.BeforeSchema = beforeSchema;
}
public string GetFileCode()
{
StringBuilder sb = new StringBuilder();
foreach (var item in this.Usings)
sb.AppendLine("using {0};".FormatWith(item));
sb.AppendLine();
sb.AppendLine($"namespace {this.Namespace}");
sb.AppendLine($"{{");
sb.AppendLine($" public static class CodeGenBeforeSchemaLogic");
sb.AppendLine($" {{");
sb.AppendLine($" public static void Start(SchemaBuilder sb)");
sb.AppendLine($" {{");
if (this.BeforeSchema != null && this.BeforeSchema.Count > 0)
this.BeforeSchema.ForEach(bs => sb.AppendLine(bs.Code.Indent(12)));
sb.AppendLine($" }}");
sb.AppendLine($" }}");
sb.AppendLine($"}}");
return sb.ToString();
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
namespace Microsoft.DocAsCode.DataContracts.ManagedReference
{
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using Microsoft.DocAsCode.Common;
using Microsoft.DocAsCode.Common.EntityMergers;
using Microsoft.DocAsCode.DataContracts.Common;
using Microsoft.DocAsCode.YamlSerialization;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using YamlDotNet.Serialization;
[Serializable]
public class ItemViewModel : IOverwriteDocumentViewModel
{
[YamlMember(Alias = Constants.PropertyName.Uid)]
[JsonProperty(Constants.PropertyName.Uid)]
[MergeOption(MergeOption.MergeKey)]
public string Uid { get; set; }
[YamlMember(Alias = Constants.PropertyName.CommentId)]
[JsonProperty(Constants.PropertyName.CommentId)]
public string CommentId { get; set; }
[YamlMember(Alias = Constants.PropertyName.Id)]
[JsonProperty(Constants.PropertyName.Id)]
public string Id { get; set; }
[YamlMember(Alias = "isEii")]
[JsonProperty("isEii")]
public bool IsExplicitInterfaceImplementation { get; set; }
[YamlMember(Alias = "isExtensionMethod")]
[JsonProperty("isExtensionMethod")]
public bool IsExtensionMethod { get; set; }
[YamlMember(Alias = "parent")]
[JsonProperty("parent")]
[UniqueIdentityReference]
public string Parent { get; set; }
[YamlMember(Alias = "children")]
[MergeOption(MergeOption.Ignore)] // todo : merge more children
[JsonProperty("children")]
[UniqueIdentityReference]
public List<string> Children { get; set; }
[YamlMember(Alias = Constants.PropertyName.Href)]
[JsonProperty(Constants.PropertyName.Href)]
public string Href { get; set; }
[YamlMember(Alias = "langs")]
[JsonProperty("langs")]
public string[] SupportedLanguages { get; set; } = new string[] { "csharp", "vb" };
[YamlMember(Alias = Constants.PropertyName.Name)]
[JsonProperty(Constants.PropertyName.Name)]
public string Name { get; set; }
[ExtensibleMember(Constants.ExtensionMemberPrefix.Name)]
[JsonIgnore]
public SortedList<string, string> Names { get; set; } = new SortedList<string, string>();
[YamlIgnore]
[JsonIgnore]
public string NameForCSharp
{
get
{
string result;
Names.TryGetValue("csharp", out result);
return result;
}
set
{
if (value == null)
{
Names.Remove("csharp");
}
else
{
Names["csharp"] = value;
}
}
}
[YamlIgnore]
[JsonIgnore]
public string NameForVB
{
get
{
string result;
Names.TryGetValue("vb", out result);
return result;
}
set
{
if (value == null)
{
Names.Remove("vb");
}
else
{
Names["vb"] = value;
}
}
}
[YamlMember(Alias = Constants.PropertyName.NameWithType)]
[JsonProperty(Constants.PropertyName.NameWithType)]
public string NameWithType { get; set; }
[ExtensibleMember(Constants.ExtensionMemberPrefix.NameWithType)]
[JsonIgnore]
public SortedList<string, string> NamesWithType { get; set; } = new SortedList<string, string>();
[YamlIgnore]
[JsonIgnore]
public string NameWithTypeForCSharp
{
get
{
string result;
Names.TryGetValue("csharp", out result);
return result;
}
set
{
if (value == null)
{
NamesWithType.Remove("csharp");
}
else
{
NamesWithType["csharp"] = value;
}
}
}
[YamlIgnore]
[JsonIgnore]
public string NameWithTypeForVB
{
get
{
string result;
Names.TryGetValue("vb", out result);
return result;
}
set
{
if (value == null)
{
NamesWithType.Remove("vb");
}
else
{
NamesWithType["vb"] = value;
}
}
}
[YamlMember(Alias = Constants.PropertyName.FullName)]
[JsonProperty(Constants.PropertyName.FullName)]
public string FullName { get; set; }
[ExtensibleMember(Constants.ExtensionMemberPrefix.FullName)]
[JsonIgnore]
public SortedList<string, string> FullNames { get; set; } = new SortedList<string, string>();
[YamlIgnore]
[JsonIgnore]
public string FullNameForCSharp
{
get
{
string result;
FullNames.TryGetValue("csharp", out result);
return result;
}
set
{
if (value == null)
{
FullNames.Remove("csharp");
}
else
{
FullNames["csharp"] = value;
}
}
}
[YamlIgnore]
[JsonIgnore]
public string FullNameForVB
{
get
{
string result;
FullNames.TryGetValue("vb", out result);
return result;
}
set
{
if (value == null)
{
FullNames.Remove("vb");
}
else
{
FullNames["vb"] = value;
}
}
}
[YamlMember(Alias = Constants.PropertyName.Type)]
[JsonProperty(Constants.PropertyName.Type)]
public MemberType? Type { get; set; }
[YamlMember(Alias = Constants.PropertyName.Source)]
[JsonProperty(Constants.PropertyName.Source)]
public SourceDetail Source { get; set; }
[YamlMember(Alias = Constants.PropertyName.Documentation)]
[JsonProperty(Constants.PropertyName.Documentation)]
public SourceDetail Documentation { get; set; }
[YamlMember(Alias = "assemblies")]
[MergeOption(MergeOption.Ignore)] // todo : merge more children
[JsonProperty("assemblies")]
public List<string> AssemblyNameList { get; set; }
[YamlMember(Alias = "namespace")]
[JsonProperty("namespace")]
[UniqueIdentityReference]
public string NamespaceName { get; set; }
[YamlMember(Alias = "summary")]
[JsonProperty("summary")]
[MarkdownContent]
public string Summary { get; set; }
[YamlMember(Alias = "remarks")]
[JsonProperty("remarks")]
[MarkdownContent]
public string Remarks { get; set; }
[YamlMember(Alias = "example")]
[JsonProperty("example")]
[MergeOption(MergeOption.Replace)]
public List<string> Examples { get; set; }
[YamlMember(Alias = "syntax")]
[JsonProperty("syntax")]
public SyntaxDetailViewModel Syntax { get; set; }
[YamlMember(Alias = "overridden")]
[JsonProperty("overridden")]
[UniqueIdentityReference]
public string Overridden { get; set; }
[YamlMember(Alias = "overload")]
[JsonProperty("overload")]
[UniqueIdentityReference]
public string Overload { get; set; }
[YamlMember(Alias = "exceptions")]
[JsonProperty("exceptions")]
public List<ExceptionInfo> Exceptions { get; set; }
[YamlMember(Alias = "seealso")]
[JsonProperty("seealso")]
public List<LinkInfo> SeeAlsos { get; set; }
[YamlMember(Alias = "see")]
[JsonProperty("see")]
public List<LinkInfo> Sees { get; set; }
[JsonIgnore]
[YamlIgnore]
[UniqueIdentityReference]
public List<string> SeeAlsosUidReference => SeeAlsos?.Where(s => s.LinkType == LinkType.CRef)?.Select(s => s.LinkId).ToList();
[JsonIgnore]
[YamlIgnore]
[UniqueIdentityReference]
public List<string> SeesUidReference => Sees?.Where(s => s.LinkType == LinkType.CRef)?.Select(s => s.LinkId).ToList();
[YamlMember(Alias = "inheritance")]
[MergeOption(MergeOption.Ignore)]
[JsonProperty("inheritance")]
[UniqueIdentityReference]
public List<string> Inheritance { get; set; }
[YamlMember(Alias = "derivedClasses")]
[MergeOption(MergeOption.Ignore)]
[JsonProperty("derivedClasses")]
[UniqueIdentityReference]
public List<string> DerivedClasses { get; set; }
[YamlMember(Alias = "implements")]
[MergeOption(MergeOption.Ignore)] // todo : merge more children
[JsonProperty("implements")]
[UniqueIdentityReference]
public List<string> Implements { get; set; }
[YamlMember(Alias = "inheritedMembers")]
[MergeOption(MergeOption.Ignore)] // todo : merge more children
[JsonProperty("inheritedMembers")]
[UniqueIdentityReference]
public List<string> InheritedMembers { get; set; }
[YamlMember(Alias = "extensionMethods")]
[MergeOption(MergeOption.Ignore)] // todo : merge more children
[JsonProperty("extensionMethods")]
[UniqueIdentityReference]
public List<string> ExtensionMethods { get; set; }
[ExtensibleMember(Constants.ExtensionMemberPrefix.Modifiers)]
[MergeOption(MergeOption.Ignore)] // todo : merge more children
[JsonIgnore]
public SortedList<string, List<string>> Modifiers { get; set; } = new SortedList<string, List<string>>();
[YamlMember(Alias = Constants.PropertyName.Conceptual)]
[JsonProperty(Constants.PropertyName.Conceptual)]
[MarkdownContent]
public string Conceptual { get; set; }
[YamlMember(Alias = "platform")]
[JsonProperty("platform")]
[MergeOption(MergeOption.Replace)]
public List<string> Platform { get; set; }
[YamlMember(Alias = "attributes")]
[JsonProperty("attributes")]
[MergeOption(MergeOption.Ignore)]
public List<AttributeInfo> Attributes { get; set; }
[ExtensibleMember]
[JsonIgnore]
public Dictionary<string, object> Metadata { get; set; } = new Dictionary<string, object>();
[EditorBrowsable(EditorBrowsableState.Never)]
[YamlIgnore]
[JsonExtensionData]
[UniqueIdentityReferenceIgnore]
[MarkdownContentIgnore]
public CompositeDictionary ExtensionData =>
CompositeDictionary
.CreateBuilder()
.Add(Constants.ExtensionMemberPrefix.Name, Names, JTokenConverter.Convert<string>)
.Add(Constants.ExtensionMemberPrefix.NameWithType, NamesWithType, JTokenConverter.Convert<string>)
.Add(Constants.ExtensionMemberPrefix.FullName, FullNames, JTokenConverter.Convert<string>)
.Add(Constants.ExtensionMemberPrefix.Modifiers, Modifiers, JTokenConverter.Convert<List<string>>)
.Add(string.Empty, Metadata)
.Create();
}
}
| |
// 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.Runtime.InteropServices;
using System.Diagnostics;
using System.DirectoryServices.Interop;
using System.ComponentModel;
using System.Threading;
using System.Reflection;
using System.Security.Permissions;
using System.DirectoryServices.Design;
using System.Globalization;
using System.Net;
namespace System.DirectoryServices
{
/// <devdoc>
/// Encapsulates a node or an object in the Active Directory hierarchy.
/// </devdoc>
[
TypeConverterAttribute(typeof(DirectoryEntryConverter)),
EnvironmentPermission(SecurityAction.Assert, Unrestricted = true),
SecurityPermission(SecurityAction.Assert, Flags = SecurityPermissionFlag.UnmanagedCode),
]
public class DirectoryEntry : Component
{
private string _path = "";
private UnsafeNativeMethods.IAds _adsObject;
private bool _useCache = true;
private bool _cacheFilled;
// disable csharp compiler warning #0414: field assigned unused value
#pragma warning disable 0414
internal bool propertiesAlreadyEnumerated = false;
#pragma warning restore 0414
private bool _disposed = false;
private AuthenticationTypes _authenticationType = AuthenticationTypes.Secure;
private NetworkCredential _credentials;
private readonly DirectoryEntryConfiguration _options;
private PropertyCollection _propertyCollection = null;
internal bool allowMultipleChange = false;
private bool _userNameIsNull = false;
private bool _passwordIsNull = false;
private bool _objectSecurityInitialized = false;
private bool _objectSecurityModified = false;
private ActiveDirectorySecurity _objectSecurity = null;
private static string s_securityDescriptorProperty = "ntSecurityDescriptor";
/// <devdoc>
/// Initializes a new instance of the <see cref='System.DirectoryServices.DirectoryEntry'/>class.
/// </devdoc>
public DirectoryEntry()
{
_options = new DirectoryEntryConfiguration(this);
}
/// <devdoc>
/// Initializes a new instance of the <see cref='System.DirectoryServices.DirectoryEntry'/> class that will bind
/// to the directory entry at <paramref name="path"/>.
/// </devdoc>
public DirectoryEntry(string path) : this()
{
Path = path;
}
/// <devdoc>
/// Initializes a new instance of the <see cref='System.DirectoryServices.DirectoryEntry'/> class.
/// </devdoc>
public DirectoryEntry(string path, string username, string password) : this(path, username, password, AuthenticationTypes.Secure)
{
}
/// <devdoc>
/// Initializes a new instance of the <see cref='System.DirectoryServices.DirectoryEntry'/> class.
/// </devdoc>
public DirectoryEntry(string path, string username, string password, AuthenticationTypes authenticationType) : this(path)
{
_credentials = new NetworkCredential(username, password);
if (username == null)
_userNameIsNull = true;
if (password == null)
_passwordIsNull = true;
_authenticationType = authenticationType;
}
internal DirectoryEntry(string path, bool useCache, string username, string password, AuthenticationTypes authenticationType)
{
_path = path;
_useCache = useCache;
_credentials = new NetworkCredential(username, password);
if (username == null)
_userNameIsNull = true;
if (password == null)
_passwordIsNull = true;
_authenticationType = authenticationType;
_options = new DirectoryEntryConfiguration(this);
}
/// <devdoc>
/// Initializes a new instance of the <see cref='System.DirectoryServices.DirectoryEntry'/> class that will bind
/// to the native Active Directory object which is passed in.
/// </devdoc>
public DirectoryEntry(object adsObject)
: this(adsObject, true, null, null, AuthenticationTypes.Secure, true)
{
}
internal DirectoryEntry(object adsObject, bool useCache, string username, string password, AuthenticationTypes authenticationType)
: this(adsObject, useCache, username, password, authenticationType, false)
{
}
internal DirectoryEntry(object adsObject, bool useCache, string username, string password, AuthenticationTypes authenticationType, bool AdsObjIsExternal)
{
_adsObject = adsObject as UnsafeNativeMethods.IAds;
if (_adsObject == null)
throw new ArgumentException(SR.DSDoesNotImplementIADs);
// GetInfo is not needed here. ADSI executes an implicit GetInfo when GetEx
// is called on the PropertyValueCollection. 0x800704BC error might be returned
// on some WinNT entries, when iterating through 'Users' group members.
// if (forceBind)
// this.adsObject.GetInfo();
_path = _adsObject.ADsPath;
_useCache = useCache;
_authenticationType = authenticationType;
_credentials = new NetworkCredential(username, password);
if (username == null)
_userNameIsNull = true;
if (password == null)
_passwordIsNull = true;
if (!useCache)
CommitChanges();
_options = new DirectoryEntryConfiguration(this);
// We are starting from an already bound connection so make sure the options are set properly.
// If this is an externallly managed com object then we don't want to change it's current behavior
if (!AdsObjIsExternal)
{
InitADsObjectOptions();
}
}
internal UnsafeNativeMethods.IAds AdsObject
{
get
{
Bind();
return _adsObject;
}
}
[DefaultValue(AuthenticationTypes.Secure)]
public AuthenticationTypes AuthenticationType
{
get => _authenticationType;
set
{
if (_authenticationType == value)
return;
_authenticationType = value;
Unbind();
}
}
private bool Bound => _adsObject != null;
/// <devdoc>
/// Gets a <see cref='System.DirectoryServices.DirectoryEntries'/>
/// containing the child entries of this node in the Active
/// Directory hierarchy.
/// </devdoc>
public DirectoryEntries Children => new DirectoryEntries(this);
internal UnsafeNativeMethods.IAdsContainer ContainerObject
{
get
{
Bind();
return (UnsafeNativeMethods.IAdsContainer)_adsObject;
}
}
/// <devdoc>
/// Gets the globally unique identifier of the <see cref='System.DirectoryServices.DirectoryEntry'/>.
/// </devdoc>
public Guid Guid
{
get
{
string guid = NativeGuid;
if (guid.Length == 32)
{
// oddly, the value comes back as a string with no dashes from LDAP
byte[] intGuid = new byte[16];
for (int j = 0; j < 16; j++)
{
intGuid[j] = Convert.ToByte(new String(new char[] { guid[j * 2], guid[j * 2 + 1] }), 16);
}
return new Guid(intGuid);
// return new Guid(guid.Substring(0, 8) + "-" + guid.Substring(8, 4) + "-" + guid.Substring(12, 4) + "-" + guid.Substring(16, 4) + "-" + guid.Substring(20));
}
else
return new Guid(guid);
}
}
public ActiveDirectorySecurity ObjectSecurity
{
get
{
if (!_objectSecurityInitialized)
{
_objectSecurity = GetObjectSecurityFromCache();
_objectSecurityInitialized = true;
}
return _objectSecurity;
}
set
{
if (value == null)
{
throw new ArgumentNullException("value");
}
_objectSecurity = value;
_objectSecurityInitialized = true;
_objectSecurityModified = true;
CommitIfNotCaching();
}
}
internal bool IsContainer
{
get
{
Bind();
return _adsObject is UnsafeNativeMethods.IAdsContainer;
}
}
internal bool JustCreated { get; set; }
/// <devdoc>
/// Gets the relative name of the object as named with the underlying directory service.
/// </devdoc>
public string Name
{
get
{
Bind();
string tmpName = _adsObject.Name;
GC.KeepAlive(this);
return tmpName;
}
}
public string NativeGuid
{
get
{
FillCache("GUID");
string tmpGuid = _adsObject.GUID;
GC.KeepAlive(this);
return tmpGuid;
}
}
/// <devdoc>
/// Gets the native Active Directory Services Interface (ADSI) object.
/// </devdoc>
public object NativeObject
{
get
{
Bind();
return _adsObject;
}
}
/// <devdoc>
/// Gets this entry's parent entry in the Active Directory hierarchy.
/// </devdoc>
public DirectoryEntry Parent
{
get
{
Bind();
return new DirectoryEntry(_adsObject.Parent, UsePropertyCache, GetUsername(), GetPassword(), AuthenticationType);
}
}
/// <devdoc>
/// Gets or sets the password to use when authenticating the client.
/// </devdoc>
[DefaultValue(null)]
public string Password
{
set
{
if (value == GetPassword())
return;
if (_credentials == null)
{
_credentials = new NetworkCredential();
// have not set it yet
_userNameIsNull = true;
}
if (value == null)
_passwordIsNull = true;
else
_passwordIsNull = false;
_credentials.Password = value;
Unbind();
}
}
/// <devdoc>
/// Gets or sets the path for this <see cref='System.DirectoryServices.DirectoryEntry'/>.
/// </devdoc>
[
DefaultValue(""),
// CoreFXPort - Remove design support
// TypeConverter("System.Diagnostics.Design.StringValueConverter, " + AssemblyRef.SystemDesign)
]
public string Path
{
get => _path;
set
{
if (value == null)
value = "";
if (System.DirectoryServices.ActiveDirectory.Utils.Compare(_path, value) == 0)
return;
_path = value;
Unbind();
}
}
/// <devdoc>
/// Gets a <see cref='System.DirectoryServices.PropertyCollection'/> of properties set on this object.
/// </devdoc>
public PropertyCollection Properties
{
get
{
if (_propertyCollection == null)
{
_propertyCollection = new PropertyCollection(this);
}
return _propertyCollection;
}
}
/// <devdoc>
/// Gets the name of the schema used for this <see cref='System.DirectoryServices.DirectoryEntry'/>
/// </devdoc>
public string SchemaClassName
{
get
{
Bind();
string tmpClass = _adsObject.Class;
GC.KeepAlive(this);
return tmpClass;
}
}
/// <devdoc>
/// Gets the <see cref='System.DirectoryServices.DirectoryEntry'/> that holds schema information for this
/// entry. An entry's <see cref='System.DirectoryServices.DirectoryEntry.SchemaClassName'/>
/// determines what properties are valid for it.</para>
/// </devdoc>
public DirectoryEntry SchemaEntry
{
get
{
Bind();
return new DirectoryEntry(_adsObject.Schema, UsePropertyCache, GetUsername(), GetPassword(), AuthenticationType);
}
}
// By default changes to properties are done locally to
// a cache and reading property values is cached after
// the first read. Setting this to false will cause the
// cache to be committed after each operation.
//
/// <devdoc>
/// Gets a value indicating whether the cache should be committed after each
/// operation.
/// </devdoc>
[DefaultValue(true)]
public bool UsePropertyCache
{
get => _useCache;
set
{
if (value == _useCache)
return;
// auto-commit when they set this to false.
if (!value)
CommitChanges();
_cacheFilled = false; // cache mode has been changed
_useCache = value;
}
}
/// <devdoc>
/// Gets or sets the username to use when authenticating the client.</para>
/// </devdoc>
[
DefaultValue(null),
// CoreFXPort - Remove design support
// TypeConverter("System.Diagnostics.Design.StringValueConverter, " + AssemblyRef.SystemDesign)
]
public string Username
{
get
{
if (_credentials == null || _userNameIsNull)
return null;
return _credentials.UserName;
}
set
{
if (value == GetUsername())
return;
if (_credentials == null)
{
_credentials = new NetworkCredential();
_passwordIsNull = true;
}
if (value == null)
_userNameIsNull = true;
else
_userNameIsNull = false;
_credentials.UserName = value;
Unbind();
}
}
public DirectoryEntryConfiguration Options
{
get
{
// only LDAP provider supports IADsObjectOptions, so make the check here
if (!(AdsObject is UnsafeNativeMethods.IAdsObjectOptions))
return null;
return _options;
}
}
internal void InitADsObjectOptions()
{
if (_adsObject is UnsafeNativeMethods.IAdsObjectOptions2)
{
//--------------------------------------------
// Check if ACCUMULATE_MODIFICATION is available
//--------------------------------------------
object o = null;
int unmanagedResult = 0;
// check whether the new option is available
// 8 is ADS_OPTION_ACCUMULATIVE_MODIFICATION
unmanagedResult = ((UnsafeNativeMethods.IAdsObjectOptions2)_adsObject).GetOption(8, out o);
if (unmanagedResult != 0)
{
// rootdse does not support this option and invalid parameter due to without accumulative change fix in ADSI
if ((unmanagedResult == unchecked((int)0x80004001)) || (unmanagedResult == unchecked((int)0x80005008)))
{
return;
}
else
{
throw COMExceptionHelper.CreateFormattedComException(unmanagedResult);
}
}
// the new option is available, set it so we get the new PutEx behavior that will allow multiple changes
Variant value = new Variant();
value.varType = 11; //VT_BOOL
value.boolvalue = -1;
((UnsafeNativeMethods.IAdsObjectOptions2)_adsObject).SetOption(8, value);
allowMultipleChange = true;
}
}
/// <devdoc>
/// Binds to the ADs object (if not already bound).
/// </devdoc>
private void Bind()
{
Bind(true);
}
internal void Bind(bool throwIfFail)
{
//Cannot rebind after the object has been disposed, since finalization has been suppressed.
if (_disposed)
throw new ObjectDisposedException(GetType().Name);
if (_adsObject == null)
{
string pathToUse = Path;
if (pathToUse == null || pathToUse.Length == 0)
{
// get the default naming context. This should be the default root for the search.
DirectoryEntry rootDSE = new DirectoryEntry("LDAP://RootDSE", true, null, null, AuthenticationTypes.Secure);
//SECREVIEW: Looking at the root of the DS will demand browse permissions
// on "*" or "LDAP://RootDSE".
string defaultNamingContext = (string)rootDSE.Properties["defaultNamingContext"][0];
rootDSE.Dispose();
pathToUse = "LDAP://" + defaultNamingContext;
}
// Ensure we've got a thread model set, else CoInitialize() won't have been called.
if (Thread.CurrentThread.GetApartmentState() == ApartmentState.Unknown)
Thread.CurrentThread.SetApartmentState(ApartmentState.MTA);
Guid g = new Guid("00000000-0000-0000-c000-000000000046"); // IID_IUnknown
object value = null;
int hr = UnsafeNativeMethods.ADsOpenObject(pathToUse, GetUsername(), GetPassword(), (int)_authenticationType, ref g, out value);
if (hr != 0)
{
if (throwIfFail)
throw COMExceptionHelper.CreateFormattedComException(hr);
}
else
{
_adsObject = (UnsafeNativeMethods.IAds)value;
}
InitADsObjectOptions();
}
}
// Create new entry with the same data, but different IADs object, and grant it Browse Permission.
internal DirectoryEntry CloneBrowsable()
{
DirectoryEntry newEntry = new DirectoryEntry(this.Path, this.UsePropertyCache, this.GetUsername(), this.GetPassword(), this.AuthenticationType);
return newEntry;
}
/// <devdoc>
/// Closes the <see cref='System.DirectoryServices.DirectoryEntry'/>
/// and releases any system resources associated with this component.
/// </devdoc>
public void Close()
{
Unbind();
}
/// <devdoc>
/// Saves any changes to the entry in the directory store.
/// </devdoc>
public void CommitChanges()
{
if (JustCreated)
{
// Note: Permissions Demand is not necessary here, because entry has already been created with appr. permissions.
// Write changes regardless of Caching mode to finish construction of a new entry.
try
{
//
// Write the security descriptor to the cache
//
SetObjectSecurityInCache();
_adsObject.SetInfo();
}
catch (COMException e)
{
throw COMExceptionHelper.CreateFormattedComException(e);
}
JustCreated = false;
_objectSecurityInitialized = false;
_objectSecurityModified = false;
// we need to refresh that properties table.
_propertyCollection = null;
return;
}
if (!_useCache)
{
// unless we have modified the existing security descriptor (in-place) through ObjectSecurity property
// there is nothing to do
if ((_objectSecurity == null) || (!_objectSecurity.IsModified()))
{
return;
}
}
if (!Bound)
return;
try
{
//
// Write the security descriptor to the cache
//
SetObjectSecurityInCache();
_adsObject.SetInfo();
_objectSecurityInitialized = false;
_objectSecurityModified = false;
}
catch (COMException e)
{
throw COMExceptionHelper.CreateFormattedComException(e);
}
// we need to refresh that properties table.
_propertyCollection = null;
}
internal void CommitIfNotCaching()
{
if (JustCreated)
return; // Do not write changes, beacuse the entry is just under construction until CommitChanges() is called.
if (_useCache)
return;
if (!Bound)
return;
try
{
//
// Write the security descriptor to the cache
//
SetObjectSecurityInCache();
_adsObject.SetInfo();
_objectSecurityInitialized = false;
_objectSecurityModified = false;
}
catch (COMException e)
{
throw COMExceptionHelper.CreateFormattedComException(e);
}
// we need to refresh that properties table.
_propertyCollection = null;
}
/// <devdoc>
/// Creates a copy of this entry as a child of the given parent.
/// </devdoc>
public DirectoryEntry CopyTo(DirectoryEntry newParent) => CopyTo(newParent, null);
/// <devdoc>
/// Creates a copy of this entry as a child of the given parent and gives it a new name.
/// </devdoc>
public DirectoryEntry CopyTo(DirectoryEntry newParent, string newName)
{
if (!newParent.IsContainer)
throw new InvalidOperationException(SR.Format(SR.DSNotAContainer , newParent.Path));
object copy = null;
try
{
copy = newParent.ContainerObject.CopyHere(Path, newName);
}
catch (COMException e)
{
throw COMExceptionHelper.CreateFormattedComException(e);
}
return new DirectoryEntry(copy, newParent.UsePropertyCache, GetUsername(), GetPassword(), AuthenticationType);
}
/// <devdoc>
/// Deletes this entry and its entire subtree from the Active Directory hierarchy.
/// </devdoc>
public void DeleteTree()
{
if (!(AdsObject is UnsafeNativeMethods.IAdsDeleteOps))
throw new InvalidOperationException(SR.DSCannotDelete);
UnsafeNativeMethods.IAdsDeleteOps entry = (UnsafeNativeMethods.IAdsDeleteOps)AdsObject;
try
{
entry.DeleteObject(0);
}
catch (COMException e)
{
throw COMExceptionHelper.CreateFormattedComException(e);
}
GC.KeepAlive(this);
}
protected override void Dispose(bool disposing)
{
// no managed object to free
// free own state (unmanaged objects)
if (!_disposed)
{
Unbind();
_disposed = true;
}
base.Dispose(disposing);
}
/// <devdoc>
/// Searches the directory store at the given path to see whether an entry exists.
/// </devdoc>
public static bool Exists(string path)
{
DirectoryEntry entry = new DirectoryEntry(path);
try
{
entry.Bind(true); // throws exceptions (possibly can break applications)
return entry.Bound;
}
catch (System.Runtime.InteropServices.COMException e)
{
if (e.ErrorCode == unchecked((int)0x80072030) ||
e.ErrorCode == unchecked((int)0x80070003) || // ERROR_DS_NO_SUCH_OBJECT and path not found (not found in strict sense)
e.ErrorCode == unchecked((int)0x800708AC)) // Group name could not be found
return false;
throw;
}
finally
{
entry.Dispose();
}
}
/// <devdoc>
/// If UsePropertyCache is true, calls GetInfo the first time it's necessary.
/// If it's false, calls GetInfoEx on the given property name.
/// </devdoc>
internal void FillCache(string propertyName)
{
if (UsePropertyCache)
{
if (_cacheFilled)
return;
RefreshCache();
_cacheFilled = true;
}
else
{
Bind();
try
{
if (propertyName.Length > 0)
_adsObject.GetInfoEx(new object[] { propertyName }, 0);
else
_adsObject.GetInfo();
}
catch (COMException e)
{
throw COMExceptionHelper.CreateFormattedComException(e);
}
}
}
/// <devdoc>
/// Calls a method on the native Active Directory.
/// </devdoc>
public object Invoke(string methodName, params object[] args)
{
object target = this.NativeObject;
Type type = target.GetType();
object result = null;
try
{
result = type.InvokeMember(methodName, BindingFlags.InvokeMethod, null, target, args, CultureInfo.InvariantCulture);
GC.KeepAlive(this);
}
catch (COMException e)
{
throw COMExceptionHelper.CreateFormattedComException(e);
}
catch (TargetInvocationException e)
{
if (e.InnerException != null)
{
if (e.InnerException is COMException)
{
COMException inner = (COMException)e.InnerException;
throw new TargetInvocationException(e.Message, COMExceptionHelper.CreateFormattedComException(inner));
}
}
throw e;
}
if (result is UnsafeNativeMethods.IAds)
return new DirectoryEntry(result, UsePropertyCache, GetUsername(), GetPassword(), AuthenticationType);
else
return result;
}
/// <devdoc>
/// Reads a property on the native Active Directory object.
/// </devdoc>
public object InvokeGet(string propertyName)
{
object target = this.NativeObject;
Type type = target.GetType();
object result = null;
try
{
result = type.InvokeMember(propertyName, BindingFlags.GetProperty, null, target, null, CultureInfo.InvariantCulture);
GC.KeepAlive(this);
}
catch (COMException e)
{
throw COMExceptionHelper.CreateFormattedComException(e);
}
catch (TargetInvocationException e)
{
if (e.InnerException != null)
{
if (e.InnerException is COMException)
{
COMException inner = (COMException)e.InnerException;
throw new TargetInvocationException(e.Message, COMExceptionHelper.CreateFormattedComException(inner));
}
}
throw e;
}
return result;
}
/// <devdoc>
/// Sets a property on the native Active Directory object.
/// </devdoc>
public void InvokeSet(string propertyName, params object[] args)
{
object target = this.NativeObject;
Type type = target.GetType();
try
{
type.InvokeMember(propertyName, BindingFlags.SetProperty, null, target, args, CultureInfo.InvariantCulture);
GC.KeepAlive(this);
}
catch (COMException e)
{
throw COMExceptionHelper.CreateFormattedComException(e);
}
catch (TargetInvocationException e)
{
if (e.InnerException != null)
{
if (e.InnerException is COMException)
{
COMException inner = (COMException)e.InnerException;
throw new TargetInvocationException(e.Message, COMExceptionHelper.CreateFormattedComException(inner));
}
}
throw e;
}
}
/// <devdoc>
/// Moves this entry to the given parent.
/// </devdoc>
public void MoveTo(DirectoryEntry newParent) => MoveTo(newParent, null);
/// <devdoc>
/// Moves this entry to the given parent, and gives it a new name.
/// </devdoc>
public void MoveTo(DirectoryEntry newParent, string newName)
{
object newEntry = null;
if (!(newParent.AdsObject is UnsafeNativeMethods.IAdsContainer))
throw new InvalidOperationException(SR.Format(SR.DSNotAContainer , newParent.Path));
try
{
if (AdsObject.ADsPath.StartsWith("WinNT:", StringComparison.Ordinal))
{
// get the ADsPath instead of using Path as ADsPath for the case that "WinNT://computername" is passed in while we need "WinNT://domain/computer"
string childPath = AdsObject.ADsPath;
string parentPath = newParent.AdsObject.ADsPath;
// we know ADsPath does not end with object type qualifier like ",computer" so it is fine to compare with whole newparent's adspath
// for the case that child has different components from newparent in the aspects other than case, we don't do any processing, just let ADSI decide in case future adsi change
if (System.DirectoryServices.ActiveDirectory.Utils.Compare(childPath, 0, parentPath.Length, parentPath, 0, parentPath.Length) == 0)
{
uint compareFlags = System.DirectoryServices.ActiveDirectory.Utils.NORM_IGNORENONSPACE |
System.DirectoryServices.ActiveDirectory.Utils.NORM_IGNOREKANATYPE |
System.DirectoryServices.ActiveDirectory.Utils.NORM_IGNOREWIDTH |
System.DirectoryServices.ActiveDirectory.Utils.SORT_STRINGSORT;
// work around the ADSI case sensitive
if (System.DirectoryServices.ActiveDirectory.Utils.Compare(childPath, 0, parentPath.Length, parentPath, 0, parentPath.Length, compareFlags) != 0)
{
childPath = parentPath + childPath.Substring(parentPath.Length);
}
}
newEntry = newParent.ContainerObject.MoveHere(childPath, newName);
}
else
{
newEntry = newParent.ContainerObject.MoveHere(Path, newName);
}
}
catch (COMException e)
{
throw COMExceptionHelper.CreateFormattedComException(e);
}
if (Bound)
System.Runtime.InteropServices.Marshal.ReleaseComObject(_adsObject); // release old handle
_adsObject = (UnsafeNativeMethods.IAds)newEntry;
_path = _adsObject.ADsPath;
// Reset the options on the ADSI object since there were lost when the new object was created.
InitADsObjectOptions();
if (!_useCache)
CommitChanges();
else
RefreshCache(); // in ADSI cache is lost after moving
}
/// <devdoc>
/// Loads the property values for this directory entry into the property cache.
/// </devdoc>
public void RefreshCache()
{
Bind();
try
{
_adsObject.GetInfo();
}
catch (COMException e)
{
throw COMExceptionHelper.CreateFormattedComException(e);
}
_cacheFilled = true;
// we need to refresh that properties table.
_propertyCollection = null;
// need to refresh the objectSecurity property
_objectSecurityInitialized = false;
_objectSecurityModified = false;
}
/// <devdoc>
/// Loads the values of the specified properties into the property cache.
/// </devdoc>
public void RefreshCache(string[] propertyNames)
{
Bind();
//Consider there shouldn't be any marshaling issues
//by just doing: AdsObject.GetInfoEx(object[]propertyNames, 0);
Object[] names = new Object[propertyNames.Length];
for (int i = 0; i < propertyNames.Length; i++)
names[i] = propertyNames[i];
try
{
AdsObject.GetInfoEx(names, 0);
}
catch (COMException e)
{
throw COMExceptionHelper.CreateFormattedComException(e);
}
// this is a half-lie, but oh well. Without it, this method is pointless.
_cacheFilled = true;
// we need to partially refresh that properties table.
if (_propertyCollection != null && propertyNames != null)
{
for (int i = 0; i < propertyNames.Length; i++)
{
if (propertyNames[i] != null)
{
string name = propertyNames[i].ToLower(CultureInfo.InvariantCulture);
_propertyCollection.valueTable.Remove(name);
// also need to consider the range retrieval case
string[] results = name.Split(new char[] { ';' });
if (results.Length != 1)
{
string rangeName = "";
for (int count = 0; count < results.Length; count++)
{
if (!results[count].StartsWith("range=", StringComparison.Ordinal))
{
rangeName += results[count];
rangeName += ";";
}
}
// remove the last ';' character
rangeName = rangeName.Remove(rangeName.Length - 1, 1);
_propertyCollection.valueTable.Remove(rangeName);
}
// if this is "ntSecurityDescriptor" we should refresh the objectSecurity property
if (String.Compare(propertyNames[i], s_securityDescriptorProperty, StringComparison.OrdinalIgnoreCase) == 0)
{
_objectSecurityInitialized = false;
_objectSecurityModified = false;
}
}
}
}
}
/// <devdoc>
/// Changes the name of this entry.
/// </devdoc>
public void Rename(string newName) => MoveTo(Parent, newName);
private void Unbind()
{
if (_adsObject != null)
System.Runtime.InteropServices.Marshal.ReleaseComObject(_adsObject);
_adsObject = null;
// we need to release that properties table.
_propertyCollection = null;
// need to refresh the objectSecurity property
_objectSecurityInitialized = false;
_objectSecurityModified = false;
}
internal string GetUsername()
{
if (_credentials == null || _userNameIsNull)
return null;
return _credentials.UserName;
}
internal string GetPassword()
{
if (_credentials == null || _passwordIsNull)
return null;
return _credentials.Password;
}
private ActiveDirectorySecurity GetObjectSecurityFromCache()
{
try
{
//
// This property is the managed version of the "ntSecurityDescriptor"
// attribute. In order to build an ActiveDirectorySecurity object from it
// we need to get the binary form of the security descriptor.
// If we use IADs::Get to get the IADsSecurityDescriptor interface and then
// convert to raw form, there would be a performance overhead (because of
// sid lookups and reverse lookups during conversion).
// So to get the security descriptor in binary form, we use
// IADsPropertyList::GetPropertyItem
//
//
// GetPropertyItem does not implicitly fill the property cache
// so we need to fill it explicitly (for an existing entry)
//
if (!JustCreated)
{
SecurityMasks securityMasksUsedInRetrieval;
//
// To ensure that we honor the security masks while retrieving
// the security descriptor, we will retrieve the "ntSecurityDescriptor" each time
// while initializing the ObjectSecurity property
//
securityMasksUsedInRetrieval = this.Options.SecurityMasks;
RefreshCache(new string[] { s_securityDescriptorProperty });
//
// Get the IAdsPropertyList interface
// (Check that the IAdsPropertyList interface is supported)
//
if (!(NativeObject is UnsafeNativeMethods.IAdsPropertyList))
throw new NotSupportedException(SR.DSPropertyListUnsupported);
UnsafeNativeMethods.IAdsPropertyList list = (UnsafeNativeMethods.IAdsPropertyList)NativeObject;
UnsafeNativeMethods.IAdsPropertyEntry propertyEntry = (UnsafeNativeMethods.IAdsPropertyEntry)list.GetPropertyItem(s_securityDescriptorProperty, (int)AdsType.ADSTYPE_OCTET_STRING);
GC.KeepAlive(this);
//
// Create a new ActiveDirectorySecurity object from the binary form
// of the security descriptor
//
object[] values = (object[])propertyEntry.Values;
//
// This should never happen. It indicates that there is a problem in ADSI's property cache logic.
//
if (values.Length < 1)
{
Debug.Fail("ntSecurityDescriptor property exists in cache but has no values.");
throw new InvalidOperationException(SR.DSSDNoValues);
}
//
// Do not support more than one security descriptor
//
if (values.Length > 1)
{
throw new NotSupportedException(SR.DSMultipleSDNotSupported);
}
UnsafeNativeMethods.IAdsPropertyValue propertyValue = (UnsafeNativeMethods.IAdsPropertyValue)values[0];
return new ActiveDirectorySecurity((byte[])propertyValue.OctetString, securityMasksUsedInRetrieval);
}
else
{
//
// Newly created directory entry
//
return null;
}
}
catch (System.Runtime.InteropServices.COMException e)
{
if (e.ErrorCode == unchecked((int)0x8000500D)) // property not found exception
return null;
else
throw;
}
}
private void SetObjectSecurityInCache()
{
if ((_objectSecurity != null) && (_objectSecurityModified || _objectSecurity.IsModified()))
{
UnsafeNativeMethods.IAdsPropertyValue sDValue = (UnsafeNativeMethods.IAdsPropertyValue)new UnsafeNativeMethods.PropertyValue();
sDValue.ADsType = (int)AdsType.ADSTYPE_OCTET_STRING;
sDValue.OctetString = _objectSecurity.GetSecurityDescriptorBinaryForm();
UnsafeNativeMethods.IAdsPropertyEntry newSDEntry = (UnsafeNativeMethods.IAdsPropertyEntry)new UnsafeNativeMethods.PropertyEntry();
newSDEntry.Name = s_securityDescriptorProperty;
newSDEntry.ADsType = (int)AdsType.ADSTYPE_OCTET_STRING;
newSDEntry.ControlCode = (int)AdsPropertyOperation.Update;
newSDEntry.Values = new object[] { sDValue };
((UnsafeNativeMethods.IAdsPropertyList)NativeObject).PutPropertyItem(newSDEntry);
}
}
}
}
| |
using System;
using System.Text;
using System.Collections.Generic;
using System.Linq;
using EmergeTk.Model;
using SolrNet;
using SolrNet.Commands;
using SolrNet.Commands.Parameters;
using SolrNet.Impl;
using SolrNet.Impl.FieldSerializers;
using System.Xml;
using System.Threading;
using SolrNet.Impl.QuerySerializers;
using SolrNet.Impl.FacetQuerySerializers;
namespace EmergeTk.Model.Search
{
public class SolrSearchProvider : ISearchServiceProvider
{
private static readonly EmergeTkLog log = EmergeTkLogManager.GetLogger(typeof(SolrSearchProvider));
private static readonly EmergeTkLog queryLog = EmergeTkLogManager.GetLogger("SolrQueries");
[ThreadStaticAttribute]
private static StopWatch solrWatch; // keep track of time spent in HTTP call
[ThreadStaticAttribute]
private static StopWatch parseWatch; // track time it takes us to parse.
[ThreadStaticAttribute]
private static StopWatch providerWatch; // track time it takes us to do ancillary SOLR provider operations.
public static StopWatch SolrWatch
{
get
{
if (solrWatch == null)
{
solrWatch = new StopWatch("SOLR Calls", "SOLR HTTP Call Time");
}
return solrWatch;
}
}
public static StopWatch ProviderWatch
{
get
{
if (providerWatch == null)
{
providerWatch = new StopWatch("SOLR Provider", "SOLR Provider Ancillary operations time");
}
return providerWatch;
}
}
public static StopWatch ParseWatch
{
get
{
if (parseWatch == null)
{
parseWatch = new StopWatch("Parse SOLR Responses", "SOLR Response Parse Time");
}
return parseWatch;
}
}
string connectionString;
bool commitEnabled = true;
SearchSerializerTestHook testHook = null;
public bool CommitEnabled
{
get
{
return commitEnabled;
}
set
{
commitEnabled = value;
}
}
public SearchSerializerTestHook TestHook
{
set
{
testHook = value;
}
}
public SolrSearchProvider()
{
connectionString = Setting.GetValueT<String>("SolrConnectionString","http://localhost:8983/solr");
}
private SolrConnection GetConnection()
{
SolrConnection conn = new SolrConnection(connectionString);
int solrTimeOut = Setting.GetValueT<int>("SolrConnectionTimeout", -1);
conn.Timeout = solrTimeOut;
return conn;
}
object throttleLock = new object ();
private void ExecuteCommand( ISolrCommand cmd )
{
lock (throttleLock)
{
log.Debug("executing command ", cmd );
ISolrConnection conn = GetConnection();
cmd.Execute(conn);
log.Debug("done executing command, comitting.");
Commit();
log.Debug("committed");
Thread.Sleep (30);
}
}
public void Commit()
{
if (commitEnabled)
{
lock (throttleLock)
{
CommitCommand cmd = new CommitCommand();
SolrConnection conn = GetConnection();
cmd.Execute(conn);
Thread.Sleep (30);
}
}
}
#region ISearchServiceProvider implementation
public void GenerateIndex (IRecordList elements)
{
if (testHook == null)
{
AddCommand<AbstractRecord> cmd = new AddCommand<AbstractRecord>(elements.ToArray().Select(r=> new KeyValuePair<AbstractRecord, double?>(r, null)), new EmergeTkSolrSerializer<AbstractRecord>());
ExecuteCommand(cmd);
}
else
{
EmergeTkSolrSerializer<AbstractRecord> serializer = new EmergeTkSolrSerializer<AbstractRecord>();
foreach (AbstractRecord r in elements)
{
testHook(serializer.Serialize(r, null));
}
}
}
public void GenerateIndex (AbstractRecord r)
{
AddCommand<AbstractRecord> cmd = new AddCommand<AbstractRecord>(new KeyValuePair<AbstractRecord, double?>[]{new KeyValuePair<AbstractRecord, double?>(r, null)}, new EmergeTkSolrSerializer<AbstractRecord>());
ExecuteCommand(cmd);
}
public void Delete (AbstractRecord r)
{
DeleteCommand cmd = new DeleteCommand(new DeleteByIdAndOrQueryParam(new string[] { r.GetType().FullName + "." + r.Id }, null, null));
ExecuteCommand(cmd);
}
public void Delete (IRecordList elements)
{
List<string> deleteList = new List<string>();
foreach( AbstractRecord r in elements )
{
deleteList.Add( r.GetType().FullName + "." + r.Id );
}
DeleteCommand cmd = new DeleteCommand(new DeleteByIdAndOrQueryParam(deleteList.ToArray(), null, null));
ExecuteCommand(cmd);
}
public void DeleteAll()
{
DeleteByQuery("*:*");
}
public void DeleteAllOfType<T>()
{
DeleteByQuery("RecordType:" + typeof(T).FullName );
}
public void DeleteByQuery(string query)
{
DeleteCommand cmd = new DeleteCommand(new DeleteByIdAndOrQueryParam(null, new SolrQuery(query), new DefaultQuerySerializer(new DefaultFieldSerializer())));
ExecuteCommand(cmd);
}
public IRecordList Search (string field, string key)
{
return Search(string.Format("{0}:{1}", field, key));
}
private SolrQueryExecuter<T> GetExecuterT<T>(ISolrQueryResultParser<T> parser)
{
SolrConnection conn = GetConnection();
ISolrFieldSerializer fieldSerializer = new DefaultFieldSerializer();
ISolrQuerySerializer querySerializer = new DefaultQuerySerializer(fieldSerializer);
ISolrFacetQuerySerializer facetQuerySerializer = new DefaultFacetQuerySerializer(querySerializer, fieldSerializer);
return new SolrQueryExecuter<T>(parser, conn, querySerializer, facetQuerySerializer);
}
public IRecordList Search( string query )
{
SolrQuery q = new SolrQuery( query );
SolrQueryExecuter<RecordKey> queryExec = GetExecuterT<RecordKey>(new EmergeTkFastParser());
ISolrQueryResults<RecordKey> results = queryExec.Execute( q, new QueryOptions() );
RecordList list = new RecordList();
foreach( RecordKey k in results )
{
AbstractRecord r = k.ToRecord();
if( r != null )
list.Add( r );
else
{
log.Warn("Did not load record key ", k);
}
//log.Debug("Adding record to search results", r);
}
return list;
}
public void Optimize()
{
OptimizeCommand oc = new OptimizeCommand();
oc.Execute(GetConnection());
}
public IRecordList<T> Search<T> (string field, string key, System.Collections.Generic.List<string> types) where T : AbstractRecord, new()
{
RecordList<T> result = new RecordList<T>();
foreach(T r in Search<T>(string.Format("{0}:{1}", field, key)) )
{
if( types.Contains( r.GetType().FullName ) )
{
result.Add( r );
}
}
return result;
}
public IRecordList<T> Search<T> (string field, string key) where T : AbstractRecord, new()
{
return Search<T>(string.Format("{0}:{1} RecordType:{2}", field, key, typeof(T).FullName));
}
public IRecordList<T> Search<T> (string query) where T : AbstractRecord, new()
{
SolrQuery q = new SolrQuery( query + " RecordType:" + typeof(T).FullName);
SolrQueryExecuter<T> queryExec = GetExecuterT<T>(new EmergeTkParser<T>());
ISolrQueryResults<T> results = queryExec.Execute( q, new QueryOptions() );
RecordList<T> list = new RecordList<T>();
foreach( T t in results )
{
list.Add( t );
//log.Debug("adding result", t );
}
return list;
}
public IRecordList<T> Search<T>( string query, SortInfo sort, int start, int count, out int numFound ) where T : AbstractRecord, new()
{
log.Info("Executing solr query: ", query );
QueryOptions options = new QueryOptions();
options.Start = start;
options.Rows = count;
if( sort != null )
{
SortOrder so = new SortOrder( sort.ColumnName, sort.Direction == SortDirection.Ascending ? Order.ASC : Order.DESC );
options.AddOrder( so );
}
SolrConnection conn = GetConnection();
SolrQuery q = new SolrQuery( query + " RecordType:" + typeof(T).FullName );
SolrQueryExecuter<T> queryExec = GetExecuterT<T>(new EmergeTkParser<T>());
ISolrQueryResults<T> results = queryExec.Execute( q, options );
RecordList<T> list = new RecordList<T>();
foreach( T t in results )
{
list.Add( t );
log.Debug("adding result", t );
}
log.DebugFormat("SOLR numFound: {0} # Records: {1} ", results.NumFound, list.Count );
numFound = results.NumFound;
return list;
}
/// <summary>
/// SearchInt - simple interface for returning list of recordkeys.
/// </summary>
/// <param name="field">
/// A <see cref="System.String"/> default field to search. - ignored by this
/// implementation.
/// </param>
/// <param name="query">
/// A <see cref="System.String"/> the query to search solr for.
/// </param>
/// <param name="type">
/// A <see cref="System.String"/> filter to objects of this type.
/// </param>
/// <param name="pageNumber">
/// A <see cref="System.Int32"/> a page number to start, -1 to ignore.
/// </param>
/// <param name="pageSize">
/// A <see cref="System.Int32"/> number of records to return for the given page. -1 to ignore.
/// </param>
/// <param name="sort">
/// A <see cref="SortInfo"/> specify sorting criteria. optional.
/// </param>
/// <returns>
/// A <see cref="List"/> A list of recordkeys describing the resultset.
/// </returns>
public List<RecordKey> SearchInt (string field, string query, string type, SortInfo[] sorts, int start, int count, out int numFound )
{
QueryOptions options = SimpleQueryOptions(sorts, start, count, null);
return SearchInt(query, type, options, out numFound);
}
/// <summary>
/// Generates log-suitable string from SOLR query.
/// </summary>
/// <param name="query">SolrQuery string</param>
/// <param name="options">SolrNet QueryOptions object</param>
/// <returns></returns>
private void SolrQLogString(String query, QueryOptions options)
{
if (options.FilterQueries == null || options.FilterQueries.Count == 0)
{
queryLog.InfoFormat("Issuing SOLR query = {0}", query);
return;
}
StopWatch watch = new StopWatch("SolrQLogString", queryLog);
watch.Start();
StringBuilder sb = new StringBuilder(query + "&");
IEnumerable<String> fqs = options.FilterQueries.Select(q => String.Format("fq={0}", ((SolrQuery)q).Query));
sb.Append(String.Join("&", fqs.ToArray()));
watch.Stop();
queryLog.InfoFormat("Issuing SOLR query = {0}", sb.ToString());
}
/// <summary>
/// shared legacy function for simple SearchInt() functionality.
/// </summary>
/// <param name="query">query in string form</param>
/// <param name="type">type of record to return</param>
/// <param name="options">SolrNet query options object</param>
/// <param name="numFound">count of entire number of records present</param>
/// <returns>List of RecordKey's, maxcount will be the count in the options
/// parameter
/// </returns>
private List<RecordKey> SearchInt(string query, String type, QueryOptions options, out int numFound )
{
SolrSearchProvider.ProviderWatch.Start();
StopWatch watch = new StopWatch("SolrSearchProvider.SearchInt", queryLog);
watch.Start();
SolrQLogString(query, options);
if (type != null)
query += " RecordType:" + type;
SolrConnection conn = GetConnection();
SolrQuery q = new SolrQuery(query);
SolrQueryExecuter<RecordKey> queryExec = GetExecuterT<RecordKey>(new EmergeTkFastParser());
SolrSearchProvider.ProviderWatch.Stop();
SolrSearchProvider.SolrWatch.Start(); // parser will stop this watch.
ISolrQueryResults<RecordKey> results = queryExec.Execute(q, options);
SolrSearchProvider.ProviderWatch.Start();
numFound = results.NumFound;
log.InfoFormat("SOLR returned {0} total result(s), count {1}", results.NumFound, results.Count);
List<RecordKey> list = new List<RecordKey>();
foreach (RecordKey rk in results)
{
//log.Debug("Adding result", rk );
list.Add(rk);
}
watch.Lap("Completed SOLR call");
watch.Stop();
SolrSearchProvider.ProviderWatch.Stop();
return list;
}
/// <summary>
/// private function returns queryoptions object for simple case, where we just
/// need a sort, start, and count.
/// </summary>
/// <param name="sorts">array of sort criteria</param>
/// <param name="start">offset into results to return</param>
/// <param name="count">count of results to return</param>
/// <returns></returns>
private QueryOptions SimpleQueryOptions(SortInfo[] sorts, int start, int count, FilterSet cachedQueries)
{
SolrSearchProvider.ProviderWatch.Start();
QueryOptions options = new QueryOptions();
if (sorts != null)
{
foreach (SortInfo sort in sorts)
{
SortOrder so = new SortOrder(sort.ColumnName, sort.Direction == SortDirection.Ascending ? Order.ASC : Order.DESC);
options.AddOrder(so);
}
}
if (start != -1)
options.Start = start;
if (count != -1)
options.Rows = count;
AddCachedQueries(options, cachedQueries);
SolrSearchProvider.ProviderWatch.Stop();
return options;
}
/// <summary>
/// Function that the emergeTk gallery calls to do searching - returns a list of
/// recordkeys only; then the entire objects are reconstituted from the data
/// layer.
/// </summary>
/// <param name="field">
/// A <see cref="System.String"/> default field to search.
/// </param>
/// <param name="mainQuery">
/// A <see cref="Chaos.Model.FilterSet"/> the dynamic part of the query to
/// search for.
/// </param>
/// <param name="cachedQuery">
/// A <see cref="Chaos.Model.FilterSet"/> set of predicates to be implemented as
/// filter queries. These are things we believe SOLR can effectively cache.
/// </param>
/// <param name="type">
/// A <see cref="System.String"/> filter to objects of this type.
/// </param>
/// <param name="pageNumber">
/// A <see cref="System.Int32"/> a page number to start, -1 to ignore.
/// </param>
/// <param name="pageSize">
/// A <see cref="System.Int32"/> number of records to return for the given page. -1 to ignore.
/// </param>
/// <param name="sort">
/// A <see cref="SortInfo"/> specify sorting criteria. optional.
/// </param>
/// <returns>
/// A <see cref="List"/> A list of recordkeys describing the resultset.
/// </returns>
public List<RecordKey> SearchInt(string field, FilterSet mainQuery, FilterSet cachedQuery, string type, SortInfo[] sorts, int start, int count, out int numFound)
{
String query = GetFilterFormatter().BuildQuery(mainQuery);
QueryOptions options = SimpleQueryOptions(sorts, start, count, cachedQuery);
return SearchInt(query, type, options, out numFound);
}
public ISearchFilterFormatter GetFilterFormatter()
{
return new SolrFilterFormatter();
}
public ISearchProviderQueryResults<T> Search<T>(String query, FilterSet cachedQuery, ISearchOptions options) where T : AbstractRecord, new()
{
SolrSearchProvider.ProviderWatch.Start();
StopWatch watch = new StopWatch("SolrSearchProvider.Search<T>", queryLog);
watch.Start();
QueryOptions queryOptions = PrepareQueryOptions(ref query, options, cachedQuery);
SolrQLogString(query, queryOptions);
SolrConnection conn = GetConnection();
SolrQuery q = new SolrQuery(query);
SolrQueryExecuter<T> queryExec = GetExecuterT<T>(new EmergeTkParser<T>(options));
SolrSearchProvider.ProviderWatch.Stop();
SolrSearchProvider.SolrWatch.Start();
ISolrQueryResults<T> resultsSolrNet = queryExec.Execute(q, queryOptions);
watch.Lap(String.Format("SOLR returned results - numFound = {0}", resultsSolrNet.NumFound));
SolrSearchProvider.ProviderWatch.Start();
SolrSearchProviderQueryResults<T> results = new SolrSearchProviderQueryResults<T>();
results.Results = resultsSolrNet;
results.Facets = resultsSolrNet.FacetFields;
results.FacetQueries = resultsSolrNet.FacetQueries;
results.NumFound = resultsSolrNet.NumFound;
if (options.MoreLikeThis != null)
{
Dictionary<T, int> moreLikeThisOrder = new Dictionary<T, int>();
foreach (KeyValuePair<String, IList<T>> kvp in resultsSolrNet.SimilarResults)
{
// we don't care about kvp.Key - it's the original result doc; we're throwing
// away that relationship for now.
IList<T> list = kvp.Value;
foreach (T t in list)
{
if (moreLikeThisOrder.ContainsKey(t))
moreLikeThisOrder[t]++;
else // never been seen before, add it.
moreLikeThisOrder[t] = 1;
}
}
results.MoreLikeThisOrder = moreLikeThisOrder;
}
watch.Lap("Completed SOLR call");
watch.Stop();
SolrSearchProvider.ProviderWatch.Stop();
return results;
}
private IEnumerable<int> GetRecordIds<T>(Dictionary<T, int> dict, Func<T, int> selector)
{
foreach (KeyValuePair<T, int> kvp in dict)
yield return selector(kvp.Key);
}
public ISearchProviderQueryResults<RecordKey> SearchInt(String query, FilterSet cachedQuery, ISearchOptions options)
{
SolrSearchProvider.ProviderWatch.Start();
StopWatch watch = new StopWatch("SolrSearchProvider.SearchInt<RecordKey>", queryLog);
watch.Start();
QueryOptions queryOptions = PrepareQueryOptions(ref query, options, cachedQuery);
SolrQLogString(query, queryOptions);
SolrConnection conn = GetConnection();
SolrQuery q = new SolrQuery(query);
SolrQueryExecuter<RecordKey> queryExec = GetExecuterT<RecordKey>(new EmergeTkFastParser(options));
SolrSearchProvider.ProviderWatch.Stop();
SolrSearchProvider.SolrWatch.Start();
ISolrQueryResults<RecordKey> resultsSolrNet = queryExec.Execute(q, queryOptions);
SolrSearchProvider.ProviderWatch.Start();
log.Info("SOLR numFound: ", resultsSolrNet.NumFound);
SolrSearchProviderQueryResults<RecordKey> results = new SolrSearchProviderQueryResults<RecordKey>();
results.Results = resultsSolrNet;
results.Facets = resultsSolrNet.FacetFields;
results.FacetQueries = resultsSolrNet.FacetQueries;
results.NumFound = resultsSolrNet.NumFound;
if (options.MoreLikeThis != null)
{
Dictionary<RecordKey, int> moreLikeThisOrder = new Dictionary<RecordKey, int>();
foreach (KeyValuePair<string, IList<RecordKey>> kvp in resultsSolrNet.SimilarResults)
{
// we don't care about kvp.Key - it's the original result doc; we're throwing
// away that relationship for now.
IList<RecordKey> list = kvp.Value;
foreach (RecordKey t in list)
{
if (moreLikeThisOrder.ContainsKey(t))
moreLikeThisOrder[t]++;
else // never been seen before, add it.
moreLikeThisOrder[t] = 1;
}
}
results.MoreLikeThisOrder = moreLikeThisOrder;
}
watch.Lap("Completed SOLR call");
watch.Stop();
SolrSearchProvider.ProviderWatch.Stop();
return results;
}
public ISearchOptions GenerateOptionsObject()
{
return new SolrSearchOptions();
}
public IFacets GenerateFacetsObject()
{
return new SolrFacets();
}
public IMoreLikeThis GenerateMoreLikeThisObject()
{
return new SolrMoreLikeThis();
}
private void SetSorts(QueryOptions queryOptions, IEnumerable<SortInfo> sorts, bool random)
{
if (sorts != null)
{
SortOrder[] sortOrders = sorts.Select(sort => new SortOrder(sort.ColumnName, sort.Direction == SortDirection.Ascending ? Order.ASC : Order.DESC)).ToArray();
queryOptions.AddOrder(sortOrders);
}
if (random)
{
// add the random sort order as the last sort; this is so that all the banners from same place don't
// group together. RandomRecordId is a random sorting of RecordId (ROWID on
// Banners table).
SortOrder soRandom = new SortOrder("RandomRecordId");
queryOptions.AddOrder(soRandom);
}
}
private QueryOptions PrepareQueryOptions(ref String query, ISearchOptions options, FilterSet cachedQueries)
{
QueryOptions queryOptions = new QueryOptions();
queryOptions.Rows = options.Rows;
queryOptions.Start = options.Start;
SetSorts(queryOptions, options.Sorts, options.RandomSort);
// get the facets, if they exist.
if (options.Facets != null && options.Facets.Fields.Count > 0)
{
SolrFacetFieldQuery[] facets = new SolrFacetFieldQuery[options.Facets.Fields.Count];
int i = 0;
foreach (String facet in options.Facets.Fields)
{
facets[i] = new SolrFacetFieldQuery(facet);
i++;
}
queryOptions.AddFacets(facets);
queryOptions.Facet.MinCount = options.Facets.MinCount;
queryOptions.Facet.Sort = true;
queryOptions.Facet.Limit = options.Facets.Limit;
}
if (options.MoreLikeThis != null && options.MoreLikeThis.Fields.Count > 0)
{
MoreLikeThisParameters moreLikeThisParms = new MoreLikeThisParameters(options.MoreLikeThis.Fields);
moreLikeThisParms.Count = options.MoreLikeThis.ChildCount;
moreLikeThisParms.MinDocFreq = options.MoreLikeThis.MinDocFreq;
moreLikeThisParms.MinTermFreq = options.MoreLikeThis.MinTermFreq;
moreLikeThisParms.Boost = options.MoreLikeThis.Boost;
queryOptions.MoreLikeThis = moreLikeThisParms;
}
AddCachedQueries(queryOptions, cachedQueries);
if (String.IsNullOrEmpty(query))
{
// if the query string is empty, then we need to force it to the standard handler.
if (options.ExtraParams == null)
options.ExtraParams = new Dictionary<string, string> { { "qt", "standard" } };
else
options.ExtraParams["qt"] = "standard";
// use standard handler syntax for all documents returned.
query = "*:*";
}
if (options.ExtraParams != null)
queryOptions.ExtraParams = options.ExtraParams;
return queryOptions;
}
private void AddCachedQueries(QueryOptions queryOptions, FilterSet cachedQueries)
{
if (cachedQueries != null)
{
ISearchFilterFormatter formatter = GetFilterFormatter();
foreach (IFilterRule rule in cachedQueries.Rules)
{
String queryPlusTag = String.Format("{{!tag={0}}}{1}", ((FilterInfo)rule).ColumnName, formatter.BuildQuery(rule));
queryOptions.FilterQueries.Add(new SolrQuery(queryPlusTag));
}
}
}
#endregion
}
public class EmergeTkParser<T> : ISolrQueryResultParser<T> where T : AbstractRecord, new()
{
private static readonly EmergeTkLog log = EmergeTkLogManager.GetLogger(typeof(EmergeTkParser<T>));
private ISearchOptions options = null;
public EmergeTkParser()
{
}
public EmergeTkParser(ISearchOptions options)
{
this.options = options;
}
public ISolrQueryResults<T> Parse(string r)
{
// done with HTTP call, stop the SOLR watch.
SolrSearchProvider.SolrWatch.Stop();
SolrSearchProvider.ParseWatch.Start();
StopWatch watch = new StopWatch("EmergeTkParser<T>.Parse");
watch.Start();
Type type = typeof(T);
SolrQueryResults<T> results = new SolrQueryResults<T>();
var xml = new XmlDocument();
xml.LoadXml(r);
watch.Lap("SOLR results parsed");
results.NumFound = int.Parse(xml.SelectSingleNode("/response/result/@numFound").Value);
XmlNodeList docs = xml.SelectNodes("/response/result/doc");
Type hitType = null;
List<int> ids = new List<int>();
foreach(XmlNode docNode in docs )
{
XmlNode idNode = docNode.SelectSingleNode("int[@name='RecordId']");
XmlNode typeNode = docNode.SelectSingleNode("str[@name='RecordType']");
if( null == idNode || null == typeNode )
{
log.Warn("could not load result", docNode.OuterXml);
}
hitType = TypeLoader.GetType(typeNode.InnerText);
int id = int.Parse( idNode.InnerText );
//log.DebugFormat("looking for hit type: {0} id {1}", typeNode.InnerText, id );
if( hitType == null || ! type.IsAssignableFrom(hitType) )
{
log.Warn("could not load result", id, typeNode.InnerText);
continue;
}
ids.Add(id);
}
SolrSearchProvider.ParseWatch.Stop();
IRecordList<T> records = DataProvider.DefaultProvider.Load<T>(ids);
SolrSearchProvider.ParseWatch.Start();
foreach( T t in records )
results.Add(t);
watch.Lap("completed building primary SOLR results, including AbstractRecord.Load calls");
if (hitType != null)
{
if (options != null)
{
if (options.Facets != null)
{
FacetAndMoreLikeThisLoader.LoadFacets<T>(results, xml);
watch.Lap("Completed loading facets");
}
if (options.MoreLikeThis != null)
{
results.SimilarResults = FacetAndMoreLikeThisLoader.GenerateMoreLikeThis<T>
(xml,
(t, i) => {
SolrSearchProvider.ParseWatch.Stop();
T record = (T)AbstractRecord.Load(t, i);
SolrSearchProvider.ParseWatch.Start();
return record;
});
watch.Lap("Completed loading MoreLikeThis results");
}
}
}
watch.Stop();
SolrSearchProvider.ParseWatch.Stop();
return results;
}
}
public class EmergeTkFastParser : ISolrQueryResultParser<RecordKey>
{
private static readonly EmergeTkLog log = EmergeTkLogManager.GetLogger(typeof(EmergeTkFastParser));
private ISearchOptions options = null;
public EmergeTkFastParser()
{
}
public EmergeTkFastParser(ISearchOptions options)
{
this.options = options;
}
public ISolrQueryResults<RecordKey> Parse(string r)
{
// HTTP request completed; stop the SOLR watch.
SolrSearchProvider.SolrWatch.Stop();
StopWatch watch = new StopWatch("EmergeTkFastParser.Parse");
SolrSearchProvider.ParseWatch.Start();
watch.Start();
SolrQueryResults<RecordKey> results = new SolrQueryResults<RecordKey>();
var xml = new XmlDocument();
xml.LoadXml(r);
watch.Lap("Done loading SOLR XML results");
results.NumFound = int.Parse(xml.SelectSingleNode("/response/result/@numFound").Value);
XmlNodeList docs = xml.SelectNodes("/response/result/doc");
foreach(XmlNode docNode in docs )
{
XmlNode idNode = docNode.SelectSingleNode("int[@name='RecordId']");
XmlNode typeNode = docNode.SelectSingleNode("str[@name='RecordType']");
if( null == idNode || null == typeNode )
{
log.Warn("could not load result", docNode.OuterXml);
continue;
}
int id = int.Parse( idNode.InnerText );
RecordKey rk = new RecordKey();
rk.Id = id;
rk.Type = typeNode.InnerText;
results.Add( rk );
}
watch.Lap("Completed parsing out primary SOLR results");
if (options != null)
{
if (options.Facets != null)
{
FacetAndMoreLikeThisLoader.LoadFacets<RecordKey>(results, xml);
watch.Lap("Completed parsing out SOLR facets info");
}
if (options.MoreLikeThis != null)
{
results.SimilarResults = FacetAndMoreLikeThisLoader.GenerateMoreLikeThis<RecordKey>
(xml,
(t, i) => new RecordKey(t.FullName, i));
watch.Lap("Completed parsing out MoreLikeThis information");
}
}
watch.Stop();
SolrSearchProvider.ParseWatch.Stop();
return results;
}
}
public class FacetAndMoreLikeThisLoader
{
private static readonly EmergeTkLog log = EmergeTkLogManager.GetLogger(typeof(FacetAndMoreLikeThisLoader));
static private void AddFacetFieldItems(XmlDocument xml, String xPath, Dictionary<String, ICollection<KeyValuePair<String, int>>> facetFields)
{
XmlNodeList lsts = xml.SelectNodes(xPath);
foreach (XmlNode lst in lsts)
{
String facetName = lst.Attributes.GetNamedItem("name").Value;
Dictionary<String, int> facetField = new Dictionary<string, int>();
XmlNodeList values = lst.SelectNodes("int");
foreach (XmlNode facetItemXmlNode in values)
{
XmlNode nameItemAttr = facetItemXmlNode.Attributes.GetNamedItem("name");
String itemName = (nameItemAttr == null) ? "Missing" : nameItemAttr.Value;
facetField.Add(itemName, Convert.ToInt32(facetItemXmlNode.InnerText));
}
facetFields.Add(facetName, facetField);
}
}
static public void LoadFacets<T>(SolrQueryResults<T> results, XmlDocument xml)
{
Dictionary<String, ICollection<KeyValuePair<String, int>>> facetFields = new Dictionary<string, ICollection<KeyValuePair<string, int>>>(StringComparer.CurrentCultureIgnoreCase);
// get the facet fields
AddFacetFieldItems(xml, "/response/lst[@name=\"facet_counts\"]/lst[@name=\"facet_fields\"]/lst", facetFields);
// now get the facet dates
AddFacetFieldItems(xml, "/response/lst[@name=\"facet_counts\"]/lst[@name=\"facet_dates\"]/lst", facetFields);
results.FacetFields = facetFields;
// get the facet queries
XmlNodeList intList = xml.SelectNodes("/response/lst[@name=\"facet_counts\"]/lst[@name=\"facet_queries\"]/int");
Dictionary<String, int> facetQueries = new Dictionary<string, int>(StringComparer.CurrentCultureIgnoreCase);
foreach (XmlNode intItem in intList)
{
XmlNode nameItem = intItem.Attributes.GetNamedItem("name");
String name = nameItem.Value;
if (!String.IsNullOrEmpty(name) && !String.IsNullOrEmpty(intItem.InnerText))
facetQueries.Add(name, Convert.ToInt32(intItem.InnerText));
}
if (facetQueries.Count > 0)
results.FacetQueries = facetQueries;
}
private static int GetRecordId(XmlNode result, out string type)
{
// the name looks like "Chaos.Model.Banner.1291"
String name = result.Attributes["name"].Value;
type = null;
// strip off Chaos.Model.Banner (or whatever) to get the recordId
// and turn it to an int.
int indexDot = name.LastIndexOf('.');
if (indexDot == -1 || name.Length < (indexDot + 2))
{
log.Error("Can't parse recordid from SOLR result name {0}", name);
return -1;
}
type = name.Substring(0, indexDot);
String recordIdStr = name.Substring(indexDot + 1);
int id;
if (!Int32.TryParse(recordIdStr, out id))
{
log.Error("Can't parse recordid for record name = {0}, ignoring", name);
return -1;
}
return id;
}
public delegate T LoadT<T>(Type type, int id);
public static IDictionary<String, IList<T>>
GenerateMoreLikeThis<T>(XmlDocument xml, LoadT<T> loader)
{
// get the MoreLikeThis results
// get the outer list of original results that are parents to
// the child SimilarResults nodes
XmlNodeList lsts = xml.SelectNodes("/response/lst[@name=\"moreLikeThis\"]/result");
// create a datastructure for the overall MoreLikeThis results
Dictionary<String, IList<T>> similarResults = new Dictionary<String, IList<T>>();
// for each parent result node
Type t = null;
foreach (XmlNode result in lsts)
{
String name = result.Attributes["name"].Value;
List<T> moreLikeThisKids = new List<T>();
XmlNodeList docs = result.SelectNodes("doc");
foreach (XmlNode doc in docs)
{
moreLikeThisKids.Add(loader(t, int.Parse(doc.SelectSingleNode("int[@name=\"RecordId\"]").InnerText)));
}
similarResults[name] = moreLikeThisKids;
}
return similarResults;
}
}
public class EmergeTkSolrSerializer<T> : ISolrDocumentSerializer<T> where T : AbstractRecord, new()
{
public XmlDocument Serialize(T doc, double? boost)
{
//REQUIRED FIELDS: RecordDefinition, RecordId, RecordType
var xml = new XmlDocument();
XmlNode docNode;
List<Field> fields = new List<Field>();
string typename = doc.GetType().FullName;
fields.Add( new Field( "RecordDefinition", typename + "." + doc.Id ) );
fields.Add( new Field( "RecordId", doc.Id ) );
fields.Add( new Field( "RecordType", typename ) );
IndexerFactory.Instance.IndexRecord(doc,fields);
DefaultFieldSerializer fieldSerializer = new DefaultFieldSerializer();
if( fields == null )
{
docNode = xml.CreateComment("ignore-node");
xml.AppendChild( docNode );
return xml;
}
docNode = xml.CreateElement("doc");
foreach (var kv in fields) {
var fieldNode = xml.CreateElement("field");
var nameAtt = xml.CreateAttribute("name");
nameAtt.InnerText = kv.Name;
fieldNode.Attributes.Append(nameAtt);
if( fieldSerializer != null && kv != null && kv.Value != null )
{
foreach( PropertyNode n in fieldSerializer.Serialize( kv.Value ) )
fieldNode.InnerText = n.FieldValue;
}
docNode.AppendChild(fieldNode);
}
xml.AppendChild(docNode);
//Console.WriteLine ( xml.OuterXml );
return xml;
}
}
public class SolrSearchOptions : ISearchOptions
{
SortInfo sort;
bool random = false;
public String Type { get; set; }
public int Start { get; set; }
public int Rows { get; set; }
public List<SortInfo> Sorts {get; set;}
public bool RandomSort
{
get
{
return random;
}
set
{
random = value;
}
}
public IFacets Facets { get; set; }
public IMoreLikeThis MoreLikeThis { get; set; }
public IDictionary<String, String> ExtraParams { get; set; }
public SolrSearchOptions()
{
Facets = null;
MoreLikeThis = null;
}
}
public class SolrFacets : IFacets
{
private List<String> fields;
public List<String> Fields
{
get
{
return fields;
}
set
{
fields = value;
}
}
public int Limit { get; set; }
public int MinCount { get; set; }
public SolrFacets()
{
fields = new List<String>();
}
}
public class SolrMoreLikeThis : IMoreLikeThis
{
private bool boost;
private List<String> fields;
public List<String> Fields
{
get
{
return fields;
}
set
{
fields = value;
}
}
public int ChildCount { get; set; }
public int MinDocFreq { get; set; }
public int MinTermFreq { get; set; }
public int Start { get; set; }
public int Rows { get; set; }
public bool Boost
{
get
{
return boost;
}
set
{
boost = value;
}
}
public SolrMoreLikeThis()
{
fields = new List<String>();
boost = true;
}
}
public class SolrSearchProviderQueryResults<T> : ISearchProviderQueryResults<T>
{
private Dictionary<String, ICollection<KeyValuePair<String, int>>> facets;
private IEnumerable<T> results;
private IDictionary<T, int> moreLikeThisOrder;
private int numFound = 0;
public IEnumerable<T> Results
{
get
{
return results;
}
internal set
{
results = value;
}
}
public IDictionary<String, ICollection<KeyValuePair<String, int>>> Facets
{
get
{
return facets;
}
internal set
{
facets = (Dictionary<String, ICollection<KeyValuePair<String, int>>>)value;
}
}
public IDictionary<string, int> FacetQueries { get; set; }
public int NumFound
{
get
{
return numFound;
}
internal set
{
numFound = value;
}
}
public IDictionary<T, int> MoreLikeThisOrder
{
internal set
{
moreLikeThisOrder = value;
}
get
{
return moreLikeThisOrder;
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using System.Runtime.Serialization;
using com.calitha.commons;
using com.calitha.goldparser;
using EpiInfo.Plugin;
namespace Epi.Core.EnterInterpreter
{
[Serializable()]
public class SymbolException : System.Exception
{
public SymbolException(string message) : base(message)
{
}
public SymbolException(string message,
Exception inner) : base(message, inner)
{
}
protected SymbolException(SerializationInfo info,
StreamingContext context) : base(info, context)
{
}
}
[Serializable()]
public class RuleException : System.Exception
{
public RuleException(string message) : base(message)
{
}
public RuleException(string message,
Exception inner) : base(message, inner)
{
}
protected RuleException(SerializationInfo info,
StreamingContext context) : base(info, context)
{
}
}
public class EpiInterpreterParser : IEnterInterpreter
{
private const string name = "EpiEnterInterpreter";
private bool IsExecuteMode = false;
private IEnterInterpreterHost host = null;
private LALRParser parser;
private IEnterInterpreterHost EnterCheckCodeInterface = null;
private Rule_Context mContext;
public EnterRule ProgramStart = null;
private string commandText = String.Empty;
private Stack<Token> tokenStack = new Stack<Token>();
public ICommandContext Context
{
get { return this.mContext; }
set { this.mContext = (Rule_Context)value; }
}
public string Name
{
get { return this.Name; }
}
public IEnterInterpreterHost Host
{
get { return this.host; }
set { this.host = value; }
}
//public event CommunicateUIEventHandler CommunicateUI;
const string RESOURCES_LANGUAGE_RULES = "Epi.Core.EnterInterpreter.grammar.EpiInfoGrammar.cgt";
//const string RESOURCES_LANGUAGE_RULES_ENTER = "Epi.Core.EnterInterpreter.grammar.EpiInfo.Enter.Grammar.cgt";
const string RESOURCES_LANGUAGE_RULES_ENTER = "Epi.Web.CheckCodeEngine.grammar.EpiInfo.Enter.Grammar.cgt";
/// <summary>
/// Returns Epi Info compiled grammar table as stream
/// </summary>
/// <returns></returns>
public static Stream GetCompiledGrammarTable()
{
Stream resourceStream = Assembly.GetExecutingAssembly().GetManifestResourceStream(RESOURCES_LANGUAGE_RULES);
return resourceStream;
}
/// <summary>
/// Returns Epi Info compiled grammar table as stream
/// </summary>
/// <returns></returns>
public static Stream GetEnterCompiledGrammarTable()
{
Stream resourceStream = Assembly.GetExecutingAssembly().GetManifestResourceStream(RESOURCES_LANGUAGE_RULES_ENTER);
return resourceStream;
}
/*
/// <summary>
/// onCommunicateUI()
/// </summary>
/// <remarks>
/// zack for communicate UI
/// </remarks>
/// <param name="msg"></param>
/// <param name="msgType"></param>
/// <returns></returns>
public bool onCommunicateUI(EpiMessages msg, MessageType msgType)
{
bool b;
b = CommunicateUI(msg, msgType);
return b;
}*/
public EpiInterpreterParser(string filename)
{
FileStream stream = new FileStream(filename,
FileMode.Open,
FileAccess.Read,
FileShare.Read);
Init(stream);
stream.Close();
}
public EpiInterpreterParser(string filename, IEnterInterpreterHost pEnterCheckCodeInterface)
{
this.EnterCheckCodeInterface = pEnterCheckCodeInterface;
FileStream stream = new FileStream(filename,
FileMode.Open,
FileAccess.Read,
FileShare.Read);
Init(stream);
stream.Close();
}
public EpiInterpreterParser(string baseName, string resourceName)
{
byte[] buffer = ResourceUtil.GetByteArrayResource(
System.Reflection.Assembly.GetExecutingAssembly(),
baseName,
resourceName);
MemoryStream stream = new MemoryStream(buffer);
Init(stream);
stream.Close();
}
public EpiInterpreterParser(Stream stream)
{
Init(stream);
}
private void Init(Stream stream, IScope pScope = null)
{
CGTReader reader = new CGTReader(stream);
parser = reader.CreateNewParser();
parser.StoreTokens = LALRParser.StoreTokensMode.NoUserObject;
parser.TrimReductions = false;
parser.OnReduce += new LALRParser.ReduceHandler(ReduceEvent);
parser.OnTokenRead += new LALRParser.TokenReadHandler(TokenReadEvent);
parser.OnAccept += new LALRParser.AcceptHandler(AcceptEvent);
parser.OnTokenError += new LALRParser.TokenErrorHandler(TokenErrorEvent);
parser.OnParseError += new LALRParser.ParseErrorHandler(ParseErrorEvent);
/*
Configuration config = null;
// check to see if config is already loaded
// if NOT then load default
try
{
config = Configuration.GetNewInstance();
if (config == null)
{
Configuration.Load(Configuration.DefaultConfigurationPath);
}
}
catch
{
// It may throw an error in the Configuration.GetNewInstanc()
// so try this from the default config path
Configuration.Load(Configuration.DefaultConfigurationPath);
}*/
if (pScope == null)
{
mContext = new Rule_Context();
}
else
{
mContext = new Rule_Context(pScope);
}
}
public EpiInterpreterParser(IEnterInterpreterHost pEnterCheckCodeInterface)
{
Stream stream = EpiInterpreterParser.GetEnterCompiledGrammarTable();
Init(stream);
pEnterCheckCodeInterface.Register(this);
this.EnterCheckCodeInterface = pEnterCheckCodeInterface;
}
public EpiInterpreterParser(IEnterInterpreterHost pEnterCheckCodeInterface, IScope pScope)
{
Stream stream = EpiInterpreterParser.GetEnterCompiledGrammarTable();
Init(stream, pScope);
pEnterCheckCodeInterface.Register(this);
this.EnterCheckCodeInterface = pEnterCheckCodeInterface;
//this.Context
}
public void Parse(string source)
{
try
{
this.mContext.AssignVariableCheck = new Dictionary<string, string>();
this.commandText = source;
this.IsExecuteMode = false;
parser.TrimReductions = true;
parser.Parse(source);
this.mContext.AssignVariableCheck = null;
}
catch (InvalidOperationException ex)
{
if (!ex.Message.ToUpper().Contains("STACK EMPTY"))
{
throw ex;
}
}
}
public void Execute(string source)
{
//if (this.host.IsExecutionEnabled)
{
try
{
this.mContext.AssignVariableCheck = new Dictionary<string, string>();
this.commandText = source;
this.IsExecuteMode = true;
parser.TrimReductions = true;
parser.Parse(source);
this.mContext.AssignVariableCheck = null;
}
catch (InvalidOperationException ex)
{
if (!ex.Message.ToUpper().Contains("STACK EMPTY"))
{
//if (this.host.IsSuppressErrorsEnabled)
{
//Logger.Log(string.Format("{0} - EnterInterpreter Parse Error. : source [{1}]\n message:\n{2}", DateTime.Now, ex.Source, ex.Message));
}/*
else
{
throw ex;
}*/
}
}
catch (Exception ex)
{
//if (this.host.IsSuppressErrorsEnabled)
{
//Logger.Log(string.Format("{0} - EnterInterpreter Execute : source [{1}]\n message:\n{2}", DateTime.Now, ex.Source, ex.Message));
}/*
else
{
throw ex;
}*/
}
}
}
private void TokenReadEvent(LALRParser parser, TokenReadEventArgs args)
{
try
{
args.Token.UserObject = CreateObject(args.Token);
}
catch (ApplicationException ex)
{
args.Continue = false;
tokenStack.Clear();
//Logger.Log(DateTime.Now + ": " + ex.Message);
throw ex;
}
}
private Object CreateObject(TerminalToken token)
{
return null;
}
private void ReduceEvent(LALRParser parser, ReduceEventArgs args)
{
try
{
args.Token.UserObject = CreateObject(args.Token);
}
catch (ApplicationException ex)
{
args.Continue = false;
//Logger.Log(DateTime.Now + ": " + ex.Message);
//todo: Report message to UI?
}
}
public static Object CreateObject(NonterminalToken token)
{
return null;
}
private void AcceptEvent(LALRParser parser, AcceptEventArgs args)
{
//System.Console.WriteLine("AcceptEvent ");
NonterminalToken T = (NonterminalToken)args.Token;
/*
try
{
Configuration.Load(Configuration.DefaultConfigurationPath);
this.Context.module = new MemoryRegion();
}
catch (System.Exception ex)
{
Configuration.CreateDefaultConfiguration();
Configuration.Load(Configuration.DefaultConfigurationPath);
this.Context.module = new MemoryRegion();
}*/
mContext.EnterCheckCodeInterface = this.EnterCheckCodeInterface;
mContext.ClearState();
EnterRule program = EnterRule.BuildStatments(mContext, T);
program.Execute();
mContext.CheckAssignedVariables();
/*
if (this.IsExecuteMode && this.host.IsExecutionEnabled)
{
program.Execute();
}
if (mContext.DefineVariablesCheckcode != null)
{
}*/
//this.ProgramStart
//this.ProgramStart.Execute();
}
private void TokenErrorEvent(LALRParser parser, TokenErrorEventArgs args)
{
//throw new com.calitha.goldparser.toTokenException(args);
}
private void ParseErrorEvent(LALRParser parser, ParseErrorEventArgs args)
{
///throw new ParseException(args);
}
}
}
| |
// 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.Buffers;
using System.Linq;
using System.Text;
using Xunit;
namespace System.Memory.Tests
{
public abstract class ReadOnlySequenceTestsChar
{
public class Array : ReadOnlySequenceTestsChar
{
public Array() : base(ReadOnlySequenceFactory<char>.ArrayFactory) { }
}
public class String : ReadOnlySequenceTestsChar
{
public String() : base(ReadOnlySequenceFactoryChar.StringFactory) { }
}
public class Memory : ReadOnlySequenceTestsChar
{
public Memory() : base(ReadOnlySequenceFactory<char>.MemoryFactory) { }
}
public class SingleSegment : ReadOnlySequenceTestsChar
{
public SingleSegment() : base(ReadOnlySequenceFactory<char>.SingleSegmentFactory) { }
}
public class SegmentPerChar : ReadOnlySequenceTestsChar
{
public SegmentPerChar() : base(ReadOnlySequenceFactory<char>.SegmentPerItemFactory) { }
}
public class SplitInThreeSegments : ReadOnlySequenceTestsChar
{
public SplitInThreeSegments() : base(ReadOnlySequenceFactory<char>.SplitInThree) { }
}
internal ReadOnlySequenceFactory<char> Factory { get; }
internal ReadOnlySequenceTestsChar(ReadOnlySequenceFactory<char> factory)
{
Factory = factory;
}
[Fact]
public void EmptyIsCorrect()
{
ReadOnlySequence<char> buffer = Factory.CreateOfSize(0);
Assert.Equal(0, buffer.Length);
Assert.True(buffer.IsEmpty);
}
[Theory]
[InlineData(1)]
[InlineData(8)]
public void LengthIsCorrect(int length)
{
ReadOnlySequence<char> buffer = Factory.CreateOfSize(length);
Assert.Equal(length, buffer.Length);
}
[Theory]
[InlineData(1)]
[InlineData(8)]
public void ToArrayIsCorrect(int length)
{
char[] data = Enumerable.Range(0, length).Select(i => (char)i).ToArray();
ReadOnlySequence<char> buffer = Factory.CreateWithContent(data);
Assert.Equal(length, buffer.Length);
Assert.Equal(data, buffer.ToArray());
}
[Fact]
public void ToStringIsCorrect()
{
char[] array = Enumerable.Range(0, 255).Select(i => (char)i).ToArray();
ReadOnlySequence<char> buffer = Factory.CreateWithContent(array);
Assert.Equal(array, buffer.ToString());
}
[Theory]
[MemberData(nameof(ValidSliceCases))]
public void Slice_Works(Func<ReadOnlySequence<char>, ReadOnlySequence<char>> func)
{
ReadOnlySequence<char> buffer = Factory.CreateWithContent(new char[] { (char)0, (char)1, (char)2, (char)3, (char)4, (char)5, (char)6, (char)7, (char)8, (char)9 });
ReadOnlySequence<char> slice = func(buffer);
Assert.Equal(new char[] { (char)5, (char)6, (char)7, (char)8, (char)9 }, slice.ToArray());
}
[Theory]
[MemberData(nameof(OutOfRangeSliceCases))]
public void ReadOnlyBufferDoesNotAllowSlicingOutOfRange(Action<ReadOnlySequence<char>> fail)
{
ReadOnlySequence<char> buffer = Factory.CreateOfSize(100);
Assert.Throws<ArgumentOutOfRangeException>(() => fail(buffer));
}
[Fact]
public void ReadOnlyBufferGetPosition_MovesPosition()
{
ReadOnlySequence<char> buffer = Factory.CreateOfSize(100);
SequencePosition position = buffer.GetPosition(65);
Assert.Equal(35, buffer.Slice(position).Length);
position = buffer.GetPosition(65, buffer.Start);
Assert.Equal(35, buffer.Slice(position).Length);
}
[Fact]
public void ReadOnlyBufferGetPosition_ChecksBounds()
{
ReadOnlySequence<char> buffer = Factory.CreateOfSize(100);
Assert.Throws<ArgumentOutOfRangeException>(() => buffer.GetPosition(101));
Assert.Throws<ArgumentOutOfRangeException>(() => buffer.GetPosition(101, buffer.Start));
}
[Fact]
public void ReadOnlyBufferGetPosition_DoesNotAlowNegative()
{
ReadOnlySequence<char> buffer = Factory.CreateOfSize(20);
Assert.Throws<ArgumentOutOfRangeException>(() => buffer.GetPosition(-1));
Assert.Throws<ArgumentOutOfRangeException>(() => buffer.GetPosition(-1, buffer.Start));
}
public void ReadOnlyBufferSlice_ChecksEnd()
{
ReadOnlySequence<char> buffer = Factory.CreateOfSize(100);
Assert.Throws<ArgumentOutOfRangeException>(() => buffer.Slice(70, buffer.Start));
}
[Fact]
public void SliceToTheEndWorks()
{
ReadOnlySequence<char> buffer = Factory.CreateOfSize(10);
Assert.True(buffer.Slice(buffer.End).IsEmpty);
}
[Theory]
[InlineData("a", 'a', 0)]
[InlineData("ab", 'a', 0)]
[InlineData("aab", 'a', 0)]
[InlineData("acab", 'a', 0)]
[InlineData("acab", 'c', 1)]
[InlineData("abcdefghijklmnopqrstuvwxyz", 'l', 11)]
[InlineData("abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz", 'l', 11)]
[InlineData("aaaaaaaaaaacmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz", 'm', 12)]
[InlineData("aaaaaaaaaaarmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz", 'r', 11)]
[InlineData("/localhost:5000/PATH/%2FPATH2/ HTTP/1.1", '%', 21)]
[InlineData("/localhost:5000/PATH/%2FPATH2/?key=value HTTP/1.1", '%', 21)]
[InlineData("/localhost:5000/PATH/PATH2/?key=value HTTP/1.1", '?', 27)]
[InlineData("/localhost:5000/PATH/PATH2/ HTTP/1.1", ' ', 27)]
public void PositionOf_ReturnsPosition(string raw, char searchFor, int expectIndex)
{
ReadOnlySequence<char> buffer = Factory.CreateWithContent(raw.ToCharArray());
SequencePosition? result = buffer.PositionOf((char)searchFor);
Assert.NotNull(result);
Assert.Equal(buffer.Slice(result.Value).ToArray(), raw.Substring(expectIndex));
}
[Fact]
public void PositionOf_ReturnsNullIfNotFound()
{
ReadOnlySequence<char> buffer = Factory.CreateWithContent(new char[] { (char)1, (char)2, (char)3 });
SequencePosition? result = buffer.PositionOf((char)4);
Assert.Null(result);
}
[Fact]
public void CopyTo_ThrowsWhenSourceLargerThenDestination()
{
ReadOnlySequence<char> buffer = Factory.CreateOfSize(10);
Assert.Throws<ArgumentOutOfRangeException>(() =>
{
Span<char> span = new char[5];
buffer.CopyTo(span);
});
}
public static TheoryData<Func<ReadOnlySequence<char>, ReadOnlySequence<char>>> ValidSliceCases => new TheoryData<Func<ReadOnlySequence<char>, ReadOnlySequence<char>>>
{
b => b.Slice(5),
b => b.Slice(0).Slice(5),
b => b.Slice(5, 5),
b => b.Slice(b.GetPosition(5), 5),
b => b.Slice(5, b.GetPosition(10)),
b => b.Slice(b.GetPosition(5), b.GetPosition(10)),
b => b.Slice(b.GetPosition(5, b.Start), 5),
b => b.Slice(5, b.GetPosition(10, b.Start)),
b => b.Slice(b.GetPosition(5, b.Start), b.GetPosition(10, b.Start)),
b => b.Slice((long)5),
b => b.Slice((long)5, 5),
b => b.Slice(b.GetPosition(5), (long)5),
b => b.Slice((long)5, b.GetPosition(10)),
b => b.Slice(b.GetPosition(5, b.Start), (long)5),
b => b.Slice((long)5, b.GetPosition(10, b.Start)),
};
public static TheoryData<Action<ReadOnlySequence<char>>> OutOfRangeSliceCases => new TheoryData<Action<ReadOnlySequence<char>>>
{
// negative start
b => b.Slice(-1), // no length
b => b.Slice(-1, -1), // negative length
b => b.Slice(-1, 0), // zero length
b => b.Slice(-1, 1), // positive length
b => b.Slice(-1, 101), // after end length
b => b.Slice(-1, b.Start), // to start
b => b.Slice(-1, b.End), // to end
// zero start
b => b.Slice(0, -1), // negative length
b => b.Slice(0, 101), // after end length
// end start
b => b.Slice(100, -1), // negative length
b => b.Slice(100, 1), // after end length
b => b.Slice(100, b.Start), // to start
// After end start
b => b.Slice(101), // no length
b => b.Slice(101, -1), // negative length
b => b.Slice(101, 0), // zero length
b => b.Slice(101, 1), // after end length
b => b.Slice(101, b.Start), // to start
b => b.Slice(101, b.End), // to end
// At Start start
b => b.Slice(b.Start, -1), // negative length
b => b.Slice(b.Start, 101), // after end length
// At End start
b => b.Slice(b.End, -1), // negative length
b => b.Slice(b.End, 1), // after end length
b => b.Slice(b.End, b.Start), // to start
// Slice at begin
b => b.Slice(0, 70).Slice(0, b.End), // to after end
b => b.Slice(0, 70).Slice(b.Start, b.End), // to after end
// from after end
b => b.Slice(0, 70).Slice(b.End),
b => b.Slice(0, 70).Slice(b.End, -1), // negative length
b => b.Slice(0, 70).Slice(b.End, 0), // zero length
b => b.Slice(0, 70).Slice(b.End, 1), // after end length
b => b.Slice(0, 70).Slice(b.End, b.Start), // to start
b => b.Slice(0, 70).Slice(b.End, b.End), // to after end
// Slice at begin
b => b.Slice(b.Start, 70).Slice(0, b.End), // to after end
b => b.Slice(b.Start, 70).Slice(b.Start, b.End), // to after end
// from after end
b => b.Slice(b.Start, 70).Slice(b.End),
b => b.Slice(b.Start, 70).Slice(b.End, -1), // negative length
b => b.Slice(b.Start, 70).Slice(b.End, 0), // zero length
b => b.Slice(b.Start, 70).Slice(b.End, 1), // after end length
b => b.Slice(b.Start, 70).Slice(b.End, b.Start), // to start
b => b.Slice(b.Start, 70).Slice(b.End, b.End), // to after end
// Slice at middle
b => b.Slice(30, 40).Slice(0, b.Start), // to before start
b => b.Slice(30, 40).Slice(0, b.End), // to after end
// from before start
b => b.Slice(30, 40).Slice(b.Start),
b => b.Slice(30, 40).Slice(b.Start, -1), // negative length
b => b.Slice(30, 40).Slice(b.Start, 0), // zero length
b => b.Slice(30, 40).Slice(b.Start, 1), // positive length
b => b.Slice(30, 40).Slice(b.Start, 41), // after end length
b => b.Slice(30, 40).Slice(b.Start, b.Start), // to before start
b => b.Slice(30, 40).Slice(b.Start, b.End), // to after end
// from after end
b => b.Slice(30, 40).Slice(b.End),
b => b.Slice(b.Start, 70).Slice(b.End, -1), // negative length
b => b.Slice(b.Start, 70).Slice(b.End, 0), // zero length
b => b.Slice(b.Start, 70).Slice(b.End, 1), // after end length
b => b.Slice(30, 40).Slice(b.End, b.Start), // to before start
b => b.Slice(30, 40).Slice(b.End, b.End), // to after end
// Slice at end
b => b.Slice(70, 30).Slice(0, b.Start), // to before start
// from before start
b => b.Slice(30, 40).Slice(b.Start),
b => b.Slice(30, 40).Slice(b.Start, -1), // negative length
b => b.Slice(30, 40).Slice(b.Start, 0), // zero length
b => b.Slice(30, 40).Slice(b.Start, 1), // positive length
b => b.Slice(30, 40).Slice(b.Start, 31), // after end length
b => b.Slice(30, 40).Slice(b.Start, b.Start), // to before start
b => b.Slice(30, 40).Slice(b.Start, b.End), // to end
// from end
b => b.Slice(70, 30).Slice(b.End, b.Start), // to before start
// Slice at end
b => b.Slice(70, 30).Slice(0, b.Start), // to before start
// from before start
b => b.Slice(30, 40).Slice(b.Start),
b => b.Slice(30, 40).Slice(b.Start, -1), // negative length
b => b.Slice(30, 40).Slice(b.Start, 0), // zero length
b => b.Slice(30, 40).Slice(b.Start, 1), // positive length
b => b.Slice(30, 40).Slice(b.Start, 31), // after end length
b => b.Slice(30, 40).Slice(b.Start, b.Start), // to before start
b => b.Slice(30, 40).Slice(b.Start, b.End), // to end
// from end
b => b.Slice(70, 30).Slice(b.End, b.Start), // to before start
};
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using System;
using System.Collections.Generic;
using System.Security.Cryptography;
using System.IO;
using System.Reflection;
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
namespace Azure.Core.TestFramework
{
/// <summary>
/// Represents the ambient environment in which the test suite is
/// being run.
/// </summary>
public abstract class TestEnvironment
{
private static readonly string RepositoryRoot;
private readonly string _prefix;
private TokenCredential _credential;
private TestRecording _recording;
private readonly Dictionary<string, string> _environmentFile = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
protected TestEnvironment(string serviceName)
{
_prefix = serviceName.ToUpperInvariant() + "_";
if (RepositoryRoot == null)
{
throw new InvalidOperationException("Unexpected error, repository root not found");
}
var testEnvironmentFile = Path.Combine(RepositoryRoot, "sdk", serviceName, "test-resources.json.env");
if (File.Exists(testEnvironmentFile))
{
var json = JsonDocument.Parse(
ProtectedData.Unprotect(File.ReadAllBytes(testEnvironmentFile), null, DataProtectionScope.CurrentUser)
);
foreach (var property in json.RootElement.EnumerateObject())
{
_environmentFile[property.Name] = property.Value.GetString();
}
}
}
static TestEnvironment()
{
// Traverse parent directories until we find an "artifacts" directory
// parent of that would become a repo root for test environment resolution purposes
var directoryInfo = new DirectoryInfo(Assembly.GetExecutingAssembly().Location);
while (directoryInfo.Name != "artifacts")
{
if (directoryInfo.Parent == null)
{
return;
}
directoryInfo = directoryInfo.Parent;
}
RepositoryRoot = directoryInfo?.Parent?.FullName;
}
internal RecordedTestMode? Mode { get; set; }
/// <summary>
/// The name of the Azure subscription containing the resource group to be used for Live tests. Recorded.
/// </summary>
public string SubscriptionId => GetRecordedVariable("SUBSCRIPTION_ID");
/// <summary>
/// The name of the Azure resource group to be used for Live tests. Recorded.
/// </summary>
public string ResourceGroup => GetRecordedVariable("RESOURCE_GROUP");
/// <summary>
/// The location of the Azure resource group to be used for Live tests (e.g. westus2). Recorded.
/// </summary>
public string Location => GetRecordedVariable("LOCATION");
/// <summary>
/// The environment of the Azure resource group to be used for Live tests (e.g. AzureCloud). Recorded.
/// </summary>
public string AzureEnvironment => GetRecordedVariable("ENVIRONMENT");
/// <summary>
/// The name of the Azure Active Directory tenant that holds the service principal to use during Live tests. Recorded.
/// </summary>
public string TenantId => GetRecordedVariable("TENANT_ID");
/// <summary>
/// The client id of the Azure Active Directory service principal to use during Live tests. Recorded.
/// </summary>
public string ClientId => GetRecordedVariable("CLIENT_ID");
/// <summary>
/// The client secret of the Azure Active Directory service principal to use during Live tests. Not recorded.
/// </summary>
public string ClientSecret => GetVariable("CLIENT_SECRET");
public TokenCredential Credential
{
get
{
if (_credential != null)
{
return _credential;
}
if (Mode == RecordedTestMode.Playback)
{
_credential = new TestCredential();
}
else
{
// Don't take a hard dependency on Azure.Identity
var type = Type.GetType("Azure.Identity.ClientSecretCredential, Azure.Identity");
if (type == null)
{
throw new InvalidOperationException("Azure.Identity must be referenced to use Credential in Live environment.");
}
_credential = (TokenCredential) Activator.CreateInstance(
type,
GetVariable("TENANT_ID"),
GetVariable("CLIENT_ID"),
GetVariable("CLIENT_SECRET")
);
}
return _credential;
}
}
/// <summary>
/// Returns and records an environment variable value when running live or recorded value during playback.
/// </summary>
protected string GetRecordedOptionalVariable(string name)
{
if (Mode == RecordedTestMode.Playback)
{
return GetRecordedValue(name);
}
string value = GetOptionalVariable(name);
SetRecordedValue(name, value);
return value;
}
/// <summary>
/// Returns and records an environment variable value when running live or recorded value during playback.
/// Throws when variable is not found.
/// </summary>
protected string GetRecordedVariable(string name)
{
var value = GetRecordedOptionalVariable(name);
EnsureValue(name, value);
return value;
}
/// <summary>
/// Returns an environment variable value.
/// Throws when variable is not found.
/// </summary>
protected string GetOptionalVariable(string name)
{
var prefixedName = _prefix + name;
// Environment variables override the environment file
var value = Environment.GetEnvironmentVariable(prefixedName) ??
Environment.GetEnvironmentVariable(name);
if (value == null)
{
_environmentFile.TryGetValue(prefixedName, out value);
}
if (value == null)
{
_environmentFile.TryGetValue(name, out value);
}
return value;
}
/// <summary>
/// Returns an environment variable value.
/// Throws when variable is not found.
/// </summary>
protected string GetVariable(string name)
{
var value = GetOptionalVariable(name);
EnsureValue(name, value);
return value;
}
private void EnsureValue(string name, string value)
{
if (value == null)
{
var prefixedName = _prefix + name;
throw new InvalidOperationException(
$"Unable to find environment variable {prefixedName} or {name} required by test." + Environment.NewLine +
"Make sure the test environment was initialized using eng/common/TestResources/New-TestResources.ps1 script.");
}
}
public void SetRecording(TestRecording recording)
{
_credential = null;
_recording = recording;
}
private string GetRecordedValue(string name)
{
if (_recording == null)
{
throw new InvalidOperationException("Recorded value should not be retrieved outside the test method invocation");
}
return _recording.GetVariable(name, null);
}
private void SetRecordedValue(string name, string value)
{
if (!Mode.HasValue)
{
return;
}
if (_recording == null)
{
throw new InvalidOperationException("Recorded value should not be set outside the test method invocation");
}
_recording?.SetVariable(name, value);
}
private class TestCredential : TokenCredential
{
public override ValueTask<AccessToken> GetTokenAsync(TokenRequestContext requestContext, CancellationToken cancellationToken)
{
return new ValueTask<AccessToken>(GetToken(requestContext, cancellationToken));
}
public override AccessToken GetToken(TokenRequestContext requestContext, CancellationToken cancellationToken)
{
return new AccessToken("TEST TOKEN " + string.Join(" ", requestContext.Scopes), DateTimeOffset.MaxValue);
}
}
}
}
| |
namespace NVerify
{
using System;
using System.IO;
using NUnit.Framework;
using NVerify.Core;
public static class MethodExtensions
{
/// <summary>
/// Tests tha a Func<typeparamref name="T"></typeparamref> throws an exception.
/// </summary>
/// <typeparam name="T">Return type</typeparam>
/// <param name="function">The function.</param>
/// <param name="message">The message.</param>
public static IVerifiable<Func<T>> ThrowsException<T>(
this IAssertion<Func<T>> function,
string message = "")
{
return new Verifiable<Func<T>>(function, target =>
Assert.IsNotNull(target.GetThrownException(),
string.Format("The function should've not thrown an exception, but it did.\n{0}",
message)));
}
/// <summary>
/// Tests that an Action should throw an exception
/// </summary>
/// <param name="action">The action.</param>
/// <param name="message">The message.</param>
public static IVerifiable<Action> ThrowsException(
this IAssertion<Action> action,
string message = "")
{
return new Verifiable<Action>(action, target =>
{
Assert.IsNotNull(target.GetThrownException(), message);
});
}
/// <summary>
/// Tests tha a Func<typeparamref name="T"/> does not throw an exception.
/// </summary>
/// <typeparam name="T">Return type</typeparam>
/// <param name="function">The function.</param>
/// <param name="message">The message.</param>
public static IVerifiable<Func<T>> DoesNotThrowException<T>(
this IAssertion<Func<T>> function,
string message = "")
{
return new Verifiable<Func<T>>(function, target =>
Assert.IsNull(
target.GetThrownException(),
string.Format(
"The function should've not thrown an exception, but it did.\n{0}",
message)));
}
/// <summary>
/// Tests that an Action should not throw an exception
/// </summary>
/// <param name="action">The action.</param>
/// <param name="message">The message.</param>
public static IVerifiable<Action> DoesNotThrowException(
this IAssertion<Action> action,
string message = "")
{
return new Verifiable<Action>(action, target =>
{
Assert.IsNull(target.GetThrownException(), message);
});
}
/// <summary>
/// Verifies that a methods writes exactly some output to console.
/// </summary>
/// <param name="assertion">The action assertion.</param>
/// <param name="expectedWritten">The expected written message to console.</param>
/// <param name="message">The message for the error.</param>
/// <returns>The verification continuation</returns>
public static IVerifiable<Action> WritesExactlyToConsole(
this IAssertion<Action> assertion,
string expectedWritten,
string message = "")
{
return new Verifiable<Action>(assertion, target =>
{
StringWriter consoleOut = new StringWriter();
Console.SetOut(consoleOut);
target();
string actualWritten = consoleOut.ToString();
Console.SetOut(Console.Out);
Assert.AreEqual(actualWritten,
expectedWritten,
message);
});
}
/// <summary>
/// Verifies that a methods does not write exactly some output to console.
/// </summary>
/// <param name="assertion">The action assertion.</param>
/// <param name="expectedWritten">The expected message not written to console.</param>
/// <param name="message">The message for the error.</param>
/// <returns>The verification continuation</returns>
public static IVerifiable<Action> DoesntWriteExactlyToConsole(
this IAssertion<Action> assertion,
string expectedWritten,
string message = "")
{
return new Verifiable<Action>(assertion, target =>
{
StringWriter consoleOut = new StringWriter();
Console.SetOut(consoleOut);
target();
string actualWritten = consoleOut.ToString();
Console.SetOut(Console.Out);
Assert.AreNotEqual(actualWritten,
expectedWritten,
message);
});
}
/// <summary>
/// Verifies that a methods writes exactly some output to console.
/// </summary>
/// <param name="assertion">The action assertion.</param>
/// <param name="expectedWritten">The expected written message to console.</param>
/// <param name="message">The message for the error.</param>
/// <returns>The verification continuation</returns>
public static IVerifiable<Action> WritesToConsole(
this IAssertion<Action> assertion,
string expectedWritten,
string message = "")
{
return new Verifiable<Action>(assertion, target =>
{
StringWriter consoleOut = new StringWriter();
Console.SetOut(consoleOut);
target();
string actualWritten = consoleOut.ToString();
Console.SetOut(Console.Out);
Assert.That(actualWritten,
Is.StringContaining(expectedWritten),
message);
});
}
/// <summary>
/// Verifies that a methods does not write some output to console.
/// </summary>
/// <param name="assertion">The action assertion.</param>
/// <param name="expectedWritten">The written message not expected.</param>
/// <param name="message">The message for the error.</param>
/// <returns>The verification continuation</returns>
public static IVerifiable<Action> DoesntWriteToConsole(
this IAssertion<Action> assertion,
string expectedWritten,
string message = "")
{
return new Verifiable<Action>(assertion, target =>
{
StringWriter consoleOut = new StringWriter();
Console.SetOut(consoleOut);
target();
string actualWritten = consoleOut.ToString();
Console.SetOut(Console.Out);
Assert.That(actualWritten,
Is.Not.StringContaining(expectedWritten),
message);
});
}
/// <summary>
/// Gets the exception thrown.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="function">The function.</param>
/// <returns></returns>
private static Exception GetThrownException<T>(this Func<T> function)
{
Exception x = null;
try
{
function();
}
catch (Exception ex)
{
x = ex;
}
return x;
}
/// <summary>
/// Gets the exception thrown.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="action">The action.</param>
/// <returns></returns>
private static Exception GetThrownException(this Action action)
{
Exception x = null;
try
{
action();
}
catch (Exception ex)
{
x = ex;
}
return x;
}
}
}
| |
#if UNITY_STANDALONE || UNITY_STANDALONE_WIN || UNITY_STANDALONE_OSX
#define COHERENT_UNITY_STANDALONE
#endif
#if UNITY_NACL || UNITY_WEBPLAYER
#define COHERENT_UNITY_UNSUPPORTED_PLATFORM
#endif
#if UNITY_EDITOR && (UNITY_IPHONE || UNITY_ANDROID)
#define COHERENT_SIMULATE_MOBILE_IN_EDITOR
#endif
using UnityEngine;
using System.Collections;
using Coherent.UI;
#if UNITY_EDITOR || COHERENT_UNITY_STANDALONE || COHERENT_UNITY_UNSUPPORTED_PLATFORM
namespace Coherent.UI
#elif UNITY_IPHONE || UNITY_ANDROID
namespace Coherent.UI.Mobile
#endif
{
public static class InputManager
{
const float UNITY_WHEEL_TICK_FACTOR = 1.0f / 3.0f;
static int[] s_KeyCodeMapping;
#region Keycode mapping initialization
static InputManager ()
{
//KeyCode[] enumValues = (KeyCode[])System.Enum.GetValues(typeof(KeyCode));
//int arraySize = (int)enumValues[enumValues.Length - 1];
//System.Diagnostics.Debug.Assert(arraySize == (int)KeyCode.Joystick4Button19);
s_KeyCodeMapping = new int[(int)KeyCode.Joystick4Button19 + 1];
s_KeyCodeMapping [(int)KeyCode.None] = 0;
s_KeyCodeMapping [(int)KeyCode.Backspace] = 0x08;
s_KeyCodeMapping [(int)KeyCode.Tab] = 0x09;
s_KeyCodeMapping [(int)KeyCode.Clear] = 0x0C;
s_KeyCodeMapping [(int)KeyCode.Return] = 0x0D;
s_KeyCodeMapping [(int)KeyCode.Pause] = 0x13;
s_KeyCodeMapping [(int)KeyCode.Escape] = 0x1B;
s_KeyCodeMapping [(int)KeyCode.Space] = 0x20;
s_KeyCodeMapping [(int)KeyCode.Exclaim] = 0x31;
s_KeyCodeMapping [(int)KeyCode.DoubleQuote] = 0xDE;
s_KeyCodeMapping [(int)KeyCode.Hash] = 0x33;
s_KeyCodeMapping [(int)KeyCode.Dollar] = 0x34;
s_KeyCodeMapping [(int)KeyCode.Ampersand] = 0x37;
s_KeyCodeMapping [(int)KeyCode.Quote] = 0xDE;
s_KeyCodeMapping [(int)KeyCode.LeftParen] = 0x39;
s_KeyCodeMapping [(int)KeyCode.RightParen] = 0x30;
s_KeyCodeMapping [(int)KeyCode.Asterisk] = 0x38;
s_KeyCodeMapping [(int)KeyCode.Plus] = 0xBB;
s_KeyCodeMapping [(int)KeyCode.Comma] = 0xBC;
s_KeyCodeMapping [(int)KeyCode.Minus] = 0xBD;
s_KeyCodeMapping [(int)KeyCode.Period] = 0xBE;
s_KeyCodeMapping [(int)KeyCode.Slash] = 0xBF;
s_KeyCodeMapping [(int)KeyCode.Alpha0] = 0x30;
s_KeyCodeMapping [(int)KeyCode.Alpha1] = 0x31;
s_KeyCodeMapping [(int)KeyCode.Alpha2] = 0x32;
s_KeyCodeMapping [(int)KeyCode.Alpha3] = 0x33;
s_KeyCodeMapping [(int)KeyCode.Alpha4] = 0x34;
s_KeyCodeMapping [(int)KeyCode.Alpha5] = 0x35;
s_KeyCodeMapping [(int)KeyCode.Alpha6] = 0x36;
s_KeyCodeMapping [(int)KeyCode.Alpha7] = 0x37;
s_KeyCodeMapping [(int)KeyCode.Alpha8] = 0x38;
s_KeyCodeMapping [(int)KeyCode.Alpha9] = 0x39;
s_KeyCodeMapping [(int)KeyCode.Colon] = 0xBA;
s_KeyCodeMapping [(int)KeyCode.Semicolon] = 0xBA;
s_KeyCodeMapping [(int)KeyCode.Less] = 0xBC;
s_KeyCodeMapping [(int)KeyCode.Equals] = 0xBB;
s_KeyCodeMapping [(int)KeyCode.Greater] = 0xBE;
s_KeyCodeMapping [(int)KeyCode.Question] = 0xBF;
s_KeyCodeMapping [(int)KeyCode.At] = 0x32;
s_KeyCodeMapping [(int)KeyCode.LeftBracket] = 0xDB;
s_KeyCodeMapping [(int)KeyCode.Backslash] = 0xDC;
s_KeyCodeMapping [(int)KeyCode.RightBracket] = 0xDD;
s_KeyCodeMapping [(int)KeyCode.Caret] = 0x36;
s_KeyCodeMapping [(int)KeyCode.Underscore] = 0xBD;
s_KeyCodeMapping [(int)KeyCode.BackQuote] = 0xC0;
s_KeyCodeMapping [(int)KeyCode.A] = 65;
s_KeyCodeMapping [(int)KeyCode.B] = 66;
s_KeyCodeMapping [(int)KeyCode.C] = 67;
s_KeyCodeMapping [(int)KeyCode.D] = 68;
s_KeyCodeMapping [(int)KeyCode.E] = 69;
s_KeyCodeMapping [(int)KeyCode.F] = 70;
s_KeyCodeMapping [(int)KeyCode.G] = 71;
s_KeyCodeMapping [(int)KeyCode.H] = 72;
s_KeyCodeMapping [(int)KeyCode.I] = 73;
s_KeyCodeMapping [(int)KeyCode.J] = 74;
s_KeyCodeMapping [(int)KeyCode.K] = 75;
s_KeyCodeMapping [(int)KeyCode.L] = 76;
s_KeyCodeMapping [(int)KeyCode.M] = 77;
s_KeyCodeMapping [(int)KeyCode.N] = 78;
s_KeyCodeMapping [(int)KeyCode.O] = 79;
s_KeyCodeMapping [(int)KeyCode.P] = 80;
s_KeyCodeMapping [(int)KeyCode.Q] = 81;
s_KeyCodeMapping [(int)KeyCode.R] = 82;
s_KeyCodeMapping [(int)KeyCode.S] = 83;
s_KeyCodeMapping [(int)KeyCode.T] = 84;
s_KeyCodeMapping [(int)KeyCode.U] = 85;
s_KeyCodeMapping [(int)KeyCode.V] = 86;
s_KeyCodeMapping [(int)KeyCode.W] = 87;
s_KeyCodeMapping [(int)KeyCode.X] = 88;
s_KeyCodeMapping [(int)KeyCode.Y] = 89;
s_KeyCodeMapping [(int)KeyCode.Z] = 90;
s_KeyCodeMapping [(int)KeyCode.Delete] = 0x2E;
s_KeyCodeMapping [(int)KeyCode.Keypad0] = 0x60;
s_KeyCodeMapping [(int)KeyCode.Keypad1] = 0x61;
s_KeyCodeMapping [(int)KeyCode.Keypad2] = 0x62;
s_KeyCodeMapping [(int)KeyCode.Keypad3] = 0x63;
s_KeyCodeMapping [(int)KeyCode.Keypad4] = 0x64;
s_KeyCodeMapping [(int)KeyCode.Keypad5] = 0x65;
s_KeyCodeMapping [(int)KeyCode.Keypad6] = 0x66;
s_KeyCodeMapping [(int)KeyCode.Keypad7] = 0x67;
s_KeyCodeMapping [(int)KeyCode.Keypad8] = 0x68;
s_KeyCodeMapping [(int)KeyCode.Keypad9] = 0x69;
s_KeyCodeMapping [(int)KeyCode.KeypadPeriod] = 0x6E;
s_KeyCodeMapping [(int)KeyCode.KeypadDivide] = 0x6F;
s_KeyCodeMapping [(int)KeyCode.KeypadMultiply] = 0x6A;
s_KeyCodeMapping [(int)KeyCode.KeypadMinus] = 0x6D;
s_KeyCodeMapping [(int)KeyCode.KeypadPlus] = 0x6B;
s_KeyCodeMapping [(int)KeyCode.KeypadEnter] = 0x0D;
s_KeyCodeMapping [(int)KeyCode.KeypadEquals] = 0;
s_KeyCodeMapping [(int)KeyCode.UpArrow] = 0x26;
s_KeyCodeMapping [(int)KeyCode.DownArrow] = 0x28;
s_KeyCodeMapping [(int)KeyCode.RightArrow] = 0x27;
s_KeyCodeMapping [(int)KeyCode.LeftArrow] = 0x25;
s_KeyCodeMapping [(int)KeyCode.Insert] = 0x2D;
s_KeyCodeMapping [(int)KeyCode.Home] = 0x24;
s_KeyCodeMapping [(int)KeyCode.End] = 0x23;
s_KeyCodeMapping [(int)KeyCode.PageUp] = 0x21;
s_KeyCodeMapping [(int)KeyCode.PageDown] = 0x22;
s_KeyCodeMapping [(int)KeyCode.F1] = 0x70;
s_KeyCodeMapping [(int)KeyCode.F2] = 0x71;
s_KeyCodeMapping [(int)KeyCode.F3] = 0x72;
s_KeyCodeMapping [(int)KeyCode.F4] = 0x73;
s_KeyCodeMapping [(int)KeyCode.F5] = 0x74;
s_KeyCodeMapping [(int)KeyCode.F6] = 0x75;
s_KeyCodeMapping [(int)KeyCode.F7] = 0x76;
s_KeyCodeMapping [(int)KeyCode.F8] = 0x77;
s_KeyCodeMapping [(int)KeyCode.F9] = 0x78;
s_KeyCodeMapping [(int)KeyCode.F10] = 0x79;
s_KeyCodeMapping [(int)KeyCode.F11] = 0x7A;
s_KeyCodeMapping [(int)KeyCode.F12] = 0x7B;
s_KeyCodeMapping [(int)KeyCode.F13] = 0x7C;
s_KeyCodeMapping [(int)KeyCode.F14] = 0x7D;
s_KeyCodeMapping [(int)KeyCode.F15] = 0x7E;
s_KeyCodeMapping [(int)KeyCode.Numlock] = 0x90;
s_KeyCodeMapping [(int)KeyCode.CapsLock] = 0x14;
s_KeyCodeMapping [(int)KeyCode.ScrollLock] = 0x91;
s_KeyCodeMapping [(int)KeyCode.RightShift] = 0x10;
s_KeyCodeMapping [(int)KeyCode.LeftShift] = 0x10;
s_KeyCodeMapping [(int)KeyCode.RightControl] = 0x11;
s_KeyCodeMapping [(int)KeyCode.LeftControl] = 0x11;
s_KeyCodeMapping [(int)KeyCode.RightAlt] = 0x12;
s_KeyCodeMapping [(int)KeyCode.LeftAlt] = 0x12;
s_KeyCodeMapping [(int)KeyCode.RightApple] = 0x5C;
s_KeyCodeMapping [(int)KeyCode.LeftApple] = 0x5B;
s_KeyCodeMapping [(int)KeyCode.LeftWindows] = 0x5C;
s_KeyCodeMapping [(int)KeyCode.RightWindows] = 0x5B;
s_KeyCodeMapping [(int)KeyCode.AltGr] = 0x12;
s_KeyCodeMapping [(int)KeyCode.Help] = 0x2F;
s_KeyCodeMapping [(int)KeyCode.Print] = 0x2A;
s_KeyCodeMapping [(int)KeyCode.SysReq] = 0x2C;
s_KeyCodeMapping [(int)KeyCode.Break] = 0x13;
s_KeyCodeMapping [(int)KeyCode.Menu] = 0; // Which key is this?
s_KeyCodeMapping [(int)KeyCode.Mouse0] = 0;
s_KeyCodeMapping [(int)KeyCode.Mouse1] = 0;
s_KeyCodeMapping [(int)KeyCode.Mouse2] = 0;
s_KeyCodeMapping [(int)KeyCode.Mouse3] = 0;
s_KeyCodeMapping [(int)KeyCode.Mouse4] = 0;
s_KeyCodeMapping [(int)KeyCode.Mouse5] = 0;
s_KeyCodeMapping [(int)KeyCode.Mouse6] = 0;
s_KeyCodeMapping [(int)KeyCode.JoystickButton0] = 0;
s_KeyCodeMapping [(int)KeyCode.JoystickButton1] = 0;
s_KeyCodeMapping [(int)KeyCode.JoystickButton2] = 0;
s_KeyCodeMapping [(int)KeyCode.JoystickButton3] = 0;
s_KeyCodeMapping [(int)KeyCode.JoystickButton4] = 0;
s_KeyCodeMapping [(int)KeyCode.JoystickButton5] = 0;
s_KeyCodeMapping [(int)KeyCode.JoystickButton6] = 0;
s_KeyCodeMapping [(int)KeyCode.JoystickButton7] = 0;
s_KeyCodeMapping [(int)KeyCode.JoystickButton8] = 0;
s_KeyCodeMapping [(int)KeyCode.JoystickButton9] = 0;
s_KeyCodeMapping [(int)KeyCode.JoystickButton10] = 0;
s_KeyCodeMapping [(int)KeyCode.JoystickButton11] = 0;
s_KeyCodeMapping [(int)KeyCode.JoystickButton12] = 0;
s_KeyCodeMapping [(int)KeyCode.JoystickButton13] = 0;
s_KeyCodeMapping [(int)KeyCode.JoystickButton14] = 0;
s_KeyCodeMapping [(int)KeyCode.JoystickButton15] = 0;
s_KeyCodeMapping [(int)KeyCode.JoystickButton16] = 0;
s_KeyCodeMapping [(int)KeyCode.JoystickButton17] = 0;
s_KeyCodeMapping [(int)KeyCode.JoystickButton18] = 0;
s_KeyCodeMapping [(int)KeyCode.JoystickButton19] = 0;
s_KeyCodeMapping [(int)KeyCode.Joystick1Button0] = 0;
s_KeyCodeMapping [(int)KeyCode.Joystick1Button1] = 0;
s_KeyCodeMapping [(int)KeyCode.Joystick1Button2] = 0;
s_KeyCodeMapping [(int)KeyCode.Joystick1Button3] = 0;
s_KeyCodeMapping [(int)KeyCode.Joystick1Button4] = 0;
s_KeyCodeMapping [(int)KeyCode.Joystick1Button5] = 0;
s_KeyCodeMapping [(int)KeyCode.Joystick1Button6] = 0;
s_KeyCodeMapping [(int)KeyCode.Joystick1Button7] = 0;
s_KeyCodeMapping [(int)KeyCode.Joystick1Button8] = 0;
s_KeyCodeMapping [(int)KeyCode.Joystick1Button9] = 0;
s_KeyCodeMapping [(int)KeyCode.Joystick1Button10] = 0;
s_KeyCodeMapping [(int)KeyCode.Joystick1Button11] = 0;
s_KeyCodeMapping [(int)KeyCode.Joystick1Button12] = 0;
s_KeyCodeMapping [(int)KeyCode.Joystick1Button13] = 0;
s_KeyCodeMapping [(int)KeyCode.Joystick1Button14] = 0;
s_KeyCodeMapping [(int)KeyCode.Joystick1Button15] = 0;
s_KeyCodeMapping [(int)KeyCode.Joystick1Button16] = 0;
s_KeyCodeMapping [(int)KeyCode.Joystick1Button17] = 0;
s_KeyCodeMapping [(int)KeyCode.Joystick1Button18] = 0;
s_KeyCodeMapping [(int)KeyCode.Joystick1Button19] = 0;
s_KeyCodeMapping [(int)KeyCode.Joystick2Button0] = 0;
s_KeyCodeMapping [(int)KeyCode.Joystick2Button1] = 0;
s_KeyCodeMapping [(int)KeyCode.Joystick2Button2] = 0;
s_KeyCodeMapping [(int)KeyCode.Joystick2Button3] = 0;
s_KeyCodeMapping [(int)KeyCode.Joystick2Button4] = 0;
s_KeyCodeMapping [(int)KeyCode.Joystick2Button5] = 0;
s_KeyCodeMapping [(int)KeyCode.Joystick2Button6] = 0;
s_KeyCodeMapping [(int)KeyCode.Joystick2Button7] = 0;
s_KeyCodeMapping [(int)KeyCode.Joystick2Button8] = 0;
s_KeyCodeMapping [(int)KeyCode.Joystick2Button9] = 0;
s_KeyCodeMapping [(int)KeyCode.Joystick2Button10] = 0;
s_KeyCodeMapping [(int)KeyCode.Joystick2Button11] = 0;
s_KeyCodeMapping [(int)KeyCode.Joystick2Button12] = 0;
s_KeyCodeMapping [(int)KeyCode.Joystick2Button13] = 0;
s_KeyCodeMapping [(int)KeyCode.Joystick2Button14] = 0;
s_KeyCodeMapping [(int)KeyCode.Joystick2Button15] = 0;
s_KeyCodeMapping [(int)KeyCode.Joystick2Button16] = 0;
s_KeyCodeMapping [(int)KeyCode.Joystick2Button17] = 0;
s_KeyCodeMapping [(int)KeyCode.Joystick2Button18] = 0;
s_KeyCodeMapping [(int)KeyCode.Joystick2Button19] = 0;
s_KeyCodeMapping [(int)KeyCode.Joystick3Button0] = 0;
s_KeyCodeMapping [(int)KeyCode.Joystick3Button1] = 0;
s_KeyCodeMapping [(int)KeyCode.Joystick3Button2] = 0;
s_KeyCodeMapping [(int)KeyCode.Joystick3Button3] = 0;
s_KeyCodeMapping [(int)KeyCode.Joystick3Button4] = 0;
s_KeyCodeMapping [(int)KeyCode.Joystick3Button5] = 0;
s_KeyCodeMapping [(int)KeyCode.Joystick3Button6] = 0;
s_KeyCodeMapping [(int)KeyCode.Joystick3Button7] = 0;
s_KeyCodeMapping [(int)KeyCode.Joystick3Button8] = 0;
s_KeyCodeMapping [(int)KeyCode.Joystick3Button9] = 0;
s_KeyCodeMapping [(int)KeyCode.Joystick3Button10] = 0;
s_KeyCodeMapping [(int)KeyCode.Joystick3Button11] = 0;
s_KeyCodeMapping [(int)KeyCode.Joystick3Button12] = 0;
s_KeyCodeMapping [(int)KeyCode.Joystick3Button13] = 0;
s_KeyCodeMapping [(int)KeyCode.Joystick3Button14] = 0;
s_KeyCodeMapping [(int)KeyCode.Joystick3Button15] = 0;
s_KeyCodeMapping [(int)KeyCode.Joystick3Button16] = 0;
s_KeyCodeMapping [(int)KeyCode.Joystick3Button17] = 0;
s_KeyCodeMapping [(int)KeyCode.Joystick3Button18] = 0;
s_KeyCodeMapping [(int)KeyCode.Joystick3Button19] = 0;
s_KeyCodeMapping [(int)KeyCode.Joystick4Button0] = 0;
s_KeyCodeMapping [(int)KeyCode.Joystick4Button1] = 0;
s_KeyCodeMapping [(int)KeyCode.Joystick4Button2] = 0;
s_KeyCodeMapping [(int)KeyCode.Joystick4Button3] = 0;
s_KeyCodeMapping [(int)KeyCode.Joystick4Button4] = 0;
s_KeyCodeMapping [(int)KeyCode.Joystick4Button5] = 0;
s_KeyCodeMapping [(int)KeyCode.Joystick4Button6] = 0;
s_KeyCodeMapping [(int)KeyCode.Joystick4Button7] = 0;
s_KeyCodeMapping [(int)KeyCode.Joystick4Button8] = 0;
s_KeyCodeMapping [(int)KeyCode.Joystick4Button9] = 0;
s_KeyCodeMapping [(int)KeyCode.Joystick4Button10] = 0;
s_KeyCodeMapping [(int)KeyCode.Joystick4Button11] = 0;
s_KeyCodeMapping [(int)KeyCode.Joystick4Button12] = 0;
s_KeyCodeMapping [(int)KeyCode.Joystick4Button13] = 0;
s_KeyCodeMapping [(int)KeyCode.Joystick4Button14] = 0;
s_KeyCodeMapping [(int)KeyCode.Joystick4Button15] = 0;
s_KeyCodeMapping [(int)KeyCode.Joystick4Button16] = 0;
s_KeyCodeMapping [(int)KeyCode.Joystick4Button17] = 0;
s_KeyCodeMapping [(int)KeyCode.Joystick4Button18] = 0;
s_KeyCodeMapping [(int)KeyCode.Joystick4Button19] = 0;
}
#endregion
private static EventModifiersState GetEventModifiersState (Event evt)
{
EventModifiersState state = new EventModifiersState ();
state.IsCtrlDown = evt.control;
state.IsAltDown = evt.alt && !Input.GetKey(KeyCode.AltGr);
state.IsShiftDown = evt.shift;
state.IsCapsOn = evt.capsLock;
state.IsNumLockOn = false; // Indeterminate
state.IsMetaDown = evt.command;
return state;
}
#region Touch handling
public struct CoherentTouch
{
public int fingerId;
public Vector2 position;
public Vector2 deltaPosition;
public float deltaTime;
public int tapCount;
public TouchPhase phase;
}
#if UNITY_ANDROID || COHERENT_SIMULATE_MOBILE_IN_EDITOR || COHERENT_SIMULATE_MOBILE_IN_PLAYER
private const int MAX_TOUCHES = 8;
private static CoherentTouch[] m_Touches = new CoherentTouch[MAX_TOUCHES];
private static CoherentTouch[] m_TouchesForNextFrame = new CoherentTouch[MAX_TOUCHES];
private static float[] m_LastChangedTime = new float[MAX_TOUCHES];
private static int m_TouchCount = 0;
private static int m_TouchCountForNextFrame = 0;
#endif
public static void ProcessTouchEvent(int id, int phase, int x, int y)
{
#if UNITY_ANDROID || COHERENT_SIMULATE_MOBILE_IN_EDITOR || COHERENT_SIMULATE_MOBILE_IN_PLAYER
// Check if we already have an event with that ID
int foundIndex = -1;
for (int i = 0; i < m_TouchCountForNextFrame; ++i)
{
if (m_TouchesForNextFrame[i].fingerId == id)
{
foundIndex = i;
break;
}
}
CoherentTouch newTouch = new CoherentTouch();
newTouch.fingerId = id;
newTouch.phase = (TouchPhase)phase;
newTouch.position = new Vector2(x, Screen.height - y);
newTouch.deltaTime = 0;
newTouch.deltaPosition = new Vector2(0, 0);
newTouch.tapCount = 1;
if (foundIndex >= 0)
{
// Update event
newTouch.deltaPosition = newTouch.position - m_TouchesForNextFrame[foundIndex].position;
m_TouchesForNextFrame[foundIndex] = newTouch;
m_LastChangedTime[foundIndex] = Time.time;
}
else
{
// Create new event if the touch has just begun; otherwise ignore the event
if (phase == (int)TouchPhase.Began)
{
if (m_TouchCountForNextFrame < MAX_TOUCHES)
{
m_TouchesForNextFrame[m_TouchCountForNextFrame] = newTouch;
m_LastChangedTime[m_TouchCountForNextFrame] = Time.time;
++m_TouchCountForNextFrame;
}
else
{
Debug.LogWarning("Cannot process touch event since current touch count exceeds maximum allowed (" + MAX_TOUCHES + ")!");
}
}
}
#endif
}
public static int TouchesCount
{
get
{
#if UNITY_ANDROID || COHERENT_SIMULATE_MOBILE_IN_EDITOR || COHERENT_SIMULATE_MOBILE_IN_PLAYER
return m_TouchCount;
#else
return Input.touchCount;
#endif
}
}
public static CoherentTouch GetTouch(int index)
{
#if UNITY_ANDROID || COHERENT_SIMULATE_MOBILE_IN_EDITOR || COHERENT_SIMULATE_MOBILE_IN_PLAYER
if (index >= 0 && index < m_TouchCount)
{
return m_Touches[index];
}
throw new System.IndexOutOfRangeException("Indexing CoherentTouch array with invalid value!");
#else
CoherentTouch coherentTouch = new CoherentTouch();
Touch unityTouch = Input.GetTouch(index);
coherentTouch.fingerId = unityTouch.fingerId;
coherentTouch.deltaPosition = unityTouch.deltaPosition;
coherentTouch.deltaTime = unityTouch.deltaTime;
coherentTouch.phase = unityTouch.phase;
coherentTouch.position = unityTouch.position;
coherentTouch.tapCount = unityTouch.tapCount;
return coherentTouch;
#endif
}
public static void PrepareForNextFrame()
{
#if UNITY_ANDROID || COHERENT_SIMULATE_MOBILE_IN_EDITOR || COHERENT_SIMULATE_MOBILE_IN_PLAYER
// Copy the 'next' touches in the 'current' array
for (int i = 0; i < m_TouchCountForNextFrame; ++i)
{
m_Touches[i] = m_TouchesForNextFrame[i];
}
m_TouchCount = m_TouchCountForNextFrame;
// - Cleanup Ended/Canceled touches from last frame;
// - Check if any of the touches' phase moved to Stationary
// - Update delta time
for (int i = 0; i < m_TouchCountForNextFrame; )
{
if (m_TouchesForNextFrame[i].phase == TouchPhase.Ended || m_TouchesForNextFrame[i].phase == TouchPhase.Canceled)
{
// Swap with last element
m_LastChangedTime[i] = m_LastChangedTime[m_TouchCountForNextFrame - 1];
m_TouchesForNextFrame[i] = m_TouchesForNextFrame[m_TouchCountForNextFrame - 1];
--m_TouchCountForNextFrame;
}
else
{
if (m_LastChangedTime[i] != Time.time)
{
m_TouchesForNextFrame[i].deltaTime = Time.time - m_LastChangedTime[i];
}
if (m_TouchesForNextFrame[i].phase == TouchPhase.Began ||
(m_TouchesForNextFrame[i].phase == TouchPhase.Moved && m_TouchesForNextFrame[i].deltaTime > 0))
{
m_TouchesForNextFrame[i].phase = TouchPhase.Stationary;
}
++i;
}
}
#endif
}
#endregion
public static void GenerateMouseMoveEvent (ref MouseEventData mouseMoveEvent)
{
mouseMoveEvent.Type = MouseEventData.EventType.MouseMove;
mouseMoveEvent.Button = MouseEventData.MouseButton.ButtonNone;
mouseMoveEvent.MouseModifiers.IsLeftButtonDown = Input.GetMouseButton (0);
mouseMoveEvent.MouseModifiers.IsMiddleButtonDown = Input.GetMouseButton (2);
mouseMoveEvent.MouseModifiers.IsRightButtonDown = Input.GetMouseButton (1);
mouseMoveEvent.Modifiers.IsCtrlDown = Input.GetKey (KeyCode.LeftControl) || Input.GetKey (KeyCode.RightControl);
mouseMoveEvent.Modifiers.IsAltDown = Input.GetKey (KeyCode.LeftAlt) || Input.GetKey (KeyCode.RightAlt);
mouseMoveEvent.Modifiers.IsShiftDown = Input.GetKey (KeyCode.LeftShift) || Input.GetKey (KeyCode.RightShift);
mouseMoveEvent.Modifiers.IsCapsOn = false; // Indeterminate
mouseMoveEvent.Modifiers.IsNumLockOn = false; // Indeterminate
if (mouseMoveEvent.MouseModifiers.IsLeftButtonDown) {
mouseMoveEvent.Button = MouseEventData.MouseButton.ButtonLeft;
} else if (mouseMoveEvent.MouseModifiers.IsMiddleButtonDown) {
mouseMoveEvent.Button = MouseEventData.MouseButton.ButtonMiddle;
} else if (mouseMoveEvent.MouseModifiers.IsRightButtonDown) {
mouseMoveEvent.Button = MouseEventData.MouseButton.ButtonRight;
}
mouseMoveEvent.X = (int)Input.mousePosition.x;
mouseMoveEvent.Y = (int)Input.mousePosition.y;
mouseMoveEvent.WheelX = 0;
mouseMoveEvent.WheelY = 0;
}
public static MouseEventData ProcessMouseEvent (Event evt)
{
MouseEventData eventData = new MouseEventData ();
EventMouseModifiersState mouseMods = new EventMouseModifiersState ();
mouseMods.IsLeftButtonDown = Input.GetMouseButton (0);
mouseMods.IsMiddleButtonDown = Input.GetMouseButton (2);
mouseMods.IsRightButtonDown = Input.GetMouseButton (1);
eventData.Modifiers = GetEventModifiersState (evt);
eventData.MouseModifiers = mouseMods;
if (evt.type == EventType.ScrollWheel) {
eventData.WheelX = evt.delta.x * UNITY_WHEEL_TICK_FACTOR;
eventData.WheelY = -evt.delta.y * UNITY_WHEEL_TICK_FACTOR;
}
eventData.X = (int)evt.mousePosition.x;
eventData.Y = (int)evt.mousePosition.y;
eventData.Button = MouseEventData.MouseButton.ButtonNone;
if (evt.button == 0) {
eventData.Button = MouseEventData.MouseButton.ButtonLeft;
} else if (evt.button == 2) {
eventData.Button = MouseEventData.MouseButton.ButtonMiddle;
} else if (evt.button == 1) {
eventData.Button = MouseEventData.MouseButton.ButtonRight;
}
// eventData.Type is left uninitialized
return eventData;
}
public static KeyEventData ProcessKeyEvent (Event evt)
{
KeyEventData eventData = new KeyEventData ();
eventData.Modifiers = GetEventModifiersState (evt);
eventData.KeyCode = s_KeyCodeMapping [(int)evt.keyCode];
eventData.IsNumPad = evt.numeric;
eventData.IsAutoRepeat = false; // Indeterminate
return eventData;
}
public static KeyEventData ProcessCharEvent (Event evt)
{
KeyEventData eventData = new KeyEventData ();
eventData.Modifiers = GetEventModifiersState (evt);
eventData.KeyCode = evt.character;
eventData.IsNumPad = evt.numeric;
eventData.IsAutoRepeat = false; // Indeterminate
eventData.Type = KeyEventData.EventType.Char;
return eventData;
}
}
}
| |
///////////////////////////////////////////////////////////////////////////////////////////////
//
// This File is Part of the CallButler Open Source PBX (http://www.codeplex.com/callbutler
//
// Copyright (c) 2005-2008, Jim Heising
// 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 Jim Heising 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.
//
///////////////////////////////////////////////////////////////////////////////////////////////
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Text;
using System.Windows.Forms;
using System.Xml;
namespace Controls
{
public partial class MapViewerControl : UserControl
{
private int zoomLevel = 0;
private double lat = 0;
private double lon = 0;
private string location = "";
private const string googleAPIKey = "ABQIAAAA_YO-lmQYdOWB8HEXfg9hHBRwqw291EfmGrUnOiS1DlRidXhZmBTd-NCr9q52qgbSyxSbZB8b-SS43g";
public MapViewerControl()
{
InitializeComponent();
ReloadMap();
}
public int Zoom
{
get
{
return zoomLevel;
}
set
{
zoomLevel = Math.Min(Math.Max(value, 0), 19);
ReloadMap();
}
}
public string MapLocation
{
get
{
return location;
}
set
{
lat = 0;
lon = 0;
LoadLocation(value);
}
}
public double Latitude
{
get
{
return lat;
}
set
{
lat = value;
ReloadMap();
}
}
public double Longitude
{
get
{
return lon;
}
set
{
lon = value;
ReloadMap();
}
}
public bool LoadLocation(string location, int zoom)
{
zoomLevel = Math.Min(Math.Max(zoom, 0), 19);
return LoadLocation(location);
}
public bool LoadLocation(string location)
{
string url = new System.Uri(string.Format("http://maps.google.com/maps/geo?q={0}&output=xml&key={1}", location, googleAPIKey)).AbsoluteUri;
try
{
XmlDocument xmlDoc = new XmlDocument();
// Load our URL
System.Net.HttpWebResponse response = (System.Net.HttpWebResponse)System.Net.HttpWebRequest.Create(url).GetResponse();
System.IO.StreamReader stream = new System.IO.StreamReader(response.GetResponseStream());
string responseString = stream.ReadToEnd();
stream.Close();
response.Close();
xmlDoc.LoadXml(responseString);
// Check to make sure our response is okay
XmlNode responseNode = xmlDoc.DocumentElement["Response"]["Status"]["code"];
if(responseNode != null && responseNode.InnerText == "200")
{
XmlNode coordinatesNode = xmlDoc.DocumentElement["Response"]["Placemark"]["Point"]["coordinates"];
string[] coordString = coordinatesNode.InnerText.Split(',');
double lat = 0;
double lon = 0;
if (double.TryParse(coordString[1], out lat) && double.TryParse(coordString[0], out lon))
{
LoadLocation(lat, lon);
return true;
}
}
}
catch(Exception e)
{
}
return false;
}
public void LoadLocation(double latitude, double longitude, int zoom)
{
zoomLevel = Math.Min(Math.Max(zoom, 0), 19);
LoadLocation(latitude, longitude);
}
public void LoadLocation(double latitude, double longitude)
{
this.lat = latitude;
this.lon = longitude;
ReloadMap();
}
private void ReloadMap()
{
string url = string.Format("http://maps.google.com/staticmap?center={0},{1}&zoom={2}&size={3}x{4}&key={5}", Latitude, Longitude, Zoom, this.Width, this.Height, googleAPIKey);
try
{
pbMap.Load(url);
}
catch
{
}
}
public static Image GetMapImage(double latitude, double longitude, int zoom, int width, int height)
{
try
{
string url = string.Format("http://maps.google.com/staticmap?center={0},{1}&zoom={2}&size={3}x{4}&key={5}", latitude, longitude, Math.Min(Math.Max(zoom, 0), 19), width, height, googleAPIKey);
Bitmap bmp = new Bitmap(System.Net.HttpWebRequest.Create(url).GetResponse().GetResponseStream());
return bmp;
}
catch
{
}
return null;
}
public static Image GetMapImage(string location, int zoom, int width, int height)
{
string url = new System.Uri(string.Format("http://maps.google.com/maps/geo?q={0}&output=xml&key={1}", location, googleAPIKey)).AbsoluteUri;
try
{
XmlDocument xmlDoc = new XmlDocument();
// Load our URL
System.Net.HttpWebResponse response = (System.Net.HttpWebResponse)System.Net.HttpWebRequest.Create(url).GetResponse();
System.IO.StreamReader stream = new System.IO.StreamReader(response.GetResponseStream());
string responseString = stream.ReadToEnd();
stream.Close();
response.Close();
xmlDoc.LoadXml(responseString);
// Check to make sure our response is okay
XmlNode responseNode = xmlDoc.DocumentElement["Response"]["Status"]["code"];
if (responseNode != null && responseNode.InnerText == "200")
{
XmlNode coordinatesNode = xmlDoc.DocumentElement["Response"]["Placemark"]["Point"]["coordinates"];
string[] coordString = coordinatesNode.InnerText.Split(',');
double lat = 0;
double lon = 0;
if (double.TryParse(coordString[1], out lat) && double.TryParse(coordString[0], out lon))
{
return GetMapImage(lat, lon, zoom, width, height);
}
}
}
catch (Exception e)
{
}
return null;
}
private void pbMap_SizeChanged(object sender, EventArgs e)
{
ReloadMap();
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Text;
using gov.va.medora.mdo.utils;
using System.Threading;
namespace gov.va.medora.mdo.dao
{
public class ConnectionManager
{
IndexedHashtable cxnTbl;
string modality;
public ConnectionManager(string modality)
{
this.modality = modality;
cxnTbl = new IndexedHashtable();
}
public ConnectionManager(Connection cxn)
{
this.modality = cxn.DataSource.Modality;
cxnTbl = new IndexedHashtable();
addConnection(cxn);
}
public ConnectionManager(DataSource src)
{
this.modality = src.Modality;
DaoFactory df = DaoFactory.getDaoFactory(DaoFactory.getConstant(src.Protocol));
Connection cxn = df.getConnection(src);
cxnTbl = new IndexedHashtable();
addConnection(cxn);
}
internal void checkModality(Connection cxn)
{
checkModality(cxn.DataSource.Modality);
}
internal void checkModality(DataSource src)
{
checkModality(src.Modality);
}
internal void checkModality(string modality)
{
if (modality != this.modality)
{
throw new Exception("Invalid modality");
}
}
public void addConnection(Connection cxn)
{
if (cxnTbl == null)
{
cxnTbl = new IndexedHashtable();
this.modality = cxn.DataSource.Modality;
}
checkModality(cxn);
if (!cxnTbl.ContainsKey(cxn.DataSource.SiteId.Id))
{
cxnTbl.Add(cxn.SiteId.Key,cxn);
}
}
public void addConnection(DataSource src)
{
if (src.Modality != this.modality)
{
throw new Exception("Invalid modality: expected " + this.modality + ", got " + src.Modality);
}
if (!cxnTbl.ContainsKey(src.SiteId.Key))
{
int protocol = DaoFactory.getConstant(src.Protocol);
DaoFactory daoFactory = DaoFactory.getDaoFactory(protocol);
cxnTbl.Add(src.SiteId.Key, daoFactory.getConnection(src));
}
}
public void removeConnection(string siteId)
{
if (cxnTbl.ContainsKey(siteId))
{
Connection cxn = (Connection)cxnTbl.GetValue(siteId);
if (cxn.IsConnected)
{
cxn.disconnect();
}
cxnTbl.Remove(siteId);
}
}
public void addConnections(string sitelist, SiteTable siteTbl)
{
string[] siteIds = StringUtils.split(sitelist, StringUtils.COMMA);
for (int i = 0; i < siteIds.Length; i++)
{
Site site = siteTbl.getSite(siteIds[i]);
if (site == null)
{
throw new Exception("No such site: " + siteIds[i]);
}
DataSource src = site.getDataSourceByModality(this.modality);
if (src == null)
{
throw new Exception("No " + modality + " data source at site " + siteIds[i]);
}
int protocol = DaoFactory.getConstant(src.Protocol);
DaoFactory daoFactory = DaoFactory.getDaoFactory(protocol);
addConnection(daoFactory.getConnection(src));
}
}
public void addConnections(DataSource[] sources)
{
for (int i = 0; i < sources.Length; i++)
{
int protocol = DaoFactory.getConstant(sources[i].Protocol);
DaoFactory daoFactory = DaoFactory.getDaoFactory(protocol);
addConnection(daoFactory.getConnection(sources[i]));
}
}
public void addConnections(IndexedHashtable t)
{
for (int i = 0; i < t.Count; i++)
{
Connection cxn = (Connection)t.GetValue(i);
addConnection(cxn);
}
}
public IndexedHashtable connect()
{
int lth = cxnTbl.Count;
QueryThread[] queries = new QueryThread[lth];
Thread[] threads = new Thread[lth];
for (int i = 0; i < lth; i++)
{
queries[i] = new QueryThread(cxnTbl.GetValue(i), "connect", new Object[0]);
threads[i] = new Thread(new ThreadStart(queries[i].execute));
threads[i].Start();
}
IndexedHashtable result = new IndexedHashtable(lth);
for (int i = 0; i < lth; i++)
{
string key = (string)cxnTbl.GetKey(i);
threads[i].Join();
//Need to report result whether it's a connection or an exception.
if (queries[i].isExceptionResult())
{
result.Add(key, queries[i].Result);
Connection cxn = (Connection)cxnTbl.GetValue(i);
cxn.ErrorMessage = ((Exception)queries[i].Result).Message;
cxn.IsConnected = false;
}
else
{
result.Add(key, ((Connection)cxnTbl.GetValue(key)).DataSource);
}
}
return result;
}
IndexedHashtable getConnections()
{
IndexedHashtable result = new IndexedHashtable();
for (int i = 0; i < cxnTbl.Count; i++)
{
Connection cxn = (Connection)cxnTbl.GetValue(i);
if (cxn.IsConnected)
{
result.Add(cxn.SiteId.Key, cxn);
}
}
if (result.Count == 0)
{
return null;
}
return result;
}
public IndexedHashtable Connections
{
get { return getConnections(); }
}
public Connection getConnection(string id)
{
if (cxnTbl == null || !cxnTbl.ContainsKey(id))
{
return null;
}
return (Connection)cxnTbl.GetValue(id);
}
public Connection LoginConnection
{
get { return (Connection)cxnTbl.GetValue(0); }
}
public IndexedHashtable disconnect()
{
if (cxnTbl.Count == 0)
{
throw new Exception("No connections");
}
// Only disconnect from the ones that are connected
IndexedHashtable myCxns = getConnections();
int lth = myCxns.Count;
QueryThread[] queries = new QueryThread[lth];
Thread[] threads = new Thread[lth];
for (int i = 0; i < lth; i++)
{
queries[i] = new QueryThread(myCxns.GetValue(i), "disconnect", new Object[0]);
threads[i] = new Thread(new ThreadStart(queries[i].execute));
threads[i].Start();
}
IndexedHashtable result = new IndexedHashtable(lth);
for (int i = 0; i < lth; i++)
{
string key = (string)myCxns.GetKey(i);
threads[i].Join();
if (queries[i].isExceptionResult())
{
result.Add(key, queries[i].Result);
}
else
{
result.Add(key, "OK");
}
}
// We only disconnected from connected connections, but we want to clear
// the entire table
cxnTbl = new IndexedHashtable();
return result;
}
public IndexedHashtable disconnectRemoteSites()
{
if (cxnTbl.Count < 2)
{
throw new Exception("No remote connections");
}
// Only disconnect from the ones that are connected
IndexedHashtable myCxns = getConnections();
int lth = myCxns.Count - 1;
QueryThread[] queries = new QueryThread[lth];
Thread[] threads = new Thread[lth];
for (int threadIdx = 0, cxnIdx = 1; threadIdx < lth; threadIdx++, cxnIdx++)
{
queries[threadIdx] = new QueryThread(myCxns.GetValue(cxnIdx), "disconnect", new Object[0]);
threads[threadIdx] = new Thread(new ThreadStart(queries[threadIdx].execute));
threads[threadIdx].Start();
}
IndexedHashtable result = new IndexedHashtable(lth);
for (int threadIdx = 0, cxnIdx = 1; threadIdx < lth; threadIdx++, cxnIdx++)
{
string key = (string)myCxns.GetKey(cxnIdx);
threads[threadIdx].Join();
if (queries[threadIdx].isExceptionResult())
{
result.Add(key, queries[threadIdx].Result);
}
else
{
result.Add(key, "OK");
}
}
// Now remove all but the logon connection from the table
Connection loginCxn = LoginConnection;
cxnTbl = new IndexedHashtable();
cxnTbl.Add(loginCxn.SiteId.Key, loginCxn);
return result;
}
public string Modality
{
get { return modality; }
}
public bool isAuthorized
{
get
{
if (cxnTbl == null || cxnTbl.Count == 0)
{
return false;
}
Connection cxn = (Connection)cxnTbl.GetValue(0);
if (!cxn.IsConnected || cxn.Uid == "")
{
return false;
}
return true;
}
}
public bool isAuthorizedForSite(string sitecode)
{
if (!isAuthorized)
{
return false;
}
Connection cxn = getConnection(sitecode);
if (cxn == null || !cxn.IsConnected || cxn.Uid == "")
{
return false;
}
return true;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlTypes;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using System.Xml;
using ILPathways.Utilities;
//using LearningRegistryCache2.App_Code.Classes;
using OLDDM = LearningRegistryCache2.App_Code.DataManagers;
using LRWarehouse.Business;
using LRWarehouse.DAL;
namespace LearningRegistryCache2
{
public class LearningRegistry : BaseDataController
{
private ResourceManager resourceManager = new ResourceManager();
private OLDDM.SubmitterManager submitterManager = new OLDDM.SubmitterManager();
//TODO - use resource property
private ResourcePropertyManager resourcePropManager = new ResourcePropertyManager();
private AuditReportingManager auditReportingManager = new AuditReportingManager();
//private NameValueManager nameValueManager = new NameValueManager();
private NsdlHandler nsdlHandler = new NsdlHandler();
private LomHandler lomHandler = new LomHandler();
private CommParaHandler commParaHandler = new CommParaHandler();
private LRParadataHandler lrParaHandler = new LRParadataHandler();
private LrmiHandler lrmiHandler = new LrmiHandler();
private BlacklistedHostManager blacklistedHostManager = new BlacklistedHostManager();
private OLDDM.LearningRegistryManager registryManager = new OLDDM.LearningRegistryManager();
private int maxRecords = 10;
int recordCntr = 0;
private string ourSignerTag = "";
public static int reportId = 0;
public static string fileName = "";
public static List<int> resourceIdList = new List<int>();
public static string deleteResourceIdList = "";
public static string EmailBody = "";
public static int lrRecordsRead = 0;
public static int lrRecordsProcessed = 0;
public static int lrRecordsSpam = 0;
public static int lrRecordsUnknownSchema = 0;
public static int lrRecordsEmptySchema = 0;
public static int lrRecordsBadDataType = 0;
public static int lrRecordsBadPayloadPlacement = 0;
public static bool HasEsUploadErrors = false;
public static string EsIdDate = DateTime.Now.ToString("yyyy-MM-dd");
public LearningRegistry()
{
ourSignerTag = ConfigurationManager.AppSettings["ourSigner"].ToString();
}
public void ExtractData(string startDate, string endDate, bool isBatch)
{
int maxRecordsInFile=int.Parse(ConfigurationManager.AppSettings["maxRecordsInFile"].ToString());
reportId = auditReportingManager.CreateReport();
XmlDocument newDoc = new XmlDocument();
newDoc.LoadXml("<root></root>");
int passNbr = 1;
string resumeToken = "";
string lrStartDate = TimeZoneInfo.ConvertTimeToUtc(DateTime.Parse(startDate)).ToString("yyyy-MM-dd HH:mm:ss").Replace(" ","T")+"Z";
string lrEndDate = TimeZoneInfo.ConvertTimeToUtc(DateTime.Parse(endDate)).ToString("yyyy-MM-dd HH:mm:ss").Replace(" ","T")+"Z";
do
{
XmlDocument document = registryManager.BasicListRecords(lrStartDate, lrEndDate, ref resumeToken);
XmlNodeList records = document.GetElementsByTagName("record");
foreach (XmlNode record in records)
{
XmlNode node = newDoc.ImportNode(record, true);
newDoc.DocumentElement.AppendChild(node);
lrRecordsRead++;
}
if (newDoc.DocumentElement.ChildNodes.Count >= maxRecordsInFile)
{
SaveDoc(newDoc, DateTime.Parse(endDate), isBatch);
newDoc = new XmlDocument();
newDoc.LoadXml("<root></root>");
}
} while (resumeToken != null && (resumeToken != "" && resumeToken != "null"));
SaveDoc(newDoc, DateTime.Parse(endDate), isBatch);
}
public void ProcessPath(string path, bool isBatch)
{
bool honorDisallowedTimes = bool.Parse(ConfigurationManager.AppSettings["honorDisallowedTimes"]);
string restrictedDays = ConfigurationManager.AppSettings["disallowedDays"];
TimeSpan restrictedStartTime = TimeSpan.Parse(ConfigurationManager.AppSettings["disallowBatchStart"]);
TimeSpan restrictedEndTime = TimeSpan.Parse(ConfigurationManager.AppSettings["disallowBatchEnd"]);
string currentDayOfWeek = "";
TimeSpan currentTime = DateTime.Now.TimeOfDay;
if (isBatch && honorDisallowedTimes)
{
currentDayOfWeek = ((int)DateTime.Now.DayOfWeek).ToString();
if (restrictedDays.IndexOf(currentDayOfWeek) > -1)
{
// We are in one of the days where we do not want to allow import during the day, check to see if we're within the timeframe
if (currentTime > restrictedStartTime && currentTime < restrictedEndTime)
{
Console.WriteLine("Processing ended early due to time restrictions");
return;
}
}
}
char[] delim = new char[1];
delim[0]='\\';
string[] pathParts = path.Split(delim);
string directory = "";
for (int i = 0; i < pathParts.Length - 1; i++)
{
directory += pathParts[i] + "\\";
}
string[] filePaths = Directory.GetFiles(directory, pathParts[pathParts.Length - 1]);
foreach (string file in filePaths)
{
Console.WriteLine("Starting " + file);
ProcessFile(file);
if (isBatch)
{
MoveToArchive(file);
}
// Check for time restriction
if (isBatch && honorDisallowedTimes)
{
currentDayOfWeek = ((int)DateTime.Now.DayOfWeek).ToString();
if (restrictedDays.IndexOf(currentDayOfWeek) > -1)
{
// We are in one of the days where we do not want to allow import during the day, check to see if we're within the timeframe
currentTime = DateTime.Now.TimeOfDay;
if (currentTime > restrictedStartTime && currentTime < restrictedEndTime)
{
Console.WriteLine("Processing ended early due to time restrictions");
break;
}
}
}
} //foreach file
}
public string GetFilePath(DateTime date, bool isBatch)
{
string retVal = "";
if (isBatch)
{
retVal = ConfigurationManager.AppSettings["xml.batchPath"];
}
else
{
retVal = ConfigurationManager.AppSettings["xml.path"].Replace("[date]", date.ToString("yyyy-MM-dd_hhmmss"));
}
return retVal;
}
private void MoveToArchive(string file)
{
string archivePath = Path.Combine(Path.GetDirectoryName(file),"archive");
if (!Directory.Exists(archivePath))
{
Directory.CreateDirectory(archivePath);
}
File.Move(file, Path.Combine(archivePath, Path.GetFileName(file)));
}
public void ProcessFile(string file)
{
fileName = file;
bool recordIsSpam = false;
int recordCount = 0;
reportId = auditReportingManager.CreateReport();
XmlDocument doc = new XmlDocument();
doc.Load(fileName);
resourceIdList = new List<int>();
XmlNodeList records = doc.GetElementsByTagName("record");
foreach (XmlNode record in records)
{
recordCount++;
Console.WriteLine(recordCount.ToString());
recordIsSpam = SpamChecker.IsSpam(record.OuterXml);
if (!recordIsSpam)
{
XmlDocument xdoc = new XmlDocument();
xdoc.LoadXml(record.OuterXml);
ProcessNode(xdoc);
lrRecordsProcessed++;
}
else
{
lrRecordsSpam++;
}
} //foreach record
// Update ElasticSearch
string status = "successful";
string collectionName = UtilityManager.GetAppKeyValue( "elasticSearchCollection", "collection5" );
// NO longer deleting resources from ES Index since ES uses IntId instead of VersionId. Kept for historical purposes.
/*if (deleteResourceIdList.Length > 1)
{
deleteResourceIdList = deleteResourceIdList.Substring(0, deleteResourceIdList.Length - 1);
string[] deleteVersionList = deleteResourceIdList.Split(',');
searchManager.MassDeleteByIntID(deleteVersionList, ref status);
}*/
if (resourceIdList.Count > 0)
{
try
{
searchManager.RefreshResources(resourceIdList);
}
catch (Exception ex)
{
HasEsUploadErrors = true;
string fn = ConfigurationManager.AppSettings["esIdLog"].Replace("[date]", EsIdDate);
using (StreamWriter sw = File.AppendText(fn))
{
foreach (int id in resourceIdList)
{
sw.WriteLine(id+",");
}
}
}
}
// Update data warehouse totals
string whtStatus = DatabaseManager.UpdateWarehouseTotals();
if (whtStatus != "successful")
{
auditReportingManager.LogMessage(reportId, fileName, "", "", ErrorType.Error, ErrorRouting.Technical, whtStatus);
}
// Update publisher totals
string pubStatus = DatabaseManager.UpdatePublisherTotals();
if (whtStatus != "successful")
{
auditReportingManager.LogMessage(reportId, fileName, "", "", ErrorType.Error, ErrorRouting.Technical, whtStatus);
}
}
public void ProcessNode(XmlDocument xdoc)
{
string docID = "";
string url = "";
string resourceDataType = "";
string payloadPlacement = "";
XmlDocument xpayload = new XmlDocument();
Resource resource = new Resource();
XmlNodeList list;
// Determine if the signer is us. If we signed the document, skip it.
string signer = GetSigner(xdoc);
if (signer.ToLower() == ourSignerTag.ToLower())
{
return;
}
// We didn't sign it, processing continues...
// Get docID, resource locator, data type, and payload placement
list = xdoc.GetElementsByTagName("doc_ID");
if (list.Count > 0)
{
docID = TrimWhitespace(list[0].InnerText);
}
else
{
docID = "";
}
resource.Version.LRDocId = docID;
list = xdoc.GetElementsByTagName("resource_locator");
if (list.Count > 0)
{
url = resourceBizService.CleanseUrl(TrimWhitespace(list[0].InnerText));
}
else
{
url = "";
}
resource.ResourceUrl = url;
list = xdoc.GetElementsByTagName("resource_data_type");
if (list.Count > 0)
{
resourceDataType = TrimWhitespace(list[0].InnerText);
}
else
{
resourceDataType = "";
}
list = xdoc.GetElementsByTagName("payload_placement");
if (list.Count > 0)
{
payloadPlacement = TrimWhitespace(list[0].InnerText);
}
else
{
payloadPlacement = "";
}
XmlNodeList schemaList = xdoc.GetElementsByTagName("payload_schema");
// Check docID, resource locator, data type, and payload placement. If these do not pass, log it and continue with the next record.
bool passedEdits = true;
if (url == "")
{
// URL not present in envelope - try to extract from payload instead. Seems to be a problem only for some NSDL/DC resources.
bool found = false;
foreach (XmlNode node in schemaList)
{
string payloadSchema = TrimWhitespace(node.InnerText);
switch (payloadSchema.ToLower())
{
case "nsdl_dc":
url = nsdlHandler.ExtractUrlFromPayload(docID, payloadPlacement, xdoc);
found = true;
break;
case "oai_dc":
url = nsdlHandler.ExtractUrlFromPayload(docID, payloadPlacement, xdoc);
found = true;
break;
case "nsdl dc 1.02.020":
url = nsdlHandler.ExtractUrlFromPayload(docID, payloadPlacement, xdoc);
found = true;
break;
case "dc":
url = nsdlHandler.ExtractUrlFromPayload(docID, payloadPlacement, xdoc);
found = true;
break;
case "dc 1.1":
url = nsdlHandler.ExtractUrlFromPayload(docID, payloadPlacement, xdoc);
found = true;
break;
default:
break;
}
if (url == "")
{
// No URL in payload either!
passedEdits = false;
auditReportingManager.LogMessage(reportId, fileName, docID, url, ErrorType.Error, ErrorRouting.Technical, "No URL found");
}
if (found)
{
break;
}
}
}
// Check for malware/phishing/blacklist
try
{
string status = "";
Uri uri = new Uri(url);
BlacklistedHost bh = blacklistedHostManager.GetByHostname(uri.Host, ref status);
if (bh != null)
{
auditReportingManager.LogMessage(reportId, fileName, docID, url, ErrorType.Error, ErrorRouting.Program,
"This URL is suspected to be a phishing page, contain malware, or may otherwise be inappropriate.");
passedEdits = false;
}
else
{
string reputation = ILPathways.Utilities.UtilityManager.CheckUnsafeUrl(url);
if (reputation == "Blacklisted")
{
auditReportingManager.LogMessage(reportId, fileName, docID, url, ErrorType.Error, ErrorRouting.Program,
"This URL is suspected to be a phishing page, contain malware, or may otherwise be inappropriate. " +
"Learn more about phishing at www.antiphishing.org. Learn more about malware at www.stopbadware.org. " +
"Advisory provided by Google at http://code.google.com/apis/safebrowsing/safebrowsing_faq.html#whyAdvisory.");
passedEdits = false;
}
}
}
catch (Exception ex)
{
auditReportingManager.LogMessage(reportId, fileName, docID, url, ErrorType.Error, ErrorRouting.Technical, "LearningRegistry.ProcessNode(): " + ex.Message);
}
if (resourceDataType != "metadata" && resourceDataType != "paradata")
{
passedEdits = false;
auditReportingManager.LogMessage(reportId, fileName, docID, url, ErrorType.Error, ErrorRouting.Technical, "Invalid resource data type");
lrRecordsBadDataType++;
}
if (payloadPlacement == "none")
{
//TODO: Write Delete process
//ProcessDelete(xdoc);
}
else if (payloadPlacement != "inline")
{
passedEdits = false;
auditReportingManager.LogMessage(reportId, fileName, docID, url, ErrorType.Error, ErrorRouting.Technical, "Payload placement is not \"inline.\"");
lrRecordsBadPayloadPlacement++;
}
// If the edits passed so far, continue processing
if (passedEdits)
{
bool found = false;
foreach (XmlNode node in schemaList)
{
string payloadSchema = TrimWhitespace(node.InnerText);
if (payloadSchema.ToLower().IndexOf("json-ld") > -1 || payloadSchema.ToLower().IndexOf("jsonld") > -1 || payloadSchema.ToLower().IndexOf("lrmi") > -1)
{
lrmiHandler.LrmiMap(docID, url, payloadPlacement, xdoc);
found = true;
}
else
{
switch (payloadSchema.ToLower())
{
case "nsdl_dc":
nsdlHandler.NsdlMap(docID, url, payloadPlacement, xdoc);
found = true;
break;
case "nsdl dc 1.02.020":
nsdlHandler.NsdlMap(docID, url, payloadPlacement, xdoc);
found = true;
break;
case "dc":
nsdlHandler.NsdlMap(docID, url, payloadPlacement, xdoc);
found = true;
break;
case "oai_dc":
nsdlHandler.NsdlMap(docID, url, payloadPlacement, xdoc);
found = true;
break;
case "dc 1.1":
nsdlHandler.NsdlMap(docID, url, payloadPlacement, xdoc);
found = true;
break;
// Some ID10T decided it would be great to plug in a payload schema of "hashtags". They all seem to be NSDL so I'm gonna handle 'em as such.
// Commented out once initial load is done.
case "hashtags":
nsdlHandler.NsdlMap(docID, url, payloadPlacement, xdoc);
found = true;
break;
case "lom":
lomHandler.LomMap(docID, url, payloadPlacement, xdoc);
found = true;
break;
case "lomv1.0adl-rv1.0":
lomHandler.LomMap(docID, url, payloadPlacement, xdoc);
found = true;
break;
case "ieee lom 2002":
lomHandler.LomMap(docID, url, payloadPlacement, xdoc);
found = true;
break;
case "lrmi":
lrmiHandler.LrmiMap(docID, url, payloadPlacement, xdoc);
found = true;
break;
case "comm_para 1.0":
commParaHandler.CommParaMap(docID, url, payloadPlacement, xdoc);
found = true;
break;
case "comm_para":
commParaHandler.CommParaMap(docID, url, payloadPlacement, xdoc);
found = true;
break;
case "oai_paradata":
commParaHandler.CommParaMap(docID, url, payloadPlacement, xdoc);
found = true;
break;
case "lr paradata 1.0":
lrParaHandler.LrParadataMap(docID, url, payloadPlacement, xdoc);
found = true;
break;
default:
break;
}
}
if (found)
{
/* if (!IsTestEnv())
{// Production - don't overload Elastic Search with requests
Console.WriteLine("Sleeping 15 seconds to not overwhelm ElasticSearch");
System.Threading.Thread.Sleep(15000);
} */
break;
}
}
if (!found)
{
if (schemaList != null && schemaList.Count > 0)
{
string payloadSchema = TrimWhitespace(schemaList[0].InnerText);
auditReportingManager.LogMessage(reportId, fileName, docID, url, ErrorType.Error, ErrorRouting.Technical,
string.Format("Unknown metadata/paradata schema \"{0}\"", payloadSchema));
lrRecordsUnknownSchema++;
}
else
{
auditReportingManager.LogMessage(reportId, fileName, docID, url, ErrorType.Error, ErrorRouting.Technical,
"Empty metadata/paradata schema!");
lrRecordsEmptySchema++;
}
}
}
}
/* public void ProcessDelete(XmlDocument xdoc)
{
ResourceVersionManager rvm = new ResourceVersionManager();
ResourceCommentManager rcm = new ResourceCommentManager();
XmlNodeList nodes = xdoc.GetElementsByTagName("replaces");
foreach(XmlNode node in nodes) {
string replaces = TrimWhitespace(node.InnerText);
string filter = string.Format("DocId = '{0}' AND Submitter = {1}",replaces, GetSigner(xdoc));
DataSet ds = rvm.Select(filter);
if(ResourceVersionManager.DoesDataSetHaveRows(ds)) {
} */
public void ExtractVerb(string path, string verb)
{
string directory = Path.GetDirectoryName(path);
string files = directory + "\\*.xml";
string outFile = Path.Combine(directory, verb + ".xml");
int nbrRecords = 0;
XmlDocument newDoc = new XmlDocument();
newDoc.LoadXml("<root></root>");
string[] filePaths = Directory.GetFiles(directory, "*.xml");
foreach (string file in filePaths)
{
Console.WriteLine("Starting " + file);
XmlDocument xdoc = new XmlDocument();
xdoc.Load(file);
XmlNodeList list = xdoc.GetElementsByTagName("record");
foreach (XmlNode node in list)
{
XmlDocument record = new XmlDocument();
record.LoadXml(node.OuterXml);
XmlNodeList xAction = record.GetElementsByTagName("action");
if (xAction.Count > 0 && xAction[0].InnerText.ToLower() == verb.ToLower())
{
XmlNode newNode = newDoc.ImportNode(node, true);
newDoc.DocumentElement.AppendChild(newNode);
nbrRecords++;
Console.WriteLine(nbrRecords);
}
}
}
newDoc.Save(outFile);
}
public void ExtractSchema(string path, string schema)
{
string directory = Path.GetDirectoryName(path);
string files = directory + "\\*.xml";
string outFile = Path.Combine(directory, schema + ".xml");
int nbrRecords = 0;
bool found = false;
XmlDocument newDoc = new XmlDocument();
newDoc.LoadXml("<root></root>");
string[] filePaths = Directory.GetFiles(directory, "*.xml");
foreach (string file in filePaths)
{
Console.WriteLine("Starting " + file);
XmlDocument xdoc = new XmlDocument();
xdoc.Load(file);
XmlNodeList list = xdoc.GetElementsByTagName("record");
foreach (XmlNode node in list)
{
XmlDocument record = new XmlDocument();
record.LoadXml(node.OuterXml);
XmlNodeList xSchema = record.GetElementsByTagName("payload_schema");
found = false;
foreach (XmlNode sNode in xSchema)
{
if (sNode.InnerText.ToLower() == schema.ToLower())
{
found = true;
break;
}
}
if (found)
{
XmlNode newNode = newDoc.ImportNode(node, true);
newDoc.DocumentElement.AppendChild(newNode);
nbrRecords++;
Console.WriteLine(nbrRecords);
if ((nbrRecords % 200) == 0)
{
newDoc.Save(outFile.Replace(".xml","") + nbrRecords.ToString() + ".xml");
newDoc = new XmlDocument();
newDoc.LoadXml("<root></root>");
}
}
}
}
newDoc.Save(outFile.Replace(".xml", "") + nbrRecords.ToString() + ".xml");
}
public void UndeleteResources()
{
DataSet ds = resourceManager.GetListOfResourcesToUndelete(true);
string collectionName = UtilityManager.GetAppKeyValue( "elasticSearchCollection", "collection5" );
if (ResourceManager.DoesDataSetHaveRows(ds))
{
List<int> undelResIds = new List<int>();
foreach (DataRow dr in ds.Tables[0].Rows)
{
string listOfResources = ResourceManager.GetRowColumn(dr, "ResourceIds", "");
string[] resIds = listOfResources.Split(',');
foreach (string id in resIds)
{
undelResIds.Add(int.Parse(id));
}
string status = "successful";
searchManager.RefreshResources(undelResIds);
// Pause so as to not overwhelm ElasticSearch
Console.WriteLine("Sleeping 60 seconds so as to not overwhelm ElasticSearch");
System.Threading.Thread.Sleep(60000);
}
}
}
protected void GetDocId(Resource resource, XmlDocument record)
{
XmlNodeList list = record.GetElementsByTagName("doc_ID");
resource.Version.LRDocId = TrimWhitespace(list[0].InnerText);
}
protected void GetCreatedDate(Resource resource, XmlDocument record)
{
XmlNodeList list = record.GetElementsByTagName("datestamp");
string sqlDate = TrimWhitespace(list[0].InnerText);
if (sqlDate == null || sqlDate == "")
{
resource.Version.Created = DateTime.Now;
}
else
{
sqlDate = sqlDate.Replace("T", " ").Replace("Z", "");
resource.Version.Created = DateTime.Parse(sqlDate);
if (resource.Version.Created < System.Data.SqlTypes.SqlDateTime.MinValue)
{
resource.Version.Created = DateTime.Now;
}
}
}
protected void SaveDoc(XmlDocument xdoc, DateTime date, bool isBatch)
{
string docLoc = GetFilePath(date, isBatch);
// Check if folder exists. If not, then create it.
bool folderExists = Directory.Exists(docLoc);
if (!folderExists)
{
Directory.CreateDirectory(docLoc);
}
docLoc += ConfigurationManager.AppSettings["xml.log"].ToString();
// Save the document to a file. White space is
// preserved (no white space).
xdoc.PreserveWhitespace = true;
docLoc = docLoc.Replace("[date]", System.DateTime.Now.ToString("yyyy-MM-dd_hhmmss_") + System.DateTime.Now.Millisecond.ToString());
Console.WriteLine(string.Format("Storing {0}",docLoc));
xdoc.Save(docLoc);
} //
public static bool IsTestEnv()
{
bool isTestEnv = false;
try
{
isTestEnv = bool.Parse(ConfigurationManager.AppSettings["IsTestEnv"].ToString());
}
catch (Exception ex)
{
// Default to false
}
return isTestEnv;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Drawing;
using MonoMac.Foundation;
using MonoMac.AppKit;
using MonoMac.ObjCRuntime;
namespace Microsoft.Xna.Framework.GamerServices
{
public partial class SigninController : MonoMac.AppKit.NSWindowController
{
NSApplication NSApp = NSApplication.SharedApplication;
internal List<MonoGameLocalGamerProfile> gamerList;
internal NSTableView tableView;
#region Constructors
// Called when created from unmanaged code
public SigninController (IntPtr handle) : base(handle)
{
Initialize ();
}
// Called when created directly from a XIB file
[Export("initWithCoder:")]
public SigninController (NSCoder coder) : base(coder)
{
Initialize ();
}
// // Call to load from the XIB/NIB file
// public SigninController () : base("TableEdit")
// {
// Initialize ();
// }
public SigninController()
{
Initialize();
}
NSWindow window = null;
internal NSButton selectButton;
// Shared initialization code
void Initialize ()
{
//window = new NSWindow(new RectangleF(0,0, 470, 250), NSWindowStyle.Titled | NSWindowStyle.Closable, NSBackingStore.Buffered, false);
window = new NSWindow(new RectangleF(0,0, 470, 250), NSWindowStyle.Titled, NSBackingStore.Buffered, false);
window.HasShadow = true;
NSView content = window.ContentView;
window.WindowController = this;
window.Title = "Sign In";
NSTextField signInLabel = new NSTextField(new RectangleF(17, 190, 109, 17));
signInLabel.StringValue = "Sign In:";
signInLabel.Editable = false;
signInLabel.Bordered = false;
signInLabel.BackgroundColor = NSColor.Control;
content.AddSubview(signInLabel);
// Create our select button
selectButton = new NSButton(new RectangleF(358,12,96,32));
selectButton.Title = "Select";
selectButton.SetButtonType(NSButtonType.MomentaryPushIn);
selectButton.BezelStyle = NSBezelStyle.Rounded;
selectButton.Activated += delegate {
profileSelected();
};
selectButton.Enabled = false;
content.AddSubview(selectButton);
// Setup our table view
NSScrollView tableContainer = new NSScrollView(new RectangleF(20,60,428, 123));
tableContainer.BorderType = NSBorderType.BezelBorder;
tableContainer.AutohidesScrollers = true;
tableContainer.HasVerticalScroller = true;
tableView = new NSTableView(new RectangleF(0,0,420, 123));
tableView.UsesAlternatingRowBackgroundColors = true;
NSTableColumn colGamerTag = new NSTableColumn("Gamer");
tableView.AddColumn(colGamerTag);
colGamerTag.Width = 420;
colGamerTag.HeaderCell.Title = "Gamer Profile";
tableContainer.DocumentView = tableView;
content.AddSubview(tableContainer);
// Create our add button
NSButton addButton = new NSButton(new RectangleF(20,27,25,25));
//Console.WriteLine(NSImage.AddTemplate);
addButton.Image = NSImage.ImageNamed("NSAddTemplate");
addButton.SetButtonType(NSButtonType.MomentaryPushIn);
addButton.BezelStyle = NSBezelStyle.SmallSquare;
addButton.Activated += delegate {
addLocalPlayer();
};
content.AddSubview(addButton);
// Create our remove button
NSButton removeButton = new NSButton(new RectangleF(44,27,25,25));
removeButton.Image = NSImage.ImageNamed("NSRemoveTemplate");
removeButton.SetButtonType(NSButtonType.MomentaryPushIn);
removeButton.BezelStyle = NSBezelStyle.SmallSquare;
removeButton.Activated += delegate {
removeLocalPlayer();
};
content.AddSubview(removeButton);
gamerList = MonoGameGamerServicesHelper.DeserializeProfiles();
// for (int x= 1; x< 25; x++) {
// gamerList.Add("Player " + x);
// }
tableView.DataSource = new GamersDataSource(this);
tableView.Delegate = new GamersTableDelegate(this);
}
#endregion
public new NSWindow Window {
get { return window; }
}
void profileSelected ()
{
if (tableView.SelectedRowCount > 0) {
var rowSelected = tableView.SelectedRow;
SignedInGamer sig = new SignedInGamer();
sig.DisplayName = gamerList[rowSelected].DisplayName;
sig.Gamertag = gamerList[rowSelected].Gamertag;
sig.InternalIdentifier = gamerList[rowSelected].PlayerInternalIdentifier;
Gamer.SignedInGamers.Add(sig);
}
MonoGameGamerServicesHelper.SerializeProfiles(gamerList);
NSApp.StopModal();
}
void removeLocalPlayer ()
{
Console.WriteLine("Remove local");
var rowToRemove = tableView.SelectedRow;
if (rowToRemove < 0 || rowToRemove > gamerList.Count -1)
return;
gamerList.RemoveAt(rowToRemove);
tableView.ReloadData();
}
void addLocalPlayer ()
{
MonoGameLocalGamerProfile prof = new MonoGameLocalGamerProfile();
prof.Gamertag = "New Player";
prof.DisplayName = prof.Gamertag;
gamerList.Add(prof);
tableView.ReloadData();
int newPlayerRow = gamerList.Count - 1;
tableView.ScrollRowToVisible(newPlayerRow);
tableView.EditColumn(0,newPlayerRow, new NSEvent(), true);
}
}
public class GamersDataSource : NSTableViewDataSource
{
SigninController controller;
public GamersDataSource (SigninController controller)
{
this.controller = controller;
}
public override int GetRowCount (NSTableView tableView)
{
return controller.gamerList.Count;
}
public override NSObject GetObjectValue (NSTableView tableView, NSTableColumn tableColumn, int row)
{
return new NSString(controller.gamerList[row].Gamertag);
}
public override void SetObjectValue (NSTableView tableView, NSObject theObject, NSTableColumn tableColumn, int row)
{
var proposedValue = theObject.ToString();
if (proposedValue.Trim().Length > 0) {
controller.gamerList[row].Gamertag = theObject.ToString();
controller.gamerList[row].DisplayName = theObject.ToString();
}
}
}
public class GamersTableDelegate : NSTableViewDelegate
{
SigninController controller;
public GamersTableDelegate (SigninController controller)
{
this.controller = controller;
}
public override bool ShouldSelectRow (NSTableView tableView, int row)
{
var profile = controller.gamerList[row];
foreach (var gamer in Gamer.SignedInGamers) {
if (profile.PlayerInternalIdentifier == gamer.InternalIdentifier)
return false;
}
return true;
}
public override void SelectionDidChange (NSNotification notification)
{
if (controller.tableView.SelectedRowCount > 0)
controller.selectButton.Enabled = true;
else
controller.selectButton.Enabled = false;
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.ComponentModel;
using System.IO;
using System.Runtime.InteropServices;
using System.Text;
namespace System.Diagnostics
{
public partial class Process : IDisposable
{
/// <summary>Gets the amount of time the process has spent running code inside the operating system core.</summary>
public TimeSpan PrivilegedProcessorTime
{
get
{
return TicksToTimeSpan(GetStat().stime);
}
}
/// <summary>Gets the time the associated process was started.</summary>
public DateTime StartTime
{
get
{
return BootTimeToDateTime(GetStat().starttime);
}
}
/// <summary>
/// Gets the amount of time the associated process has spent utilizing the CPU.
/// It is the sum of the <see cref='System.Diagnostics.Process.UserProcessorTime'/> and
/// <see cref='System.Diagnostics.Process.PrivilegedProcessorTime'/>.
/// </summary>
public TimeSpan TotalProcessorTime
{
get
{
Interop.procfs.ParsedStat stat = GetStat();
return TicksToTimeSpan(stat.utime + stat.stime);
}
}
/// <summary>
/// Gets the amount of time the associated process has spent running code
/// inside the application portion of the process (not the operating system core).
/// </summary>
public TimeSpan UserProcessorTime
{
get
{
return TicksToTimeSpan(GetStat().utime);
}
}
/// <summary>
/// Gets or sets which processors the threads in this process can be scheduled to run on.
/// </summary>
private unsafe IntPtr ProcessorAffinityCore
{
get
{
EnsureState(State.HaveId);
Interop.libc.cpu_set_t set = default(Interop.libc.cpu_set_t);
if (Interop.libc.sched_getaffinity(_processId, (IntPtr)sizeof(Interop.libc.cpu_set_t), &set) != 0)
{
throw new Win32Exception(); // match Windows exception
}
ulong bits = 0;
int maxCpu = IntPtr.Size == 4 ? 32 : 64;
for (int cpu = 0; cpu < maxCpu; cpu++)
{
if (Interop.libc.CPU_ISSET(cpu, &set))
bits |= (1u << cpu);
}
return (IntPtr)bits;
}
set
{
EnsureState(State.HaveId);
Interop.libc.cpu_set_t set = default(Interop.libc.cpu_set_t);
long bits = (long)value;
int maxCpu = IntPtr.Size == 4 ? 32 : 64;
for (int cpu = 0; cpu < maxCpu; cpu++)
{
if ((bits & (1u << cpu)) != 0)
Interop.libc.CPU_SET(cpu, &set);
}
if (Interop.libc.sched_setaffinity(_processId, (IntPtr)sizeof(Interop.libc.cpu_set_t), &set) != 0)
{
throw new Win32Exception(); // match Windows exception
}
}
}
/// <summary>
/// Make sure we have obtained the min and max working set limits.
/// </summary>
private void GetWorkingSetLimits(out IntPtr minWorkingSet, out IntPtr maxWorkingSet)
{
minWorkingSet = IntPtr.Zero; // no defined limit available
ulong rsslim = GetStat().rsslim;
// rsslim is a ulong, but maxWorkingSet is an IntPtr, so we need to cap rsslim
// at the max size of IntPtr. This often happens when there is no configured
// rsslim other than ulong.MaxValue, which without these checks would show up
// as a maxWorkingSet == -1.
switch (IntPtr.Size)
{
case 4:
if (rsslim > int.MaxValue)
rsslim = int.MaxValue;
break;
case 8:
if (rsslim > long.MaxValue)
rsslim = long.MaxValue;
break;
}
maxWorkingSet = (IntPtr)rsslim;
}
/// <summary>Sets one or both of the minimum and maximum working set limits.</summary>
/// <param name="newMin">The new minimum working set limit, or null not to change it.</param>
/// <param name="newMax">The new maximum working set limit, or null not to change it.</param>
/// <param name="resultingMin">The resulting minimum working set limit after any changes applied.</param>
/// <param name="resultingMax">The resulting maximum working set limit after any changes applied.</param>
private void SetWorkingSetLimitsCore(IntPtr? newMin, IntPtr? newMax, out IntPtr resultingMin, out IntPtr resultingMax)
{
// RLIMIT_RSS with setrlimit not supported on Linux > 2.4.30.
throw new PlatformNotSupportedException();
}
// -----------------------------
// ---- PAL layer ends here ----
// -----------------------------
/// <summary>Gets the path to the current executable, or null if it could not be retrieved.</summary>
private static string GetExePath()
{
// Determine the maximum size of a path
int maxPath = Interop.libc.MaxPath;
// Start small with a buffer allocation, and grow only up to the max path
for (int pathLen = 256; pathLen < maxPath; pathLen *= 2)
{
// Read from procfs the symbolic link to this process' executable
byte[] buffer = new byte[pathLen + 1]; // +1 for null termination
int resultLength = (int)Interop.Sys.ReadLink(Interop.procfs.SelfExeFilePath, buffer, (ulong)pathLen);
// If we got one, null terminate it (readlink doesn't do this) and return the string
if (resultLength > 0)
{
buffer[resultLength] = (byte)'\0';
return Encoding.UTF8.GetString(buffer, 0, resultLength);
}
// If the buffer was too small, loop around again and try with a larger buffer.
// Otherwise, bail.
if (resultLength == 0 || Interop.Sys.GetLastError() != Interop.Error.ENAMETOOLONG)
{
break;
}
}
// Could not get a path
return null;
}
// ----------------------------------
// ---- Unix PAL layer ends here ----
// ----------------------------------
/// <summary>Computes a time based on a number of ticks since boot.</summary>
/// <param name="ticksAfterBoot">The number of ticks since boot.</param>
/// <returns>The converted time.</returns>
internal static DateTime BootTimeToDateTime(ulong ticksAfterBoot)
{
// Read procfs to determine the system's uptime, aka how long ago it booted
string uptimeStr = File.ReadAllText(Interop.procfs.ProcUptimeFilePath, Encoding.UTF8);
int spacePos = uptimeStr.IndexOf(' ');
double uptime;
if (spacePos < 1 || !double.TryParse(uptimeStr.Substring(0, spacePos), out uptime))
{
throw new Win32Exception();
}
// Use the uptime and the current time to determine the absolute boot time
DateTime bootTime = DateTime.UtcNow - TimeSpan.FromSeconds(uptime);
// And use that to determine the absolute time for ticksStartedAfterBoot
DateTime dt = bootTime + TicksToTimeSpan(ticksAfterBoot);
// The return value is expected to be in the local time zone.
// It is converted here (rather than starting with DateTime.Now) to avoid DST issues.
return dt.ToLocalTime();
}
/// <summary>Reads the stats information for this process from the procfs file system.</summary>
private Interop.procfs.ParsedStat GetStat()
{
EnsureState(State.HaveId);
return Interop.procfs.ReadStatFile(_processId);
}
}
}
| |
using AjaxControlToolkit.Design;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Web.Script.Serialization;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace AjaxControlToolkit {
/// <summary>
/// AutoComplete extends any ASP.NET TextBox control. It associates that control with a
/// popup panel to display words that begin with the prefix that is entered into the text box.
/// </summary>
[Designer(typeof(AutoCompleteExtenderDesigner))]
[ClientScriptResource("Sys.Extended.UI.AutoCompleteBehavior", Constants.AutoCompleteName)]
[RequiredScript(typeof(CommonToolkitScripts))]
[RequiredScript(typeof(PopupExtender))]
[RequiredScript(typeof(TimerScript))]
[RequiredScript(typeof(AnimationExtender))]
[TargetControlType(typeof(TextBox))]
[ToolboxBitmap(typeof(ToolboxIcons.Accessor), Constants.AutoCompleteName + Constants.IconPostfix)]
public class AutoCompleteExtender : AnimationExtenderControlBase {
/// <summary>
/// Minimum length of text before the webservice provides suggestions.
/// The default is 3
/// </summary>
[DefaultValue(3)]
[ExtenderControlProperty]
[ClientPropertyName("minimumPrefixLength")]
public virtual int MinimumPrefixLength {
get { return GetPropertyValue("MinimumPrefixLength", 3); }
set { SetPropertyValue("MinimumPrefixLength", value); }
}
/// <summary>
/// Time in milliseconds when the timer will kick in to get suggestions using the web service.
/// The default is 1000
/// </summary>
[DefaultValue(1000)]
[ExtenderControlProperty]
[ClientPropertyName("completionInterval")]
public virtual int CompletionInterval {
get { return GetPropertyValue("CompletionInterval", 1000); }
set { SetPropertyValue("CompletionInterval", value); }
}
/// <summary>
/// A number of suggestions to be provided.
/// The default is 10
/// </summary>
[DefaultValue(10)]
[ExtenderControlProperty]
[ClientPropertyName("completionSetCount")]
public virtual int CompletionSetCount {
get { return GetPropertyValue("CompletionSetCount", 10); }
set { SetPropertyValue("CompletionSetCount", value); }
}
/// <summary>
/// ID of an element that will serve as the completion list.
/// </summary>
/// <remarks>
/// Deprecated. Use the default flyout and style that using the CssClass properties.
/// </remarks>
[DefaultValue("")]
[ExtenderControlProperty]
[ClientPropertyName("completionListElementID")]
[IDReferenceProperty(typeof(WebControl))]
[Obsolete("Instead of passing in CompletionListElementID, use the default flyout and style that using the CssClass properties.")]
[Browsable(false)]
[EditorBrowsable(EditorBrowsableState.Never)]
public virtual string CompletionListElementID {
get { return GetPropertyValue("CompletionListElementID", String.Empty); }
set { SetPropertyValue("CompletionListElementID", value); }
}
/// <summary>
/// The web service method to be called
/// </summary>
[DefaultValue("")]
[RequiredProperty]
[ExtenderControlProperty]
[ClientPropertyName("serviceMethod")]
public virtual string ServiceMethod {
get { return GetPropertyValue("ServiceMethod", String.Empty); }
set { SetPropertyValue("ServiceMethod", value); }
}
/// <summary>
/// The path to the web service that the extender will pull the
/// word/sentence completions from. If this is not provided, the
/// service method should be a page method.
/// </summary>
[UrlProperty]
[ExtenderControlProperty]
[TypeConverter(typeof(ServicePathConverter))]
[ClientPropertyName("servicePath")]
public virtual string ServicePath {
get { return GetPropertyValue("ServicePath", String.Empty); }
set { SetPropertyValue("ServicePath", value); }
}
/// <summary>
/// User/page specific context provided to an optional overload of the web method described by ServiceMethod/ServicePath.
/// If the context key is used, it should have the same signature with an additional parameter named contextKey of a string type.
/// </summary>
[ExtenderControlProperty]
[ClientPropertyName("contextKey")]
[DefaultValue(null)]
public string ContextKey {
get { return GetPropertyValue<string>("ContextKey", null); }
set {
SetPropertyValue<string>("ContextKey", value);
UseContextKey = true;
}
}
/// <summary>
/// Whether or not the ContextKey property should be used.
/// This will be automatically enabled if the ContextKey property is ever set (on either the client or the server).
/// If the context key is used, it should have the same signature with an additional parameter named contextKey of a string type.
/// </summary>
[ExtenderControlProperty]
[ClientPropertyName("useContextKey")]
[DefaultValue(false)]
public bool UseContextKey {
get { return GetPropertyValue<bool>("UseContextKey", false); }
set { SetPropertyValue<bool>("UseContextKey", value); }
}
/// <summary>
/// A CSS class that will be used to style the completion list flyout.
/// </summary>
[DefaultValue("")]
[ExtenderControlProperty]
[ClientPropertyName("completionListCssClass")]
public string CompletionListCssClass {
get { return GetPropertyValue("CompletionListCssClass", String.Empty); }
set { SetPropertyValue("CompletionListCssClass", value); }
}
/// <summary>
/// A CSS class that will be used to style an item in the autocomplete list.
/// </summary>
[DefaultValue("")]
[ExtenderControlProperty]
[ClientPropertyName("completionListItemCssClass")]
public string CompletionListItemCssClass {
get { return GetPropertyValue("CompletionListItemCssClass", String.Empty); }
set { SetPropertyValue("CompletionListItemCssClass", value); }
}
/// <summary>
/// A CSS class that will be used to style a highlighted item in the autocomplete list.
/// </summary>
[DefaultValue("")]
[ExtenderControlProperty]
[ClientPropertyName("highlightedItemCssClass")]
public string CompletionListHighlightedItemCssClass {
get { return GetPropertyValue("CompletionListHighlightedItemCssClass", String.Empty); }
set { SetPropertyValue("CompletionListHighlightedItemCssClass", value); }
}
/// <summary>
/// A flag to denote whether client-side caching is enabled.
/// The default is true.
/// </summary>
[DefaultValue(true)]
[ExtenderControlProperty]
[ClientPropertyName("enableCaching")]
public virtual bool EnableCaching {
get { return GetPropertyValue("EnableCaching", true); }
set { SetPropertyValue("EnableCaching", value); }
}
/// <summary>
/// The character(s) used to separate words for autocomplete
/// </summary>
[ExtenderControlProperty]
[ClientPropertyName("delimiterCharacters")]
public virtual string DelimiterCharacters {
get { return GetPropertyValue("DelimiterCharacters", String.Empty); }
set { SetPropertyValue("DelimiterCharacters", value); }
}
/// <summary>
/// Determines if the first row of the Search Results is selected by default.
/// The default is false.
/// </summary>
[DefaultValue(false)]
[ExtenderControlProperty]
[ClientPropertyName("firstRowSelected")]
public virtual bool FirstRowSelected {
get { return GetPropertyValue("FirstRowSelected", false); }
set { SetPropertyValue("FirstRowSelected", value); }
}
/// <summary>
/// If delimiter characters are specified and ShowOnlyCurrentWordInCompletionListItem is set to true,
/// then the completion list displays suggestions just for the current word,
/// otherwise, it displays the whole string that will show up in the TextBox
/// if that item is selected, which is the current default.
/// The default is false.
/// </summary>
[ExtenderControlProperty]
[ClientPropertyName("showOnlyCurrentWordInCompletionListItem")]
[DefaultValue(false)]
public bool ShowOnlyCurrentWordInCompletionListItem {
get { return GetPropertyValue<bool>("ShowOnlyCurrentWordInCompletionListItem", false); }
set { SetPropertyValue<bool>("ShowOnlyCurrentWordInCompletionListItem", value); }
}
/// <summary>
/// OnShow animation
/// </summary>
[ExtenderControlProperty]
[ClientPropertyName("onShow")]
[Browsable(false)]
[DefaultValue(null)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public Animation OnShow {
get { return GetAnimation(ref _onShow, "OnShow"); }
set { SetAnimation(ref _onShow, "OnShow", value); }
}
Animation _onShow;
/// <summary>
/// OnHide animation
/// </summary>
[ExtenderControlProperty]
[ClientPropertyName("onHide")]
[Browsable(false)]
[DefaultValue(null)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public Animation OnHide {
get { return GetAnimation(ref _onHide, "OnHide"); }
set { SetAnimation(ref _onHide, "OnHide", value); }
}
Animation _onHide;
/// <summary>
/// A handler attached to the client-side populating event
/// </summary>
[DefaultValue("")]
[ExtenderControlEvent]
[ClientPropertyName("populating")]
public string OnClientPopulating {
get { return GetPropertyValue("OnClientPopulating", String.Empty); }
set { SetPropertyValue("OnClientPopulating", value); }
}
/// <summary>
/// A handler attached to the client-side populated event
/// </summary>
[DefaultValue("")]
[ExtenderControlEvent]
[ClientPropertyName("populated")]
public string OnClientPopulated {
get { return GetPropertyValue("OnClientPopulated", String.Empty); }
set { SetPropertyValue("OnClientPopulated", value); }
}
/// <summary>
/// A handler attached to the client-side showing event
/// </summary>
[DefaultValue("")]
[ExtenderControlEvent]
[ClientPropertyName("showing")]
public string OnClientShowing {
get { return GetPropertyValue("OnClientShowing", String.Empty); }
set { SetPropertyValue("OnClientShowing", value); }
}
/// <summary>
/// A handler attached to the client-side shown event
/// </summary>
[DefaultValue("")]
[ExtenderControlEvent]
[ClientPropertyName("shown")]
public string OnClientShown {
get { return GetPropertyValue("OnClientShown", String.Empty); }
set { SetPropertyValue("OnClientShown", value); }
}
/// <summary>
/// A handler attached to the client-side hiding event
/// </summary>
[DefaultValue("")]
[ExtenderControlEvent]
[ClientPropertyName("hiding")]
public string OnClientHiding {
get { return GetPropertyValue("OnClientHiding", String.Empty); }
set { SetPropertyValue("OnClientHiding", value); }
}
/// <summary>
/// A handler attached to the client-side hidden event
/// </summary>
[DefaultValue("")]
[ExtenderControlEvent]
[ClientPropertyName("hidden")]
public string OnClientHidden {
get { return GetPropertyValue("OnClientHidden", String.Empty); }
set { SetPropertyValue("OnClientHidden", value); }
}
/// <summary>
/// A handler attached to the client-side itemSelected event
/// </summary>
[DefaultValue("")]
[ExtenderControlEvent]
[ClientPropertyName("itemSelected")]
public string OnClientItemSelected {
get { return GetPropertyValue("OnClientItemSelected", String.Empty); }
set { SetPropertyValue("OnClientItemSelected", value); }
}
/// <summary>
/// A handler attached to the client-side itemOver event
/// </summary>
[DefaultValue("")]
[ExtenderControlEvent]
[ClientPropertyName("itemOver")]
public string OnClientItemOver {
get { return GetPropertyValue("OnClientItemOver", String.Empty); }
set { SetPropertyValue("OnClientItemOver", value); }
}
/// <summary>
/// A handler attached to the client-side itemOut event
/// </summary>
[DefaultValue("")]
[ExtenderControlEvent]
[ClientPropertyName("itemOut")]
public string OnClientItemOut {
get { return GetPropertyValue("OnClientItemOut", String.Empty); }
set { SetPropertyValue("OnClientItemOut", value); }
}
// Convert server IDs into ClientIDs for animations
protected override void OnPreRender(EventArgs e) {
base.OnPreRender(e);
ResolveControlIDs(_onShow);
ResolveControlIDs(_onHide);
}
/// <summary>
/// Creates a serialized JSON object representing a text/value pair that can
/// be returned by the webservice
/// </summary>
/// <param name="text" type="String">Text part</param>
/// <param name="value" type="String">Value part</param>
/// <returns>Serialized JSON</returns>
public static string CreateAutoCompleteItem(string text, string value) {
return new JavaScriptSerializer().Serialize(new Pair(text, value));
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Text;
namespace Netco.Logging
{
/// <summary>
/// Sends all log messages to the console.
/// </summary>
internal sealed class ConsoleLogger : ILogger
{
private readonly string _name;
/// <summary>
/// Initializes a new instance of the <see cref="ConsoleLogger"/> class.
/// </summary>
/// <param name="name">The logger name.</param>
public ConsoleLogger( string name )
{
this._name = name;
}
/// <summary>
/// Gets or sets a value indicating whether to separate log entries.
/// </summary>
/// <value><c>true</c> if separate log entries with new line; otherwise, <c>false</c>.</value>
/// <remarks>When entries are separated, they are easier to read, but take up more space.</remarks>
public bool SeparateLogEntries { get; set; }
/// <summary>
/// Logs the specified message.
/// </summary>
/// <param name="messages">All message to log.</param>
private void LM( params string[] messages )
{
var sb = new StringBuilder();
for( var i = 0; i < messages.Length; i++ )
{
sb.AppendLine( messages[ i ] );
if( i < messages.Length - 1 )
sb.Append( "\t" );
}
if( this.SeparateLogEntries )
sb.AppendLine();
Console.Write( "{0} - {1}", this._name, sb );
}
public void Trace( string message )
{
this.LM( message );
}
public void Trace( Exception exception, string message )
{
this.LM( message, exception.Message, exception.StackTrace );
}
public void Trace( string messageWithFormatting, params object[] args )
{
this.LM( string.Format( messageWithFormatting, args ) );
}
public void Trace( Exception exception, string messageWithFormatting, params object[] args )
{
this.LM( string.Format( messageWithFormatting, args ), exception.Message, exception.StackTrace );
}
public void Debug( string message )
{
this.LM( message );
}
public void Debug( Exception exception, string message )
{
this.LM( message, exception.Message, exception.StackTrace );
}
public void Debug( string format, params object[] args )
{
this.LM( string.Format( format, args ) );
}
public void Debug( Exception exception, string format, params object[] args )
{
this.LM( string.Format( format, args ), exception.Message, exception.StackTrace );
}
public void Info( string message )
{
this.LM( message );
}
public void Info( Exception exception, string message )
{
this.LM( message, exception.Message, exception.StackTrace );
}
public void Info( string format, params object[] args )
{
this.LM( string.Format( format, args ) );
}
public void Info( Exception exception, string format, params object[] args )
{
this.LM( string.Format( format, args ), exception.Message, exception.StackTrace );
}
public void Warn( string message )
{
this.LM( message );
}
public void Warn( Exception exception, string message )
{
this.LM( message, exception.Message, exception.StackTrace );
}
public void Warn( string format, params object[] args )
{
this.LM( string.Format( format, args ) );
}
public void Warn( Exception exception, string format, params object[] args )
{
this.LM( string.Format( format, args ), exception.Message, exception.StackTrace );
}
public void Error( string message )
{
this.LM( message );
}
public void Error( Exception exception, string message )
{
this.LM( message, exception.Message, exception.StackTrace );
}
public void Error( string format, params object[] args )
{
this.LM( string.Format( format, args ) );
}
public void Error( Exception exception, string format, params object[] args )
{
this.LM( string.Format( format, args ), exception.Message, exception.StackTrace );
}
public void Fatal( string message )
{
this.LM( message );
}
public void Fatal( Exception exception, string message )
{
this.LM( message, exception.Message, exception.StackTrace );
}
public void Fatal( string format, params object[] args )
{
this.LM( string.Format( format, args ) );
}
public void Fatal( Exception exception, string format, params object[] args )
{
this.LM( string.Format( format, args ), exception.Message, exception.StackTrace );
}
}
/// <summary>
/// Returns console logger for the specified object type.
/// </summary>
public sealed class ConsoleLoggerFactory : ILoggerFactory
{
/// <summary>
/// Gets or sets a value indicating whether to separate log entries.
/// </summary>
/// <value><c>true</c> if separate log entries with new line; otherwise, <c>false</c>.</value>
/// <remarks>When entries are separated, they are easier to read, but take up more space.</remarks>
public bool SeparateLogEntries { get; set; }
private readonly Dictionary< Type, ILogger > _typeLoggers = new Dictionary< Type, ILogger >();
private readonly Dictionary< string, ILogger > _loggers = new Dictionary< string, ILogger >();
/// <summary>
/// Gets the logger to log message for the specified type.
/// </summary>
/// <param name="objectToLogType">Type of the object to log.</param>
/// <returns>
/// Logger to log messages for the specified type.
/// </returns>
public ILogger GetLogger( Type objectToLogType )
{
if( !this._typeLoggers.ContainsKey( objectToLogType ) )
{
this._typeLoggers[ objectToLogType ] = new ConsoleLogger( objectToLogType.Name )
{ SeparateLogEntries = this.SeparateLogEntries };
}
return this._typeLoggers[ objectToLogType ];
}
/// <summary>
/// Gets the logger to log message with the specified name.
/// </summary>
/// <param name="loggerName">The logger name.</param>
/// <returns>
/// Named logger to log messages.
/// </returns>
public ILogger GetLogger( string loggerName )
{
if( !this._loggers.ContainsKey( loggerName ) )
{
this._loggers[ loggerName ] = new ConsoleLogger( loggerName )
{ SeparateLogEntries = this.SeparateLogEntries };
}
return this._loggers[ loggerName ];
}
}
}
| |
// Copyright (c) Govert van Drimmelen. All rights reserved.
// Excel-DNA is licensed under the zlib license. See LICENSE.txt for details.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Reflection;
using System.Runtime.InteropServices;
using ExcelDna.ComInterop;
using ExcelDna.Logging;
namespace ExcelDna.Integration
{
// Loads the managed assembly, finds all the methods to be exported to Excel
// and build the method information.
// DOCUMENT: There is a lot of magic here, and many arbitrary decisions about what to register, and how.
internal class AssemblyLoader
{
// We consolidate the TraceSources for both ExcelDna.Integration and ExcelDna.Loader under the Excel.Integration name
// (since it is the public contract for ExcelDna).
// For the first version we don't make separate TraceSources for each class, though in future we might specialize under
// the ExcelDna.Integration namespace, so listening to ExcelDna.Integration* will be the forward-compatible pattern.
// Consolidated processing so we only have a single pass through the types.
// CONSIDER: This is pretty ugly right now (both the flow and the names.)
// Try some fancy visitor pattern?
public static void ProcessAssemblies(
List<ExportedAssembly> assemblies,
List<MethodInfo> methods,
List<ExcelAddInInfo> addIns,
List<Type> rtdServerTypes,
List<ExcelComClassType> comClassTypes)
{
List<AssemblyLoaderExcelServer.ExcelServerInfo> excelServerInfos = new List<AssemblyLoaderExcelServer.ExcelServerInfo>();
bool loadRibbons = (ExcelDnaUtil.ExcelVersion >= 12.0);
foreach (ExportedAssembly assembly in assemblies)
{
Logger.Initialization.Verbose("Processing assembly {0}. ExplicitExports {1}, ExplicitRegistration {2}, ComServer {3}, IsDynamic {4}",
assembly.Assembly.FullName, assembly.ExplicitExports, assembly.ExplicitRegistration, assembly.ComServer, assembly.IsDynamic);
// Patch contributed by y_i on CodePlex:
// http://stackoverflow.com/questions/11915389/assembly-gettypes-throwing-an-exception
Type[] types;
try
{
// NOTE: The fact that NonPublic types are returned here, and processed as-if they were public
// was a mistake. But it would be a serious breaking change to go back, so we'll leave it as is.
types = assembly.Assembly.GetTypes();
}
catch (ReflectionTypeLoadException e)
{
// From MSDN:
// [...]contains the array of classes (Types property) that were defined in the module and were loaded.
// The array can contain some null values.
types = e.Types;
}
bool explicitExports = assembly.ExplicitExports;
bool explicitRegistration = assembly.ExplicitRegistration;
foreach (Type type in types)
{
if (type == null) continue; // We might get nulls from ReflectionTypeLoadException above
Logger.Initialization.Verbose("Processing type {0}", type.FullName);
try
{
object[] attribs = type.GetCustomAttributes(false);
bool isRtdServer;
if (!explicitRegistration)
{
GetExcelMethods(type, explicitExports, methods);
}
AssemblyLoaderExcelServer.GetExcelServerInfos(type, attribs, excelServerInfos);
GetExcelAddIns(assembly, type, loadRibbons, addIns);
GetRtdServerTypes(type, rtdServerTypes, out isRtdServer);
GetComClassTypes(assembly, type, attribs, isRtdServer, comClassTypes);
}
catch (Exception e)
{
Logger.Initialization.Warn("Type {0} could not be processed. Error: {1}", type.FullName, e.ToString());
}
}
}
// Sigh. Excel server (service?) stuff is still ugly - but no real reason to remove it yet.
AssemblyLoaderExcelServer.GetExcelServerMethods(excelServerInfos, methods);
}
static void GetExcelMethods(Type t, bool explicitExports, List<MethodInfo> excelMethods)
{
// DOCUMENT: Exclude if not a class, not public, /*abstract,*/ an array,
// open generic type or in "My" namespace.
// Some basic checks -- what else?
// TODO: Sort out exactly which types to export.
if (!t.IsClass || !t.IsPublic ||
/*t.IsAbstract ||*/ t.IsArray ||
(t.IsGenericType && t.ContainsGenericParameters) ||
t.Namespace == "My")
{
// Ignored cases
Logger.Initialization.Info("Type ignored: {0}", t.FullName);
return;
}
MethodInfo[] mis = t.GetMethods(BindingFlags.Public | BindingFlags.Static);
// Filter list first - LINQ would be nice here :-)
foreach (MethodInfo mi in mis)
{
if (IsMethodSupported(mi, explicitExports))
excelMethods.Add(mi);
}
}
static bool IsMethodSupported(MethodInfo mi, bool explicitExports)
{
var isSupported = true;
// Skip generic methods - these may appear even though we have skipped generic types,
// e.g. in F# --standalone assemblies
if (mi.IsAbstract || mi.IsGenericMethod)
{
isSupported = false;
}
// if explicitexports - check that this method is marked
else if (explicitExports && !IsMethodMarkedForExport(mi))
{
isSupported = false;
}
else if (!IsParameterTypeSupported(mi.ReturnType))
{
isSupported = false;
}
else
{
foreach (ParameterInfo pi in mi.GetParameters())
{
if (!IsParameterTypeSupported(pi.ParameterType))
isSupported = false;
}
}
// We want to log methods that are marked for export, but have unsupported types.
if (!isSupported && IsMethodMarkedForExport(mi))
{
Logger.Initialization.Error("Method not registered - unsupported signature, abstract or generic: '{0}.{1}'", mi.DeclaringType.Name, mi.Name);
}
else if (!isSupported)
{
// CONSIDER: More detailed logging
Logger.Initialization.Info("Method not registered - unsupported signature, abstract or generic: '{0}.{1}'", mi.DeclaringType.Name, mi.Name);
}
return isSupported;
}
// CAUTION: This check needs to match the usage in ExcelDna.Loader.XlMethodInfo.SetAttributeInfo()
static bool IsMethodMarkedForExport(MethodInfo mi)
{
object[] atts = mi.GetCustomAttributes(false);
foreach (object att in atts)
{
Type attType = att.GetType();
if (TypeHasAncestorWithFullName(attType, "ExcelDna.Integration.ExcelFunctionAttribute") ||
TypeHasAncestorWithFullName(attType, "ExcelDna.Integration.ExcelCommandAttribute" ) )
{
return true;
}
}
return false;
}
static readonly List<Type> _supportedParameterTypes = new List<Type>
{
typeof(double),
typeof(string),
typeof(DateTime),
typeof(double[]),
typeof(double[,]),
typeof(object),
typeof(object[]),
typeof(object[,]),
typeof(bool),
typeof(int),
typeof(short),
typeof(ushort),
typeof(decimal),
typeof(long),
typeof(void)
};
static bool IsParameterTypeSupported(Type type)
{
return _supportedParameterTypes.Contains(type) ||
(ExcelDnaUtil.ExcelVersion >= 14.0 && type == typeof(ExcelAsyncHandle)); // Only Excel 2010+
}
// Some support for creating add-ins that are notified of open and close
// this allows the add-in to add menus, toolbar buttons etc.
// Also records whether this class should be loaded as a ComAddIn (for the Ribbon).
public class ExcelAddInInfo
{
public MethodInfo AutoOpenMethod;
public MethodInfo AutoCloseMethod;
public bool IsCustomUI;
public object Instance;
public DnaLibrary ParentDnaLibrary;
}
static public void GetExcelAddIns(ExportedAssembly assembly, Type t, bool loadRibbons, List<ExcelAddInInfo> addIns)
{
// NOTE: We probably should have restricted this to public types, but didn't. Now it's too late.
// So internal classes that implement IExcelAddIn are also loaded.
try
{
Type addInType = t.GetInterface("ExcelDna.Integration.IExcelAddIn");
bool isRibbon = IsRibbonType(t);
if (addInType != null || (isRibbon && loadRibbons) )
{
ExcelAddInInfo info = new ExcelAddInInfo();
if (addInType != null)
{
info.AutoOpenMethod = addInType.GetMethod("AutoOpen");
info.AutoCloseMethod = addInType.GetMethod("AutoClose");
}
info.IsCustomUI = isRibbon;
// TODO: Consider how to handle exception from constructors here.
info.Instance = Activator.CreateInstance(t);
info.ParentDnaLibrary = assembly.ParentDnaLibrary;
addIns.Add(info);
Logger.Registration.Verbose("GetExcelAddIns - Created add-in object of type: {0}", t.FullName);
}
}
catch (Exception e) // I think only CreateInstance can throw an exception here...
{
Logger.Initialization.Warn("GetExcelAddIns CreateInstance problem for type: {0} - exception: {1}", t.FullName, e);
}
}
// DOCUMENT: We register types that implement an interface with the IRtdServer Guid. These include
// "Microsoft.Office.Interop.Excel.IRtdServer" and
// "ExcelDna.Integration.Rtd.IRtdServer".
// The RTD server can be accessed using the ExcelDnaUtil.RTD function under the
// FullName of the type, or under the ProgId defined in an attribute, if there is one.
static public void GetRtdServerTypes(Type t, List<Type> rtdServerTypes, out bool isRtdServer)
{
isRtdServer = false;
Type[] itfs = t.GetInterfaces();
foreach (Type itf in itfs)
{
if (itf.GUID == ComAPI.guidIRtdServer)
{
//object[] attrs = t.GetCustomAttributes(typeof(ProgIdAttribute), false);
//if (attrs.Length >= 1)
//{
// ProgIdAttribute progIdAtt = (ProgIdAttribute)attrs[0];
// rtdServerTypes[progIdAtt.Value] = t;
//}
//rtdServerTypes[t.FullName] = t;
rtdServerTypes.Add(t);
isRtdServer = true;
Logger.Initialization.Verbose("GetRtdServerTypes - Found RTD server type: {0}", t.FullName);
}
}
}
// DOCUMENT: We register ComVisible types that
// (implement IRtdServer OR are in ExternalLibraries marked ComServer='true'
static public void GetComClassTypes(ExportedAssembly assembly, Type type, object[] attributes, bool isRtdServer, List<ExcelComClassType> comClassTypes)
{
if (!Marshal.IsTypeVisibleFromCom(type))
{
return;
}
if (isRtdServer || assembly.ComServer)
{
string progId;
Guid clsId;
// Check for public default constructor
if (type.GetConstructor(BindingFlags.Public | BindingFlags.Instance, null, Type.EmptyTypes, null) == null)
{
// No use to us here - won't be able to construct.
return;
}
if (assembly.IsDynamic)
{
// Check that we have an explicit Guid attribute
object[] attrs = type.GetCustomAttributes(typeof(GuidAttribute), false);
if (attrs.Length == 0)
{
// No Guid attribute - skip this type.
return;
}
else
{
GuidAttribute guidAtt = (GuidAttribute)attrs[0];
clsId = new Guid(guidAtt.Value);
}
}
else
{
clsId = Marshal.GenerateGuidForType(type);
}
progId = Marshal.GenerateProgIdForType(type);
ExcelComClassType comClassType = new ExcelComClassType
{
Type = type,
ClsId = clsId,
ProgId = progId,
IsRtdServer = isRtdServer,
TypeLibPath = assembly.TypeLibPath
};
comClassTypes.Add(comClassType);
Logger.Initialization.Verbose("GetComClassTypes - Found type {0}, with ProgId {1}", type.FullName, progId);
}
}
static bool IsRibbonType(Type type)
{
// Ribbon type is one that has ExcelRibbon as an ancestor (but is not ExcelRibbon itself), is not abstract, and it's parent is not a ribbon type
// We are trying to prevent loading multiple copies of a ribbon along the inheritance hierarchy,
// while still allowing some abstraction of Ribbon handling classes.
// Current design will load only the least-derived concrete class.
bool isRibbon =
type != null &&
TypeHasAncestorWithFullName(type.BaseType, "ExcelDna.Integration.CustomUI.ExcelRibbon") &&
!type.IsAbstract &&
!IsRibbonType(type.BaseType);
return isRibbon;
}
private static bool TypeHasAncestorWithFullName(Type type, string fullName)
{
if (type == null) return false;
if (type.FullName == fullName) return true;
return TypeHasAncestorWithFullName(type.BaseType, fullName);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using Baseline;
using Weasel.Postgresql;
using Marten.Testing.Events;
using Marten.Testing.Events.Projections;
using Marten.Testing.Harness;
using NpgsqlTypes;
using StoryTeller;
using StoryTeller.Grammars.Tables;
using Weasel.Core;
namespace Marten.Storyteller.Fixtures.EventStore
{
public class EventStoreFixture: Fixture
{
private readonly LightweightCache<string, Guid> _streams = new LightweightCache<string, Guid>();
private IDocumentStore _store;
private Guid _lastStream;
private long _version;
private DateTime _time;
private string _mode;
public override void SetUp()
{
_streams.ClearAll();
_store = DocumentStore.For(opts =>
{
opts.Connection(ConnectionSource.ConnectionString);
opts.AutoCreateSchemaObjects = AutoCreate.All;
});
Context.State.Store(_store);
}
[FormatAs("For a new 'Quest' named {name} that started on {date}")]
public void ForNewQuestStream(string name, DateTime date)
{
var started = new QuestStarted { Name = name };
using (var session = _store.LightweightSession())
{
_lastStream = session.Events.StartStream<Quest>(started).Id;
_streams[name] = _lastStream;
session.SaveChanges();
rewriteEventTime(date, session, _lastStream);
}
}
[FormatAs("The version of quest {name} should be {version}")]
public long TheQuestVersionShouldBe(string name)
{
using (var session = _store.LightweightSession())
{
var streamId = _streams[name];
var state = session.Events.FetchStreamState(streamId);
return state.Version;
}
}
[ExposeAsTable("If the Event Timestamps were")]
public void OverwriteTimestamps(long version, DateTime time)
{
var store = Context.State.Retrieve<IDocumentStore>();
using (var session = store.OpenSession())
{
var cmd = session.Connection.CreateCommand()
.Sql("update mt_events set timestamp = :time where stream_id = :stream and version = :version")
.With("stream", _lastStream)
.With("time", time.ToUniversalTime(), DbType.DateTime)
.With("version", version)
;
cmd.ExecuteNonQuery();
session.SaveChanges();
}
}
public IGrammar AllTheCapturedEventsShouldBe()
{
return VerifyStringList(allEvents)
.Titled("When fetching the entire event stream, the captured events returned should be")
.Ordered();
}
private IEnumerable<string> allEvents()
{
using (var session = _store.LightweightSession())
{
return session.Events.FetchStream(_lastStream).Select(x => x.Data.ToString()).ToArray();
}
}
[Hidden, FormatAs("For version # {version}")]
public void Version(long version)
{
_version = version;
}
[Hidden]
public IGrammar EventsAtTimeShouldBe()
{
return VerifyStringList(() => allEvents(_time))
.Titled("The captured events for this stream and specified time should be")
.Ordered();
}
public IGrammar FetchEventsByTimestamp()
{
return Paragraph("Fetch the events by time", _ =>
{
_ += this["Time"];
_ += this["FetchMode"];
_ += this["EventsAtTimeShouldBe"];
});
}
private IEnumerable<string> allEvents(DateTime time)
{
using (var session = _store.LightweightSession())
{
switch (_mode)
{
case "Synchronously":
return session.Events.FetchStream(_lastStream, timestamp: time.ToUniversalTime()).Select(x => x.Data.ToString()).ToArray();
case "Asynchronously":
return session.Events.FetchStreamAsync(_lastStream, timestamp: time.ToUniversalTime()).GetAwaiter().GetResult().Select(x => x.Data.ToString()).ToArray();
case "In a batch":
throw new NotSupportedException("Not ready yet");
}
throw new NotSupportedException();
}
}
[FormatAs("Fetching {mode}")]
public void FetchMode([SelectionValues("Synchronously", "Asynchronously", "In a batch"), Default("Synchronously")]string mode)
{
_mode = mode;
}
[Hidden, FormatAs("For time # {time}")]
public void Time(DateTime time)
{
_time = time;
}
[Hidden]
public IGrammar EventsAtVersionShouldBe()
{
return VerifyStringList(() => allEvents(_version))
.Titled("The captured events for this stream and specified version should be")
.Ordered();
}
public IGrammar FetchEventsByVersion()
{
return Paragraph("Fetch the events by version", _ =>
{
_ += this["FetchMode"];
_ += this["Version"];
_ += this["EventsAtVersionShouldBe"];
});
}
private IEnumerable<string> allEvents(long version)
{
using (var session = _store.LightweightSession())
{
switch (_mode)
{
case "Synchronously":
return session.Events.FetchStream(_lastStream, version).Select(x => x.Data.ToString()).ToArray();
case "Asynchronously":
return session.Events.FetchStreamAsync(_lastStream, version).GetAwaiter().GetResult().Select(x => x.Data.ToString()).ToArray();
case "In a batch":
throw new NotSupportedException("Not ready yet");
}
}
using (var session = _store.LightweightSession())
{
return session.Events.FetchStream(_lastStream, version).Select(x => x.Data.ToString()).ToArray();
}
}
public IGrammar HasAdditionalEvents()
{
return Embed<QuestEventFixture>("With events").Before(c => c.State.Store("streamId", _lastStream));
}
private static void rewriteEventTime(DateTime date, IDocumentSession session, Guid id)
{
// TODO -- let's rethink this one later
session.Connection.CreateCommand().Sql("update mt_events set timestamp = :date where id = :id")
.With("date", date.ToUniversalTime(), DbType.DateTime)
.With("id", id)
.ExecuteNonQuery();
session.SaveChanges();
}
[FormatAs("Live aggregating to QuestParty should be {returnValue}")]
public string LiveAggregationToQueryPartyShouldBe()
{
using (var session = _store.OpenSession())
{
switch (_mode)
{
case "Synchronously":
return session.Events.AggregateStream<QuestParty>(_lastStream).ToString();
case "Asynchronously":
return session.Events.AggregateStreamAsync<QuestParty>(_lastStream).GetAwaiter().GetResult().ToString();
}
throw new NotSupportedException();
}
}
[FormatAs("Live aggregating to QuestParty at time {timestamp} should be {returnValue}")]
public string LiveAggregationToQueryPartyByTimestampShouldBe(DateTime timestamp)
{
using (var session = _store.OpenSession())
{
switch (_mode)
{
case "Synchronously":
return session.Events.AggregateStream<QuestParty>(_lastStream, timestamp: timestamp.ToUniversalTime()).ToString();
case "Asynchronously":
return session.Events.AggregateStreamAsync<QuestParty>(_lastStream, timestamp: timestamp.ToUniversalTime()).GetAwaiter().GetResult().ToString();
}
throw new NotSupportedException();
}
}
[FormatAs("Live aggregating to QuestParty at version {version} should be {returnValue}")]
public string LiveAggregationToQueryPartyVersionShouldBe(long version)
{
using (var session = _store.OpenSession())
{
switch (_mode)
{
case "Synchronously":
return session.Events.AggregateStream<QuestParty>(_lastStream, version).ToString();
case "Asynchronously":
return session.Events.AggregateStreamAsync<QuestParty>(_lastStream, version).GetAwaiter().GetResult().ToString();
}
}
throw new Exception();
}
}
}
| |
#region License
/* The MIT License (MIT)
* Copyright (c) 2019 Michael Stum, http://www.Stum.de <opensource@stum.de>
*
* 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.
*/
#endregion
using System;
using System.Collections.Generic;
using System.Linq;
namespace mstum.utils
{
/// <summary>
/// The Minimum and Maximum value of something
/// </summary>
/// <typeparam name="T"></typeparam>
public class Extent<T>
{
public T Min { get; set; }
public T Max { get; set; }
public Extent()
{
}
public Extent(T min, T max)
{
Min = min;
Max = max;
}
}
public static class ExtentExtensionMethods
{
public static Extent<TResult> Extent<TSource, TResult>(this IEnumerable<TSource> source, Func<TSource, TResult> selector)
{
return Extent(source.Select(selector));
}
public static Extent<TSource> Extent<TSource>(this IEnumerable<TSource> source)
{
if (source == null) throw new ArgumentNullException(nameof(source));
var comparer = Comparer<TSource>.Default;
var minValue = default(TSource);
var maxValue = default(TSource);
if (minValue == null)
{
foreach (var x in source)
{
if (x != null && (maxValue == null || comparer.Compare(x, maxValue) > 0))
{
maxValue = x;
}
if (x != null && (minValue == null || comparer.Compare(x, minValue) < 0))
{
minValue = x;
}
}
return new Extent<TSource>(minValue, maxValue);
}
else
{
bool hasMinValue = false;
bool hasMaxValue = false;
foreach (var x in source)
{
if (hasMinValue)
{
if (comparer.Compare(x, minValue) < 0)
{
minValue = x;
}
}
else
{
minValue = x;
hasMinValue = true;
}
if (hasMaxValue)
{
if (comparer.Compare(x, maxValue) > 0)
{
maxValue = x;
}
}
else
{
maxValue = x;
hasMaxValue = true;
}
}
if (hasMinValue && hasMaxValue) return new Extent<TSource>(minValue, maxValue);
throw new InvalidOperationException("Sequence contains no elements");
}
}
// Non-Boxing Methods
public static Extent<int> Extent<TSource>(this IEnumerable<TSource> source, Func<TSource, int> selector)
{
return Extent(source.Select(selector));
}
public static Extent<int?> Extent<TSource>(this IEnumerable<TSource> source, Func<TSource, int?> selector)
{
return Extent(source.Select(selector));
}
public static Extent<long> Extent<TSource>(this IEnumerable<TSource> source, Func<TSource, long> selector)
{
return Extent(source.Select(selector));
}
public static Extent<long?> Extent<TSource>(this IEnumerable<TSource> source, Func<TSource, long?> selector)
{
return Extent(source.Select(selector));
}
public static Extent<float> Extent<TSource>(this IEnumerable<TSource> source, Func<TSource, float> selector)
{
return Extent(source.Select(selector));
}
public static Extent<float?> Extent<TSource>(this IEnumerable<TSource> source, Func<TSource, float?> selector)
{
return Extent(source.Select(selector));
}
public static Extent<double> Extent<TSource>(this IEnumerable<TSource> source, Func<TSource, double> selector)
{
return Extent(source.Select(selector));
}
public static Extent<double?> Extent<TSource>(this IEnumerable<TSource> source, Func<TSource, double?> selector)
{
return Extent(source.Select(selector));
}
public static Extent<decimal> Extent<TSource>(this IEnumerable<TSource> source, Func<TSource, decimal> selector)
{
return Extent(source.Select(selector));
}
public static Extent<decimal?> Extent<TSource>(this IEnumerable<TSource> source, Func<TSource, decimal?> selector)
{
return Extent(source.Select(selector));
}
public static Extent<DateTime> Extent<TSource>(this IEnumerable<TSource> source, Func<TSource, DateTime> selector)
{
return Extent(source.Select(selector));
}
public static Extent<DateTime?> Extent<TSource>(this IEnumerable<TSource> source, Func<TSource, DateTime?> selector)
{
return Extent(source.Select(selector));
}
public static Extent<TimeSpan> Extent<TSource>(this IEnumerable<TSource> source, Func<TSource, TimeSpan> selector)
{
return Extent(source.Select(selector));
}
public static Extent<TimeSpan?> Extent<TSource>(this IEnumerable<TSource> source, Func<TSource, TimeSpan?> selector)
{
return Extent(source.Select(selector));
}
public static Extent<int> Extent(this IEnumerable<int> source)
{
if (source == null) throw new ArgumentNullException(nameof(source));
int minValue = 0;
int maxValue = 0;
bool hasMinValue = false;
bool hasMaxValue = false;
foreach (var x in source)
{
if (hasMinValue)
{
if (x < minValue) minValue = x;
}
else
{
minValue = x;
hasMinValue = true;
}
if (hasMaxValue)
{
if (x > maxValue) maxValue = x;
}
else
{
maxValue = x;
hasMaxValue = true;
}
}
if (hasMinValue) return new Extent<int>(minValue, maxValue);
throw new InvalidOperationException("Sequence contains no elements");
}
public static Extent<int?> Extent(this IEnumerable<int?> source)
{
if (source == null) throw new ArgumentNullException(nameof(source));
int? minValue = null;
int? maxValue = null;
foreach (var x in source)
{
if (minValue == null || x < minValue)
{
minValue = x;
}
if (maxValue == null || x > maxValue)
{
maxValue = x;
}
}
return new Extent<int?>(minValue, maxValue);
}
public static Extent<long> Extent(this IEnumerable<long> source)
{
if (source == null) throw new ArgumentNullException(nameof(source));
long minValue = 0;
long maxValue = 0;
bool hasMinValue = false;
bool hasMaxValue = false;
foreach (var x in source)
{
if (hasMinValue)
{
if (x < minValue) minValue = x;
}
else
{
minValue = x;
hasMinValue = true;
}
if (hasMaxValue)
{
if (x > maxValue) maxValue = x;
}
else
{
maxValue = x;
hasMaxValue = true;
}
}
if (hasMinValue) return new Extent<long>(minValue, maxValue);
throw new InvalidOperationException("Sequence contains no elements");
}
public static Extent<long?> Extent(this IEnumerable<long?> source)
{
if (source == null) throw new ArgumentNullException(nameof(source));
long? minValue = null;
long? maxValue = null;
foreach (var x in source)
{
if (minValue == null || x < minValue)
{
minValue = x;
}
if (maxValue == null || x > maxValue)
{
maxValue = x;
}
}
return new Extent<long?>(minValue, maxValue);
}
public static Extent<float> Extent(this IEnumerable<float> source)
{
if (source == null) throw new ArgumentNullException(nameof(source));
float minValue = 0;
float maxValue = 0;
bool hasMinValue = false;
bool hasMaxValue = false;
foreach (var x in source)
{
// Normally NaN < anything is false, as is anything < NaN
// However, this leads to some irksome outcomes in Min and Max.
// If we use those semantics then > Min(NaN, 5.0) is NaN, but
// > Min(5.0, NaN) is 5.0! To fix this, we impose a total
// ordering where NaN is smaller and bigger than every value,
// including negative/positive infinity.
if (hasMinValue)
{
if (x < minValue || float.IsNaN(x)) minValue = x;
}
else
{
minValue = x;
hasMinValue = true;
}
if (hasMaxValue)
{
if (x > maxValue || float.IsNaN(x)) maxValue = x;
}
else
{
maxValue = x;
hasMaxValue = true;
}
}
if (hasMinValue) return new Extent<float>(minValue, maxValue);
throw new InvalidOperationException("Sequence contains no elements");
}
public static Extent<float?> Extent(this IEnumerable<float?> source)
{
if (source == null) throw new ArgumentNullException(nameof(source));
float? minValue = 0;
float? maxValue = 0;
foreach (var x in source)
{
if (x == null) continue;
if (minValue == null || x < minValue || float.IsNaN(x.Value))
{
minValue = x;
}
if (maxValue == null || x > maxValue || float.IsNaN(x.Value))
{
maxValue = x;
}
}
return new Extent<float?>(minValue, maxValue);
}
public static Extent<double> Extent(this IEnumerable<double> source)
{
if (source == null) throw new ArgumentNullException(nameof(source));
double minValue = 0;
double maxValue = 0;
bool hasMinValue = false;
bool hasMaxValue = false;
foreach (var x in source)
{
if (hasMinValue)
{
if (x < minValue || double.IsNaN(x)) minValue = x;
}
else
{
minValue = x;
hasMinValue = true;
}
if (hasMaxValue)
{
if (x > maxValue || double.IsNaN(x)) maxValue = x;
}
else
{
maxValue = x;
hasMaxValue = true;
}
}
if (hasMinValue) return new Extent<double>(minValue, maxValue);
throw new InvalidOperationException("Sequence contains no elements");
}
public static Extent<double?> Extent(this IEnumerable<double?> source)
{
if (source == null) throw new ArgumentNullException(nameof(source));
double? minValue = 0;
double? maxValue = 0;
foreach (var x in source)
{
if (x == null) continue;
if (minValue == null || x < minValue || double.IsNaN(x.Value))
{
minValue = x;
}
if (maxValue == null || x > maxValue || double.IsNaN(x.Value))
{
maxValue = x;
}
}
return new Extent<double?>(minValue, maxValue);
}
public static Extent<decimal> Extent(this IEnumerable<decimal> source)
{
if (source == null) throw new ArgumentNullException(nameof(source));
decimal minValue = 0;
decimal maxValue = 0;
bool hasMinValue = false;
bool hasMaxValue = false;
foreach (var x in source)
{
if (hasMinValue)
{
if (x < minValue) minValue = x;
}
else
{
minValue = x;
hasMinValue = true;
}
if (hasMaxValue)
{
if (x > maxValue) maxValue = x;
}
else
{
maxValue = x;
hasMaxValue = true;
}
}
if (hasMinValue) return new Extent<decimal>(minValue, maxValue);
throw new InvalidOperationException("Sequence contains no elements");
}
public static Extent<decimal?> Extent(this IEnumerable<decimal?> source)
{
if (source == null) throw new ArgumentNullException(nameof(source));
decimal? minValue = null;
decimal? maxValue = null;
foreach (var x in source)
{
if (minValue == null || x < minValue)
{
minValue = x;
}
if (maxValue == null || x > maxValue)
{
maxValue = x;
}
}
return new Extent<decimal?>(minValue, maxValue);
}
public static Extent<DateTime> Extent(this IEnumerable<DateTime> source)
{
if (source == null) throw new ArgumentNullException(nameof(source));
DateTime minValue = DateTime.MinValue;
DateTime maxValue = DateTime.MinValue;
bool hasMinValue = false;
bool hasMaxValue = false;
foreach (var x in source)
{
if (hasMinValue)
{
if (x < minValue) minValue = x;
}
else
{
minValue = x;
hasMinValue = true;
}
if (hasMaxValue)
{
if (x > maxValue) maxValue = x;
}
else
{
maxValue = x;
hasMaxValue = true;
}
}
if (hasMinValue) return new Extent<DateTime>(minValue, maxValue);
throw new InvalidOperationException("Sequence contains no elements");
}
public static Extent<DateTime?> Extent(this IEnumerable<DateTime?> source)
{
if (source == null) throw new ArgumentNullException(nameof(source));
DateTime? minValue = null;
DateTime? maxValue = null;
foreach (var x in source)
{
if (minValue == null || x < minValue)
{
minValue = x;
}
if (maxValue == null || x > maxValue)
{
maxValue = x;
}
}
return new Extent<DateTime?>(minValue, maxValue);
}
public static Extent<TimeSpan> Extent(this IEnumerable<TimeSpan> source)
{
if (source == null) throw new ArgumentNullException(nameof(source));
TimeSpan minValue = TimeSpan.Zero;
TimeSpan maxValue = TimeSpan.Zero;
bool hasMinValue = false;
bool hasMaxValue = false;
foreach (var x in source)
{
if (hasMinValue)
{
if (x < minValue) minValue = x;
}
else
{
minValue = x;
hasMinValue = true;
}
if (hasMaxValue)
{
if (x > maxValue) maxValue = x;
}
else
{
maxValue = x;
hasMaxValue = true;
}
}
if (hasMinValue) return new Extent<TimeSpan>(minValue, maxValue);
throw new InvalidOperationException("Sequence contains no elements");
}
public static Extent<TimeSpan?> Extent(this IEnumerable<TimeSpan?> source)
{
if (source == null) throw new ArgumentNullException(nameof(source));
TimeSpan? minValue = null;
TimeSpan? maxValue = null;
foreach (var x in source)
{
if (minValue == null || x < minValue)
{
minValue = x;
}
if (maxValue == null || x > maxValue)
{
maxValue = x;
}
}
return new Extent<TimeSpan?>(minValue, maxValue);
}
}
}
| |
//=============================================================================
// System : Sandcastle Help File Builder Plug-Ins
// File : AjaxDocConfigDlg.cs
// Author : Eric Woodruff (Eric@EWoodruff.us)
// Updated : 02/29/2008
// Note : Copyright 2007-2008, Eric Woodruff, All rights reserved
// Compiler: Microsoft Visual C#
//
// This file contains a form that is used to configure the settings for the
// AjaxDoc Builder plug-in.
//
// This code is published under the Microsoft Public License (Ms-PL). A copy
// of the license should be distributed with the code. It can also be found
// at the project website: http://SHFB.CodePlex.com. This notice, the
// author's name, and all copyright notices must remain intact in all
// applications, documentation, and source files.
//
// Version Date Who Comments
// ============================================================================
// 1.5.2.0 09/15/2007 EFW Created the code
//=============================================================================
using System;
using System.Collections;
using System.ComponentModel;
using System.Globalization;
using System.IO;
using System.Windows.Forms;
using System.Xml;
using System.Xml.XPath;
using SandcastleBuilder.Utils;
namespace SandcastleBuilder.PlugIns
{
/// <summary>
/// This form is used to configure the settings for the
/// <see cref="AjaxDocPlugIn"/>.
/// </summary>
internal partial class AjaxDocConfigDlg : Form
{
private XmlDocument config; // The configuration
/// <summary>
/// This is used to return the configuration information
/// </summary>
public string Configuration
{
get { return config.OuterXml; }
}
/// <summary>
/// Constructor
/// </summary>
/// <param name="currentConfig">The current XML configuration
/// XML fragment</param>
public AjaxDocConfigDlg(string currentConfig)
{
XPathNavigator navigator, root, node;
UserCredentials userCreds;
ProxyCredentials proxyCreds;
InitializeComponent();
lnkCodePlexSHFB.Links[0].LinkData = "http://SHFB.CodePlex.com";
lnkCodePlexAjaxDoc.Links[0].LinkData = "http://AjaxDoc.CodePlex.com";
// Load the current settings
config = new XmlDocument();
config.LoadXml(currentConfig);
navigator = config.CreateNavigator();
root = navigator.SelectSingleNode("configuration");
if(root.IsEmptyElement)
return;
node = root.SelectSingleNode("ajaxDoc");
if(node != null)
{
txtAjaxDocUrl.Text = node.GetAttribute("url", String.Empty);
txtProjectName.Text = node.GetAttribute("project", String.Empty);
chkRegenerateFiles.Checked = Convert.ToBoolean(
node.GetAttribute("regenerate", String.Empty),
CultureInfo.InvariantCulture);
}
userCreds = UserCredentials.FromXPathNavigator(root);
chkUseDefaultCredentials.Checked = userCreds.UseDefaultCredentials;
txtUserName.Text = userCreds.UserName;
txtPassword.Text = userCreds.Password;
proxyCreds = ProxyCredentials.FromXPathNavigator(root);
chkUseProxyServer.Checked = proxyCreds.UseProxyServer;
txtProxyServer.Text = (proxyCreds.ProxyServer == null) ? null :
proxyCreds.ProxyServer.OriginalString;
chkUseProxyDefCreds.Checked = proxyCreds.Credentials.UseDefaultCredentials;
txtProxyUserName.Text = proxyCreds.Credentials.UserName;
txtProxyPassword.Text = proxyCreds.Credentials.Password;
}
/// <summary>
/// Close without saving
/// </summary>
/// <param name="sender">The sender of the event</param>
/// <param name="e">The event arguments</param>
private void btnCancel_Click(object sender, EventArgs e)
{
this.Close();
}
/// <summary>
/// Go to the CodePlex home page of the Sandcastle Help File Builder
/// project.
/// </summary>
/// <param name="sender">The sender of the event</param>
/// <param name="e">The event arguments</param>
private void codePlex_LinkClicked(object sender,
LinkLabelLinkClickedEventArgs e)
{
try
{
System.Diagnostics.Process.Start((string)e.Link.LinkData);
}
catch(Exception ex)
{
System.Diagnostics.Debug.WriteLine(ex.ToString());
MessageBox.Show("Unable to launch link target. " +
"Reason: " + ex.Message, Constants.AppName,
MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
}
/// <summary>
/// Enable or disable the user name and password controls based on
/// the Default Credentials check state.
/// </summary>
/// <param name="sender">The sender of the event</param>
/// <param name="e">The event arguments</param>
private void chkUseDefaultCredentials_CheckedChanged(object sender,
EventArgs e)
{
txtUserName.Enabled = txtPassword.Enabled =
!chkUseDefaultCredentials.Checked;
}
/// <summary>
/// Enable or disable the proxy server settings based on the Use
/// Proxy Server check state.
/// </summary>
/// <param name="sender">The sender of the event</param>
/// <param name="e">The event arguments</param>
private void chkUseProxyServer_CheckedChanged(object sender, EventArgs e)
{
txtProxyServer.Enabled = chkUseProxyDefCreds.Enabled =
txtProxyUserName.Enabled = txtProxyPassword.Enabled =
chkUseProxyServer.Checked;
if(chkUseProxyServer.Checked)
chkUseProxyDefCreds_CheckedChanged(sender, e);
}
/// <summary>
/// Enable or disable the proxy user credentials based on the Proxy
/// Default Credentials check state.
/// </summary>
/// <param name="sender">The sender of the event</param>
/// <param name="e">The event arguments</param>
private void chkUseProxyDefCreds_CheckedChanged(object sender, EventArgs e)
{
if(chkUseProxyDefCreds.Enabled)
txtProxyUserName.Enabled = txtProxyPassword.Enabled =
!chkUseProxyDefCreds.Checked;
}
/// <summary>
/// Validate the configuration and save it
/// </summary>
/// <param name="sender">The sender of the event</param>
/// <param name="e">The event arguments</param>
private void btnOK_Click(object sender, EventArgs e)
{
XmlAttribute attr;
XmlNode root, node;
UserCredentials userCreds;
ProxyCredentials proxyCreds;
bool isValid = true;
Uri ajaxDoc = null, proxyServer = null;
txtAjaxDocUrl.Text = txtAjaxDocUrl.Text.Trim();
txtProjectName.Text = txtProjectName.Text.Trim();
txtUserName.Text = txtUserName.Text.Trim();
txtPassword.Text = txtPassword.Text.Trim();
txtProxyServer.Text = txtProxyServer.Text.Trim();
txtProxyUserName.Text = txtProxyUserName.Text.Trim();
txtProxyPassword.Text = txtProxyPassword.Text.Trim();
epErrors.Clear();
if(txtAjaxDocUrl.Text.Length == 0)
{
epErrors.SetError(txtAjaxDocUrl, "An AjaxDoc URL is required");
isValid = false;
}
else
if(!Uri.TryCreate(txtAjaxDocUrl.Text,
UriKind.RelativeOrAbsolute, out ajaxDoc))
{
epErrors.SetError(txtAjaxDocUrl, "The AjaxDoc URL does " +
"not appear to be valid");
isValid = false;
}
if(txtProjectName.Text.Length == 0)
{
epErrors.SetError(txtProjectName, "A project filename " +
"is required");
isValid = false;
}
if(!chkUseDefaultCredentials.Checked)
{
if(txtUserName.Text.Length == 0)
{
epErrors.SetError(txtUserName, "A user name is " +
"required if not using default credentials");
isValid = false;
}
if(txtPassword.Text.Length == 0)
{
epErrors.SetError(txtPassword, "A password is " +
"required if not using default credentials");
isValid = false;
}
}
Uri.TryCreate(txtProxyServer.Text, UriKind.RelativeOrAbsolute,
out proxyServer);
if(chkUseProxyServer.Checked)
{
if(txtProxyServer.Text.Length == 0)
{
epErrors.SetError(txtProxyServer, "A proxy server is " +
"required if one is used");
isValid = false;
}
else
if(proxyServer == null)
{
epErrors.SetError(txtProxyServer, "The proxy server " +
"name does not appear to be valid");
isValid = false;
}
if(!chkUseProxyDefCreds.Checked)
{
if(txtProxyUserName.Text.Length == 0)
{
epErrors.SetError(txtProxyUserName, "A user name is " +
"required if not using default credentials");
isValid = false;
}
if(txtProxyPassword.Text.Length == 0)
{
epErrors.SetError(txtProxyPassword, "A password is " +
"required if not using default credentials");
isValid = false;
}
}
}
if(!isValid)
return;
if(txtAjaxDocUrl.Text[txtAjaxDocUrl.Text.Length - 1] != '/')
txtAjaxDocUrl.Text += "/";
// Store the changes
root = config.SelectSingleNode("configuration");
node = root.SelectSingleNode("ajaxDoc");
if(node == null)
{
node = config.CreateNode(XmlNodeType.Element,
"ajaxDoc", null);
root.AppendChild(node);
attr = config.CreateAttribute("url");
node.Attributes.Append(attr);
attr = config.CreateAttribute("project");
node.Attributes.Append(attr);
attr = config.CreateAttribute("regenerate");
node.Attributes.Append(attr);
}
node.Attributes["url"].Value = txtAjaxDocUrl.Text;
node.Attributes["project"].Value = txtProjectName.Text;
node.Attributes["regenerate"].Value =
chkRegenerateFiles.Checked.ToString().ToLower(
CultureInfo.InvariantCulture);
userCreds = new UserCredentials(chkUseDefaultCredentials.Checked,
txtUserName.Text, txtPassword.Text);
userCreds.ToXml(config, root);
proxyCreds = new ProxyCredentials(chkUseProxyServer.Checked,
proxyServer, new UserCredentials(chkUseProxyDefCreds.Checked,
txtProxyUserName.Text, txtProxyPassword.Text));
proxyCreds.ToXml(config, root);
this.DialogResult = DialogResult.OK;
this.Close();
}
}
}
| |
/*
* 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 System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using Lucene.Net.Analysis;
using Lucene.Net.Documents;
using Lucene.Net.Analysis.Standard;
using Lucene.Net.Index;
using Lucene.Net.Search;
using Lucene.Net.QueryParsers;
using Lucene.Net.Store;
using Lucene.Net.Util;
using NUnit.Framework;
using Version = Lucene.Net.Util.Version;
namespace Lucene.Net.Search
{
[TestFixture]
public class TestSimpleFacetedSearch
{
Directory _Dir = new RAMDirectory();
IndexReader _Reader;
[SetUp]
public void SetUp()
{
IndexWriter writer = new IndexWriter(_Dir, new StandardAnalyzer(Version.LUCENE_CURRENT), true, IndexWriter.MaxFieldLength.UNLIMITED);
AddDoc(writer, "us", "CCN", "politics", "The White House doubles down on social media");
AddDoc(writer, "us", "CCN", "politics", "Senate Dems fail to block filibuster over judicial nominee");
AddDoc(writer, "us", "BCC", "politics", "A frozen pig's foot and a note laced with anti-Semitic rants were sent to Rep. Peter King's Capitol Hill office, a congressional source familiar with the situation confirmed to CNN Monday");
AddDoc(writer, "us", "CCN", "sport", "But when all was said and done, Haslem's 13 points, five rebounds, two assists, one block and one steal in the course of 23 minutes");
AddDoc(writer, "en", "CCN", "tech", "blockingQueue<T> contains two private fields and exposes two public methods.");
AddDoc(writer, "en", "BCC", "tech", "An Argentine court this week granted an injunction that blocks the Internet giant from 'suggesting' searches that lead to certain sites that have been deemed anti-Semitic, and removes the sites from the search engine's index");
AddDoc(writer, "en", "CCN", "dummy", "oooooooooooooooooooooo");
writer.Close();
_Reader = IndexReader.Open(_Dir, true);
}
void AddDoc(IndexWriter writer, string lang, string source, string group, string text)
{
Field f0 = new Field("lang", lang, Field.Store.YES, Field.Index.NOT_ANALYZED);
Field f1 = new Field("source", source, Field.Store.YES, Field.Index.NOT_ANALYZED);
Field f2 = new Field("category", group, Field.Store.YES, Field.Index.NOT_ANALYZED);
Field f3 = new Field("text", text, Field.Store.YES, Field.Index.ANALYZED);
Document doc = new Document();
doc.Add(f0);
doc.Add(f1);
doc.Add(f2);
doc.Add(f3);
writer.AddDocument(doc);
}
[Test]
public void Test1()
{
//See, Is there an exception
HowToUse("block*");
HowToUse("qwertyuiop");
//OK. No exception
}
[Test]
public void Test2()
{
Query query = new QueryParser(Lucene.Net.Util.Version.LUCENE_29, "text", new StandardAnalyzer(Lucene.Net.Util.Version.LUCENE_29)).Parse("block*");
SimpleFacetedSearch sfs = new SimpleFacetedSearch(_Reader, "category");
SimpleFacetedSearch.Hits hits = sfs.Search(query);
Assert.AreEqual(4, hits.HitsPerFacet.Length);
foreach (SimpleFacetedSearch.HitsPerFacet hpg in hits.HitsPerFacet)
{
if (hpg.Name[0] == "politics")
{
Assert.AreEqual(1, hpg.HitCount);
}
else
if (hpg.Name[0] == "tech")
{
Assert.AreEqual(2, hpg.HitCount);
}
else
if (hpg.Name[0] == "sport")
{
Assert.AreEqual(1, hpg.HitCount);
}
else
{
Assert.AreEqual(0, hpg.HitCount);
}
}
Assert.AreEqual(4, hits.TotalHitCount);
foreach (SimpleFacetedSearch.HitsPerFacet hpg in hits.HitsPerFacet)
{
foreach (Document doc in hpg.Documents)
{
string text = doc.GetField("text").StringValue;
Assert.IsTrue(text.Contains("block"));
}
}
}
[Test]
public void Test3()
{
Query query = new QueryParser(Lucene.Net.Util.Version.LUCENE_29, "text", new StandardAnalyzer(Lucene.Net.Util.Version.LUCENE_29)).Parse("block*");
SimpleFacetedSearch sfs = new SimpleFacetedSearch(_Reader, new string[] { "lang", "source", "category" });
SimpleFacetedSearch.Hits hits = sfs.Search(query);
Assert.AreEqual(6, hits.HitsPerFacet.Length);
int nohit = 0;
foreach (SimpleFacetedSearch.HitsPerFacet hpg in hits.HitsPerFacet)
{
//Test for [System.Collections.Generic.KeyNotFoundException : The given key was not present in the dictionary.]
var x = hits[hpg.Name];
var y = hits[hpg.Name.ToString()];
if (hpg.Name[0] == "us" && hpg.Name[1] == "CCN" && hpg.Name[2] == "politics")
{
Assert.AreEqual(1, hpg.HitCount);
}
else
if (hpg.Name[0] == "en" && hpg.Name[1] == "BCC" && hpg.Name[2] == "tech")
{
Assert.AreEqual(1, hpg.HitCount);
}
else
if (hpg.Name[0] == "us" && hpg.Name[1] == "CCN" && hpg.Name[2] == "sport")
{
Assert.AreEqual(1, hpg.HitCount);
}
else
if (hpg.Name[0] == "en" && hpg.Name[1] == "CCN" && hpg.Name[2] == "tech")
{
Assert.AreEqual(1, hpg.HitCount);
}
else
{
nohit++;
Assert.AreEqual(0, hpg.HitCount);
}
}
Assert.AreEqual(2, nohit);
Assert.AreEqual(4, hits.TotalHitCount);
foreach (SimpleFacetedSearch.HitsPerFacet hpg in hits.HitsPerFacet)
{
foreach (Document doc in hpg.Documents)
{
string text = doc.GetField("text").StringValue;
Assert.IsTrue(text.Contains("block"));
}
}
}
[Test]
public void Test4()
{
Query query = new QueryParser(Lucene.Net.Util.Version.LUCENE_29, "text", new StandardAnalyzer(Lucene.Net.Util.Version.LUCENE_29)).Parse("xxxxxxxxxxxxx");
SimpleFacetedSearch sfs = new SimpleFacetedSearch(_Reader, "category");
SimpleFacetedSearch.Hits hits = sfs.Search(query);
Assert.AreEqual(4, hits.HitsPerFacet.Length);
Assert.AreEqual(0, hits.HitsPerFacet[0].HitCount);
Assert.AreEqual(0, hits.HitsPerFacet[1].HitCount);
Assert.AreEqual(0, hits.HitsPerFacet[2].HitCount);
}
[Test]
public void Test5()
{
Query query = new MatchAllDocsQuery();
SimpleFacetedSearch sfs = new SimpleFacetedSearch(_Reader, "category");
SimpleFacetedSearch.Hits hits = sfs.Search(query);
Assert.AreEqual(7, hits.TotalHitCount);
}
[Test]
public void Test6()
{
Query query = new MatchAllDocsQuery();
SimpleFacetedSearch sfs = new SimpleFacetedSearch(_Reader, "nosuchfield");
SimpleFacetedSearch.Hits hits = sfs.Search(query);
Assert.AreEqual(0, hits.TotalHitCount);
Assert.AreEqual(0, hits.HitsPerFacet.Length);
}
[Test]
public void Test7()
{
Query query = new QueryParser(Lucene.Net.Util.Version.LUCENE_29, "text", new StandardAnalyzer(Lucene.Net.Util.Version.LUCENE_29)).Parse("a");
SimpleFacetedSearch sfs = new SimpleFacetedSearch(_Reader, "category");
SimpleFacetedSearch.Hits hits = sfs.Search(query);
Assert.AreEqual(0, hits.TotalHitCount, "Unexpected TotalHitCount");
foreach(var x in hits.HitsPerFacet.Where(h=>h.HitCount>0))
{
Assert.Fail("There must be no hit");
}
}
int _errorCount = 0;
void MultiThreadedAccessThread(object o)
{
SimpleFacetedSearch sfs = (SimpleFacetedSearch)o;
Query query = new QueryParser(Lucene.Net.Util.Version.LUCENE_29, "text", new StandardAnalyzer(Lucene.Net.Util.Version.LUCENE_29)).Parse("block*");
for (int i = 0; i < 2000; i++)
{
SimpleFacetedSearch.Hits hits = sfs.Search(query);
if (6 != hits.HitsPerFacet.Length) _errorCount++;
foreach (SimpleFacetedSearch.HitsPerFacet hpg in hits.HitsPerFacet)
{
if (hpg.Name[0] == "us" && hpg.Name[1] == "CCN" && hpg.Name[2] == "politics")
{
if (1 != hpg.HitCount) _errorCount++;
}
else
if (hpg.Name[0] == "en" && hpg.Name[1] == "BCC" && hpg.Name[2] == "tech")
{
if (1 != hpg.HitCount) _errorCount++;
}
else
if (hpg.Name[0] == "us" && hpg.Name[1] == "CCN" && hpg.Name[2] == "sport")
{
if (1 != hpg.HitCount) _errorCount++;
}
else
if (hpg.Name[0] == "en" && hpg.Name[1] == "CCN" && hpg.Name[2] == "tech")
{
if (1 != hpg.HitCount) _errorCount++;
}
else
{
if (0 != hpg.HitCount) _errorCount++;
}
if (4 != hits.TotalHitCount) _errorCount++;
}
}
}
[Test]
public void TestMultiThreadedAccess()
{
Query query = new QueryParser(Lucene.Net.Util.Version.LUCENE_29, "text", new StandardAnalyzer(Lucene.Net.Util.Version.LUCENE_29)).Parse("block*");
SimpleFacetedSearch sfs = new SimpleFacetedSearch(_Reader, new string[] { "lang", "source", "category" });
_errorCount = 0;
Thread[] t = new Thread[20];
for (int i = 0; i < t.Length; i++)
{
t[i] = new Thread(MultiThreadedAccessThread);
t[i].Start(sfs);
}
for (int i = 0; i < t.Length; i++)
{
t[i].Join();
}
Assert.AreEqual(0, _errorCount);
}
/// <summary>
/// *****************************************************
/// * SAMPLE USAGE *
/// *****************************************************
/// </summary>
void HowToUse(string searchString)
{
Query query = new QueryParser(Lucene.Net.Util.Version.LUCENE_29, "text", new StandardAnalyzer(Lucene.Net.Util.Version.LUCENE_29)).Parse(searchString);
SimpleFacetedSearch sfs = new SimpleFacetedSearch(_Reader, new string[] { "source", "category" });
SimpleFacetedSearch.Hits hits = sfs.Search(query, 10);
long totalHits = hits.TotalHitCount;
foreach (SimpleFacetedSearch.HitsPerFacet hpg in hits.HitsPerFacet)
{
long hitCountPerGroup = hpg.HitCount;
SimpleFacetedSearch.FacetName facetName = hpg.Name;
for (int i = 0; i < facetName.Length; i++)
{
string part = facetName[i];
}
foreach (Document doc in hpg.Documents)
{
string text = doc.GetField("text").StringValue;
System.Diagnostics.Debug.WriteLine(">>" + facetName + ": " + text);
}
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using PcapDotNet.Packets.Ethernet;
using PcapDotNet.Packets.Icmp;
using PcapDotNet.Packets.IpV4;
using PcapDotNet.Packets.TestUtils;
using PcapDotNet.TestUtils;
namespace PcapDotNet.Packets.Test
{
/// <summary>
/// Summary description for IcmpTests
/// </summary>
[TestClass]
public class IcmpTests
{
/// <summary>
/// Gets or sets the test context which provides
/// information about and functionality for the current test run.
/// </summary>
public TestContext TestContext { get; set; }
#region Additional test attributes
//
// You can use the following additional attributes as you write your tests:
//
// Use ClassInitialize to run code before running the first test in the class
// [ClassInitialize()]
// public static void MyClassInitialize(TestContext testContext) { }
//
// Use ClassCleanup to run code after all tests in a class have run
// [ClassCleanup()]
// public static void MyClassCleanup() { }
//
// Use TestInitialize to run code before running each test
// [TestInitialize()]
// public void MyTestInitialize() { }
//
// Use TestCleanup to run code after each test has run
// [TestCleanup()]
// public void MyTestCleanup() { }
//
#endregion
[TestMethod]
public void RandomIcmpTest()
{
EthernetLayer ethernetLayer = new EthernetLayer
{
Source = new MacAddress("00:01:02:03:04:05"),
Destination = new MacAddress("A0:A1:A2:A3:A4:A5")
};
int seed = new Random().Next();
Console.WriteLine("Seed: " + seed);
Random random = new Random(seed);
for (int i = 0; i != 2000; ++i)
{
IpV4Layer ipV4Layer = random.NextIpV4Layer(null);
ipV4Layer.HeaderChecksum = null;
Layer ipLayer = random.NextBool() ? (Layer)ipV4Layer : random.NextIpV6Layer(IpV4Protocol.InternetControlMessageProtocol, false);
IcmpLayer icmpLayer = random.NextIcmpLayer();
icmpLayer.Checksum = null;
if (icmpLayer.MessageType == IcmpMessageType.DestinationUnreachable &&
icmpLayer.MessageTypeAndCode != IcmpMessageTypeAndCode.DestinationUnreachableFragmentationNeededAndDoNotFragmentSet)
{
((IcmpDestinationUnreachableLayer)icmpLayer).NextHopMaximumTransmissionUnit = 0;
}
IEnumerable<ILayer> icmpPayloadLayers = random.NextIcmpPayloadLayers(icmpLayer);
int icmpPayloadLength = icmpPayloadLayers.Select(layer => layer.Length).Sum();
switch (icmpLayer.MessageType)
{
case IcmpMessageType.ParameterProblem:
if (icmpPayloadLength % 4 != 0)
icmpPayloadLayers = icmpPayloadLayers.Concat(new[] {new PayloadLayer {Data = random.NextDatagram(4 - icmpPayloadLength % 4)}});
icmpPayloadLength = icmpPayloadLayers.Select(layer => layer.Length).Sum();
IcmpParameterProblemLayer icmpParameterProblemLayer = (IcmpParameterProblemLayer)icmpLayer;
icmpParameterProblemLayer.Pointer = (byte)(icmpParameterProblemLayer.Pointer % icmpPayloadLength);
icmpParameterProblemLayer.OriginalDatagramLength = icmpPayloadLength - icmpPayloadLayers.First().Length;
break;
case IcmpMessageType.SecurityFailures:
((IcmpSecurityFailuresLayer)icmpLayer).Pointer %= (ushort)icmpPayloadLength;
break;
}
PacketBuilder packetBuilder = new PacketBuilder(new ILayer[] { ethernetLayer, ipLayer, icmpLayer }.Concat(icmpPayloadLayers));
Packet packet = packetBuilder.Build(DateTime.Now);
Assert.IsTrue(packet.IsValid, "IsValid");
byte[] buffer = (byte[])packet.Buffer.Clone();
buffer.Write(ethernetLayer.Length + ipLayer.Length, random.NextDatagram(icmpLayer.Length));
Packet illegalPacket = new Packet(buffer, DateTime.Now, packet.DataLink);
Assert.IsFalse(illegalPacket.IsValid, "IsInvalid");
if (illegalPacket.Ethernet.Ip.Icmp is IcmpUnknownDatagram)
{
byte[] icmpBuffer = new byte[illegalPacket.Ethernet.Ip.Icmp.ExtractLayer().Length];
ILayer layer = illegalPacket.Ethernet.Ip.Icmp.ExtractLayer();
layer.Write(icmpBuffer,0,icmpBuffer.Length, null,null);
layer.Finalize(icmpBuffer,0,icmpBuffer.Length,null);
MoreAssert.AreSequenceEqual(illegalPacket.Ethernet.Ip.Icmp.ToArray(),
icmpBuffer);
Assert.AreEqual(illegalPacket,
PacketBuilder.Build(DateTime.Now, ethernetLayer, ipLayer, illegalPacket.Ethernet.Ip.Icmp.ExtractLayer()));
}
// Ethernet
ethernetLayer.EtherType = ipLayer == ipV4Layer ? EthernetType.IpV4 : EthernetType.IpV6;
Assert.AreEqual(ethernetLayer, packet.Ethernet.ExtractLayer(), "Ethernet Layer");
ethernetLayer.EtherType = EthernetType.None;
// IP.
if (ipLayer == ipV4Layer)
{
// IPv4.
ipV4Layer.Protocol = IpV4Protocol.InternetControlMessageProtocol;
ipV4Layer.HeaderChecksum = ((IpV4Layer)packet.Ethernet.IpV4.ExtractLayer()).HeaderChecksum;
Assert.AreEqual(ipV4Layer, packet.Ethernet.IpV4.ExtractLayer());
ipV4Layer.HeaderChecksum = null;
Assert.AreEqual(ipV4Layer.Length, packet.Ethernet.IpV4.HeaderLength);
Assert.IsTrue(packet.Ethernet.IpV4.IsHeaderChecksumCorrect);
Assert.AreEqual(ipV4Layer.Length + icmpLayer.Length + icmpPayloadLength,
packet.Ethernet.IpV4.TotalLength);
Assert.AreEqual(IpV4Datagram.DefaultVersion, packet.Ethernet.IpV4.Version);
}
else
{
// IPv6.
Assert.AreEqual(ipLayer, packet.Ethernet.IpV6.ExtractLayer());
}
// ICMP
IcmpDatagram actualIcmp = packet.Ethernet.Ip.Icmp;
IcmpLayer actualIcmpLayer = (IcmpLayer)actualIcmp.ExtractLayer();
icmpLayer.Checksum = actualIcmpLayer.Checksum;
Assert.AreEqual(icmpLayer, actualIcmpLayer);
Assert.AreEqual(icmpLayer.GetHashCode(), actualIcmpLayer.GetHashCode());
if (actualIcmpLayer.MessageType != IcmpMessageType.RouterSolicitation)
{
Assert.AreNotEqual(random.NextIcmpLayer(), actualIcmpLayer);
Assert.AreNotEqual(random.NextIcmpLayer().GetHashCode(), actualIcmpLayer.GetHashCode());
}
Assert.IsTrue(actualIcmp.IsChecksumCorrect);
Assert.AreEqual(icmpLayer.MessageType, actualIcmp.MessageType);
Assert.AreEqual(icmpLayer.CodeValue, actualIcmp.Code);
Assert.AreEqual(icmpLayer.MessageTypeAndCode, actualIcmp.MessageTypeAndCode);
Assert.AreEqual(packet.Length - ethernetLayer.Length - ipLayer.Length - IcmpDatagram.HeaderLength, actualIcmp.Payload.Length);
Assert.IsNotNull(icmpLayer.ToString());
switch (packet.Ethernet.Ip.Icmp.MessageType)
{
case IcmpMessageType.RouterSolicitation:
case IcmpMessageType.SourceQuench:
case IcmpMessageType.TimeExceeded:
Assert.AreEqual<uint>(0, actualIcmp.Variable);
break;
case IcmpMessageType.DestinationUnreachable:
case IcmpMessageType.ParameterProblem:
case IcmpMessageType.Redirect:
case IcmpMessageType.ConversionFailed:
case IcmpMessageType.Echo:
case IcmpMessageType.EchoReply:
case IcmpMessageType.Timestamp:
case IcmpMessageType.TimestampReply:
case IcmpMessageType.InformationRequest:
case IcmpMessageType.InformationReply:
case IcmpMessageType.RouterAdvertisement:
case IcmpMessageType.AddressMaskRequest:
case IcmpMessageType.AddressMaskReply:
break;
case IcmpMessageType.TraceRoute:
Assert.AreEqual(((IcmpTraceRouteLayer)icmpLayer).OutboundHopCount == 0xFFFF, ((IcmpTraceRouteDatagram)actualIcmp).IsOutbound);
break;
case IcmpMessageType.DomainNameRequest:
case IcmpMessageType.SecurityFailures:
break;
case IcmpMessageType.DomainNameReply:
default:
throw new InvalidOperationException("Invalid icmpMessageType " + packet.Ethernet.Ip.Icmp.MessageType);
}
}
}
[TestMethod]
public void IcmpRouterAdvertisementEntryTest()
{
Random random = new Random();
IcmpRouterAdvertisementEntry entry1 = new IcmpRouterAdvertisementEntry(random.NextIpV4Address(), random.Next());
IcmpRouterAdvertisementEntry entry2 = new IcmpRouterAdvertisementEntry(random.NextIpV4Address(), random.Next());
Assert.AreEqual(entry1, entry1);
Assert.AreEqual(entry1.GetHashCode(), entry1.GetHashCode());
Assert.AreNotEqual(entry1, entry2);
Assert.AreNotEqual(entry1.GetHashCode(), entry2.GetHashCode());
}
[TestMethod]
[ExpectedException(typeof(ArgumentNullException), AllowDerivedTypes = false)]
public void IcmpDatagramCreateDatagramNullBufferTest()
{
Assert.IsNotNull(IcmpDatagram.CreateDatagram(null, 0, 0));
Assert.Fail();
}
[TestMethod]
public void IcmpDatagramCreateDatagramBadOffsetTest()
{
Assert.IsInstanceOfType(IcmpDatagram.CreateDatagram(new byte[0], -1, 0), typeof(IcmpUnknownDatagram));
}
[TestMethod]
[ExpectedException(typeof(ArgumentOutOfRangeException), AllowDerivedTypes = false)]
public void IcmpParameterProblemLayerOriginalDatagramLengthNotRound()
{
Layer layer = new IcmpParameterProblemLayer {OriginalDatagramLength = 6};
Assert.IsNotNull(layer);
}
[TestMethod]
[ExpectedException(typeof(ArgumentOutOfRangeException), AllowDerivedTypes = false)]
public void IcmpParameterProblemLayerOriginalDatagramLengthTooBig()
{
Layer layer = new IcmpParameterProblemLayer { OriginalDatagramLength = 2000 };
Assert.IsNotNull(layer);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Text;
using System.Windows.Forms;
using System.Runtime.CompilerServices;
using System.Diagnostics;
namespace Trionic5Controls
{
public class Surface3DRenderer
{
double screenDistance, sf, cf, st, ct, R, A, B, C, D; //transformations coeficients
double density = 4f;
Color penColor = Color.Black;
PointF startPoint = new PointF(-10, -10);
PointF endPoint = new PointF(10, 10);
RendererFunction function = defaultFunction;
ColorSchema colorSchema = ColorSchema.Autumn;
private double m_maxdata_element = 0;
private double m_correction_percentage = 1;
private bool m_isRedWhite = false;
int m_highlighted_x_value = -1;
int m_highlighted_y_value = -1;
int m_highlightedselection_x_value = -1;
int m_highlightedselection_y_value = -1;
private bool m_showinBlue = false;
public bool ShowinBlue
{
get { return m_showinBlue; }
set { m_showinBlue = value; }
}
public bool IsRedWhite
{
get { return m_isRedWhite; }
set { m_isRedWhite = value; }
}
public double Correction_percentage
{
get { return m_correction_percentage; }
set { m_correction_percentage = value; }
}
int[] x_axisvalues;
public int[] X_axisvalues
{
get { return x_axisvalues; }
set { x_axisvalues = value; }
}
int[] y_axisvalues;
public int[] Y_axisvalues
{
get { return y_axisvalues; }
set { y_axisvalues = value; }
}
string m_xaxis_descr = "x-axis";
public string Xaxis_descr
{
get { return m_xaxis_descr; }
set { m_xaxis_descr = value; }
}
string m_yaxis_descr = "y-axis";
public string Yaxis_descr
{
get { return m_yaxis_descr; }
set { m_yaxis_descr = value; }
}
string m_zaxis_descr = "z-axis";
public string Zaxis_descr
{
get { return m_zaxis_descr; }
set { m_zaxis_descr = value; }
}
#region Properties
/// <summary>
/// Surface spanning net density
/// </summary>
public double Density
{
get { return density; }
set { density = value; }
}
/// <summary>
/// Quadrilateral pen color
/// </summary>
public Color PenColor
{
get { return penColor; }
set { penColor = value; }
}
public PointF StartPoint
{
get { return startPoint; }
set { startPoint = value; }
}
public PointF EndPoint
{
get { return endPoint; }
set { endPoint = value; }
}
public RendererFunction Function
{
get { return function; }
set { function = value; }
}
public ColorSchema ColorSchema
{
get { return colorSchema; }
set { colorSchema = value; }
}
#endregion
/// <summary>
/// Initializes a new instance of the <see cref="Surface3DRenderer"/> class. Calculates transformations coeficients.
/// </summary>
/// <param name="obsX">Observator's X position</param>
/// <param name="obsY">Observator's Y position</param>
/// <param name="obsZ">Observator's Z position</param>
/// <param name="xs0">X coordinate of screen</param>
/// <param name="ys0">Y coordinate of screen</param>
/// <param name="screenWidth">Drawing area width in pixels.</param>
/// <param name="screenHeight">Drawing area height in pixels.</param>
/// <param name="screenDistance">The screen distance.</param>
/// <param name="screenWidthPhys">Width of the screen in meters.</param>
/// <param name="screenHeightPhys">Height of the screen in meters.</param>
public Surface3DRenderer(double obsX, double obsY, double obsZ, int xs0, int ys0, int screenWidth, int screenHeight, double screenDistance, double screenWidthPhys, double screenHeightPhys)
{
ReCalculateTransformationsCoeficients(obsX, obsY, obsZ, xs0, ys0, screenWidth, screenHeight, screenDistance, screenWidthPhys, screenHeightPhys);
}
public void ReCalculateTransformationsCoeficients(double obsX, double obsY, double obsZ, int xs0, int ys0, int screenWidth, int screenHeight, double screenDistance, double screenWidthPhys, double screenHeightPhys)
{
double r1, a;
if (screenWidthPhys <= 0)//when screen dimensions are not specified
screenWidthPhys = screenWidth * 0.0257 / 72.0; //0.0257 m = 1 inch. Screen has 72 px/inch
if (screenHeightPhys <= 0)
screenHeightPhys = screenHeight * 0.0257 / 72.0;
r1 = obsX * obsX + obsY * obsY;
a = Math.Sqrt(r1);//distance in XY plane
R = Math.Sqrt(r1 + obsZ * obsZ);//distance from observator to center
if (a != 0) //rotation matrix coeficients calculation
{
sf = obsY / a;//sin( fi)
cf = obsX / a;//cos( fi)
}
else
{
sf = 0;
cf = 1;
}
st = a / R;//sin( teta)
ct = obsZ / R;//cos( teta)
//linear tranfrormation coeficients
A = screenWidth / screenWidthPhys;
B = xs0 + A * screenWidthPhys / 2.0;
C = -(double)screenHeight / screenHeightPhys;
D = ys0 - C * screenHeightPhys / 2.0;
this.screenDistance = screenDistance;
}
/// <summary>
/// Performs projection. Calculates screen coordinates for 3D point.
/// </summary>
/// <param name="x">Point's x coordinate.</param>
/// <param name="y">Point's y coordinate.</param>
/// <param name="z">Point's z coordinate.</param>
/// <returns>Point in 2D space of the screen.</returns>
public PointF Project(double x, double y, double z)
{
double xn, yn, zn;//point coordinates in computer's frame of reference
//transformations
xn = -sf * x + cf * y;
yn = -cf * ct * x - sf * ct * y + st * z;
zn = -cf * st * x - sf * st * y - ct * z + R;
if (zn == 0) zn = 0.01;
//Tales' theorem
return new PointF((float)(A * xn * screenDistance / zn + B), (float)(C * yn * screenDistance / zn + D));
}
private System.Data.DataTable m_mapdata = new System.Data.DataTable();
public System.Data.DataTable Mapdata
{
get {
return m_mapdata;
}
set
{
m_mapdata = value;
foreach (System.Data.DataRow dr in m_mapdata.Rows)
{
foreach (object cell in dr.ItemArray)
{
try
{
double d = Convert.ToDouble(cell);
if (d > m_maxdata_element) m_maxdata_element = d;
}
catch (Exception E)
{
Console.WriteLine("Set m_mapdata: " + E.Message);
}
}
}
}
}
private System.Data.DataTable m_mapcomparedata = new System.Data.DataTable();
public System.Data.DataTable Mapcomparedata
{
get
{
return m_mapcomparedata;
}
set
{
m_mapcomparedata = value;
foreach (System.Data.DataRow dr in m_mapdata.Rows)
{
foreach (object cell in dr.ItemArray)
{
try
{
double d = Convert.ToDouble(cell);
if (d > m_maxdata_element) m_maxdata_element = d;
}
catch (Exception E)
{
Console.WriteLine("Set m_mapdata: " + E.Message);
}
}
}
}
}
private System.Data.DataTable m_maporiginaldata = new System.Data.DataTable();
public System.Data.DataTable Maporiginaldata
{
get
{
return m_maporiginaldata;
}
set
{
m_maporiginaldata = value;
foreach (System.Data.DataRow dr in m_mapdata.Rows)
{
foreach (object cell in dr.ItemArray)
{
try
{
double d = Convert.ToDouble(cell);
if (d > m_maxdata_element) m_maxdata_element = d;
}
catch (Exception E)
{
Console.WriteLine("Set m_mapdata: " + E.Message);
}
}
}
}
}
public void DrawXAxis(string description, double[] values)
{
}
public double GetDataFromTable(double xi, double yi)
{
double retval = 0;
//Console.WriteLine("xi A = " + xi.ToString() + " yi = " + yi.ToString());
xi = (m_mapdata.Columns.Count-1) - xi;
//Console.WriteLine("xi B = " + xi.ToString());
if (xi < m_mapdata.Columns.Count && yi < m_mapdata.Rows.Count)
{
try
{
if (m_mapdata.Rows[(int)yi][(int)xi] != DBNull.Value)
{
retval = Convert.ToDouble(m_mapdata.Rows[(int)yi][(int)xi]);
if (retval > 0xF000)
{
retval = 0x10000 - retval;
}
}
}
catch (Exception E)
{
Console.WriteLine(E.Message);
}
}
else
{
Console.WriteLine("xi C = " + xi.ToString() + " yi C = " + yi.ToString());
}
return retval;
}
public double GetDataFromOriginalTable(double xi, double yi)
{
double retval = 0;
//Console.WriteLine("xi A = " + xi.ToString() + " yi = " + yi.ToString());
xi = (m_maporiginaldata.Columns.Count - 1) - xi;
//Console.WriteLine("xi B = " + xi.ToString());
if (xi < m_maporiginaldata.Columns.Count && yi < m_maporiginaldata.Rows.Count)
{
try
{
if (m_maporiginaldata.Rows[(int)yi][(int)xi] != DBNull.Value)
{
retval = Convert.ToDouble(m_maporiginaldata.Rows[(int)yi][(int)xi]);
if (retval > 0xF000)
{
retval = 0x10000 - retval;
}
}
}
catch (Exception E)
{
Console.WriteLine(E.Message);
}
}
else
{
//Console.WriteLine("xi C = " + xi.ToString() + " yi C = " + yi.ToString());
}
return retval;
}
public double GetDataFromCompareTable(double xi, double yi)
{
double retval = 0;
//Console.WriteLine("xi A = " + xi.ToString() + " yi = " + yi.ToString());
xi = (m_mapcomparedata.Columns.Count - 1) - xi;
//Console.WriteLine("xi B = " + xi.ToString());
if (xi < m_mapcomparedata.Columns.Count && yi < m_mapcomparedata.Rows.Count)
{
try
{
if (m_mapcomparedata.Rows[(int)yi][(int)xi] != DBNull.Value)
{
retval = Convert.ToDouble(m_mapcomparedata.Rows[(int)yi][(int)xi]);
if (retval > 0xF000)
{
retval = 0x10000 - retval;
}
}
}
catch (Exception E)
{
Console.WriteLine(E.Message);
}
}
else
{
//Console.WriteLine("xi C = " + xi.ToString() + " yi C = " + yi.ToString());
}
return retval;
}
private SolidBrush GetDrawingColor(double b)
{
//return new SolidBrush(Color.LightBlue);
b *= 255;
//b /= m_MaxValueInTable;
if (m_maxdata_element != 0)
{
b /= m_maxdata_element;
}
int green = 128;
int blue = 128;
Color c = Color.White;
if (b < 0) b = 0;
if (b > 255) b = 255;
if (Double.IsNaN(b)) b = 0;
if (m_showinBlue)
{
b /= 2;
blue = 255 - (int)b;
green = 0;
c = Color.FromArgb((int)b, green, blue);
}
else if (!m_isRedWhite)
{
blue = 0;
green = 255 - (int)b;
c = Color.FromArgb((int)b, green, blue);
}
else
{
if (b < 0) b = 0;
c = Color.FromArgb((int)b, Color.Red);
}
SolidBrush sb = new SolidBrush(c);
return sb;
}
public void RenderSurface(Graphics graphics, PointF LastMouseHoverPoint)
{
//double tempi = 0;
//density = 1F;
PointF[] axis_bounds = new PointF[7];
SolidBrush[] brushes = new SolidBrush[colorSchema.Length];
for (int i = 0; i < brushes.Length; i++)
brushes[i] = new SolidBrush(colorSchema[i]);
double z1, z2;
PointF[] polygon = new PointF[4];
PointF[] polygonoriginal = new PointF[4];
PointF[] polygoncompare = new PointF[4];
double xi = startPoint.X, yi, minZ = double.PositiveInfinity, maxZ = double.NegativeInfinity;
double[,] mesh = new double[(int)((endPoint.X - startPoint.X) / density + 2), (int)((endPoint.Y - startPoint.Y) / density + 2)];
double[,] meshCompare = new double[(int)((endPoint.X - startPoint.X) / density + 2), (int)((endPoint.Y - startPoint.Y) / density + 2)];
double[,] meshOriginal = new double[(int)((endPoint.X - startPoint.X) / density + 2), (int)((endPoint.Y - startPoint.Y) / density + 2)];
PointF[,] meshF = new PointF[mesh.GetLength(0), mesh.GetLength(1)];
PointF[,] meshFCompare = new PointF[mesh.GetLength(0), mesh.GetLength(1)];
PointF[,] meshFOriginal = new PointF[mesh.GetLength(0), mesh.GetLength(1)];
// assen tekenen
PointF[] axispolygon = new PointF[4];
for (int z = 1; z <= (int)Math.Ceiling(m_maxdata_element); z++)
{
string zvalue = z.ToString();
try
{
float dblzvalue = z * (1F/(float)m_correction_percentage);
zvalue = dblzvalue.ToString("F0");
}
catch (Exception E)
{
Console.WriteLine(E.Message);
}
PointF p = Project(mesh.GetLength(0)+1, 0, z);
graphics.DrawString(zvalue, new Font(FontFamily.GenericSansSerif, 6), Brushes.Black, p);
}
for (int t = 0; t < mesh.GetLength(0); t++)
{
for (int yt = 0; yt < (int)Math.Ceiling(m_maxdata_element); yt++)
{
try
{
axispolygon[1] = Project(t, 0, yt);
axispolygon[0] = Project(t + 1, 0, yt);
axispolygon[2] = Project(t, 0, yt + 1);
axispolygon[3] = Project(t + 1, 0, yt + 1);
graphics.DrawPolygon(Pens.DarkGray, axispolygon);
}
catch (Exception E)
{
Console.WriteLine(E.Message);
}
}
}
// assen tekenen
for (int t = 0; t < mesh.GetLength(1) ; t++)
{
for (int yt = 0; yt < (int)Math.Ceiling(m_maxdata_element); yt++)
{
try
{
axispolygon[1] = Project(0, t, yt);
axispolygon[0] = Project(0, t + 1, yt);
axispolygon[2] = Project(0, t, yt + 1);
axispolygon[3] = Project(0, t + 1, yt + 1);
graphics.DrawPolygon(Pens.DarkGray, axispolygon);
}
catch (Exception E)
{
Console.WriteLine(E.Message);
}
}
string yaxis = t.ToString();
if (y_axisvalues != null)
{
yaxis = "";
if (y_axisvalues.Length > t)
{
yaxis = y_axisvalues.GetValue((y_axisvalues.Length - 1) - (t)).ToString();
}
}
PointF p = Project( mesh.GetLength(0) + 1,t + 1, 0);
graphics.DrawString(yaxis, new Font(FontFamily.GenericSansSerif, 6), Brushes.Black, p);
}
for (int t = 0; t < mesh.GetLength(0) ; t++)
{
for (int yt = 0; yt < mesh.GetLength(1); yt++)
{
try
{
axispolygon[1] = Project(t, yt, 0);
axispolygon[0] = Project(t, yt + 1, 0);
axispolygon[2] = Project(t + 1, yt, 0);
axispolygon[3] = Project(t + 1, yt + 1, 0);
graphics.DrawPolygon(Pens.DarkGray, axispolygon);
}
catch (Exception E)
{
Console.WriteLine(E.Message);
}
}
string xaxis = t.ToString();
if (x_axisvalues != null)
{
xaxis = "";
if (x_axisvalues.Length > t)
{
xaxis = x_axisvalues.GetValue((x_axisvalues.Length - 1) - t).ToString();
}
}
PointF p = Project(t + 1, mesh.GetLength(1) + 1 ,0);
graphics.DrawString(xaxis, new Font(FontFamily.GenericSansSerif, 6), Brushes.Black, p);
}
for (int x = 0; x < mesh.GetLength(0); x++)
{
yi = startPoint.Y;
for (int y = 0; y < mesh.GetLength(1); y++)
{
double zz = 0;
double zzorig = 0;
double zzcompare = 0;
if (x == (mesh.GetLength(0) - 1) && y == (mesh.GetLength(1) - 1))
{
zz = GetDataFromTable(xi - 1, yi - 1);// ;//function(xi, yi);
zzorig = GetDataFromOriginalTable(xi - 1, yi - 1);// ;//function(xi, yi);
zzcompare = GetDataFromCompareTable(xi - 1, yi - 1);// ;//function(xi, yi);
}
else if (x == (mesh.GetLength(0) - 1))
{
zz = GetDataFromTable(xi - 1, yi);// ;//function(xi, yi);
zzorig = GetDataFromOriginalTable(xi - 1, yi);// ;//function(xi, yi);
zzcompare = GetDataFromCompareTable(xi - 1, yi);// ;//function(xi, yi);
}
else if (y == (mesh.GetLength(1) - 1))
{
zz = GetDataFromTable(xi, yi - 1);// ;//function(xi, yi);
zzorig = GetDataFromOriginalTable(xi, yi - 1);// ;//function(xi, yi);
zzcompare = GetDataFromCompareTable(xi, yi - 1);// ;//function(xi, yi);
}
else
{
zz = GetDataFromTable(xi, yi);// ;//function(xi, yi);
zzorig = GetDataFromOriginalTable(xi, yi);// ;//function(xi, yi);
zzcompare = GetDataFromCompareTable(xi, yi);// ;//function(xi, yi);
}
// tempi += 0.01;
mesh[x, y] = zz;
meshF[x, y] = Project(xi, yi, zz);
meshCompare[x, y] = zzcompare;
meshFCompare[x, y] = Project(xi, yi, zzcompare);
meshOriginal[x, y] = zzorig;
meshFOriginal[x, y] = Project(xi, yi, zzorig);
yi += density;
if (minZ > zz) minZ = zz;
if (maxZ < zz) maxZ = zz;
}
xi += density;
}
double cc = (maxZ - minZ) / (brushes.Length - 1.0);
SolidBrush sborig = new SolidBrush(Color.FromArgb(40, Color.Blue));
Pen penorig = new Pen(Color.FromArgb(30, Color.Blue));
SolidBrush sbcomp = new SolidBrush(Color.FromArgb(50, Color.DimGray));
Pen pencomp = new Pen(Color.FromArgb(40, Color.DimGray));
using (Pen pen = new Pen(penColor))
for (int x = 0; x < mesh.GetLength(0) - 1; x++)
{
for (int y = 0; y < mesh.GetLength(1) - 1; y++)
{
z1 = mesh[x, y];
z2 = mesh[x, y + 1];
//z2 = mesh[x + 1, y + 1];
polygon[0] = meshF[x, y];
polygon[1] = meshF[x, y + 1];
polygon[2] = meshF[x + 1, y + 1];
polygon[3] = meshF[x + 1, y];
polygonoriginal[0] = meshFOriginal[x, y];
polygonoriginal[1] = meshFOriginal[x, y + 1];
polygonoriginal[2] = meshFOriginal[x + 1, y + 1];
polygonoriginal[3] = meshFOriginal[x + 1, y];
polygoncompare[0] = meshFCompare[x, y];
polygoncompare[1] = meshFCompare[x, y + 1];
polygoncompare[2] = meshFCompare[x + 1, y + 1];
polygoncompare[3] = meshFCompare[x + 1, y];
/*
if (x == mesh.GetLength(0) - 1)
{
if (y == mesh.GetLength(1) - 1)
{
z1 = mesh[x, y];
z2 = mesh[x, y];
}
else
{
z1 = mesh[x, y];
z2 = mesh[x, y + 1];
polygon[0] = meshF[x, y];
//polygon[0].Y = 0;
//polygon[0].Y += meshF[x, y].Y - meshF[x - 1, y].Y;
polygon[1] = meshF[x, y + 1];
//polygon[1].Y += meshF[x, y].Y - meshF[x - 1, y].Y;
polygon[2] = meshF[x, y + 1];
polygon[2].X += meshF[x, y].X - meshF[x - 1, y].X;
polygon[2].Y += meshF[x, y + 1].Y - meshF[x , y + 1].Y;
//polygon[2].Y += meshF[x, y].Y -meshF[x - 1, y].Y;
polygon[3] = meshF[x, y];
polygon[3].X += meshF[x, y].X - meshF[x - 1, y ].X;
polygon[3].Y += meshF[x, y].Y - meshF[x , y ].Y;
//polygon[3].Y += meshF[x, y].Y - meshF[x- 1, y ].Y;
}
}
else if (y == mesh.GetLength(1) - 1)
{
if (x == mesh.GetLength(0) - 1)
{
z1 = mesh[x, y];
z2 = mesh[x, y];
}
else
{
z1 = mesh[x, y];
z2 = mesh[x, y];
polygon[0] = meshF[x, y];
polygon[1] = meshF[x, y];
// polygon[1].Y += 10;// meshF[x, y].Y - meshF[x, y - 1].Y;
polygon[1].X += meshF[x, y].X - meshF[x, y - 1].X;
polygon[2] = meshF[x + 1, y];
// polygon[2].Y += 10;// meshF[x, y].Y - meshF[x, y - 1].Y;
polygon[2].X += meshF[x, y].X - meshF[x, y - 1].X;
polygon[3] = meshF[x + 1, y];
// moet uitbreiden naar einde
}
}
else
{
z1 = mesh[x, y];
z2 = mesh[x, y + 1];
//z2 = mesh[x + 1, y + 1];
/*
polygon[0] = meshF[x, y];
polygon[1] = meshF[x, y + 1];
polygon[2] = meshF[x + 1, y + 1];
polygon[3] = meshF[x + 1, y];
}*/
/*if (x == 0 && y == 0)
{
axis_bounds[0] = polygon[0];
}
else if (x == (mesh.GetLength(0) - 2) && y == 0)
{
axis_bounds[1] = polygon[0];
}
else if (x == 0 && y == (mesh.GetLength(1) - 2))
{
// graphics.DrawString("YMAX", new Font(FontFamily.GenericSerif, 8), Brushes.Black, polygon[2]);
axis_bounds[2] = polygon[0];
}
else if (x == (mesh.GetLength(0) - 2) && y == (mesh.GetLength(1) - 2))
{
// graphics.DrawString("MAX", new Font(FontFamily.GenericSerif, 8), Brushes.Black, polygon[3]);
axis_bounds[3] = polygon[0];
}*/
//graphics.SmoothingMode = SmoothingMode.AntiAlias;
//graphics.InterpolationMode = InterpolationMode.HighQualityBilinear;
if ((int)(((z1 + z2) / 2.0 - minZ) / cc) < brushes.Length)
{
try
{
int brushnumber = (brushes.Length - 1) - (int)(((z1 + z2) / 2.0 - minZ) / cc);
//brushes[brushnumber].Color.A =
//int red = GetDrawingColor(z2);
//Console.WriteLine(z1.ToString() + " = red: " + red.ToString());
//graphics.FillPolygon(brushes[brushnumber], polygon);
if (!Double.IsNaN(z1))
{
if (x == m_highlighted_x_value && y == m_highlighted_y_value)
{
graphics.FillPolygon(Brushes.Yellow, polygon);
}
else if (x == m_highlightedselection_x_value && y == m_highlightedselection_y_value)
{
graphics.FillPolygon(Brushes.SteelBlue, polygon);
}
//NEW
else if (x + 1 == m_highlightedselection_x_value && y == m_highlightedselection_y_value)
{
graphics.FillPolygon(Brushes.SteelBlue, polygon);
}
else if (x + 1 == m_highlightedselection_x_value && y + 1 == m_highlightedselection_y_value)
{
graphics.FillPolygon(Brushes.SteelBlue, polygon);
}
else if (x == m_highlightedselection_x_value && y + 1 == m_highlightedselection_y_value)
{
graphics.FillPolygon(Brushes.SteelBlue, polygon);
}
//NEW
else
{
graphics.FillPolygon(GetDrawingColor(z1), polygon);
//LinearGradientBrush lgb = new LinearGradientBrush((PointF)polygon.GetValue(3), (PointF)polygon.GetValue(0), GetDrawingColor(z2).Color, GetDrawingColor(z1).Color);
//graphics.FillPolygon(lgb, polygon);
}
if (m_maporiginaldata.Rows.Count > 0)
{
graphics.FillPolygon(sborig, polygonoriginal);
graphics.DrawPolygon(penorig, polygonoriginal);
}
if (m_mapcomparedata.Rows.Count > 0)
{
graphics.FillPolygon(sbcomp, polygoncompare);
graphics.DrawPolygon(pencomp, polygoncompare);
}
}
}
catch (Exception E)
{
Console.WriteLine(E.Message);
}
}
else
{
graphics.FillPolygon(Brushes.Blue, polygon);
}
graphics.DrawPolygon(pen, polygon);
}
}
for (int i = 0; i < brushes.Length; i++)
brushes[i].Dispose();
// axis labels
PointF xaxispoint = Project(mesh.GetLength(0) / 2, mesh.GetLength(1) + 4, 0);
graphics.DrawString(m_xaxis_descr, new Font(FontFamily.GenericSansSerif, 8), Brushes.MidnightBlue, xaxispoint);
/*float width = graphics.MeasureString(m_xaxis_descr, new Font(FontFamily.GenericSansSerif,8)).Width;
float height = graphics.MeasureString(m_xaxis_descr, new Font(FontFamily.GenericSansSerif, 8)).Height;
graphics.TranslateTransform( width, 0);
graphics.RotateTransform(45);
graphics.DrawString(m_xaxis_descr, new Font(FontFamily.GenericSansSerif, 8), Brushes.MidnightBlue, xaxispoint);*/
PointF yaxispoint = Project(mesh.GetLength(0) + 4, mesh.GetLength(1) / 2, 0);
graphics.DrawString(m_yaxis_descr, new Font(FontFamily.GenericSansSerif, 8), Brushes.MidnightBlue, yaxispoint);
PointF zaxispoint = Project(mesh.GetLength(0) + 4, 0, m_maxdata_element/2);
graphics.DrawString(m_zaxis_descr, new Font(FontFamily.GenericSansSerif, 8), Brushes.MidnightBlue, zaxispoint);
/*if (LastMouseHoverPoint.X != 0 && LastMouseHoverPoint.Y != 0)
{
graphics.FillEllipse(Brushes.YellowGreen, LastMouseHoverPoint.X, LastMouseHoverPoint.Y, 5, 5);
}*/
}
public static RendererFunction GetFunctionHandle(string formula)
{
CompiledFunction fn = FunctionCompiler.Compile(2, formula);
return new RendererFunction(delegate(double x, double y)
{
return fn(x, y);
});
}
public void SetFunction(string formula)
{
function = GetFunctionHandle(formula);
}
private static double defaultFunction(double a, double b)
{
double an = a, bn = b, anPlus1;
short iter = 0;
do
{
anPlus1 = (an + bn) / 2.0;
bn = Math.Sqrt(an * bn);
an = anPlus1;
if (iter++ > 1000) return an;
} while (Math.Abs(an - bn)<0.1);
return an;
}
internal bool GetMousePoint(int x, int y, out PointF tableposition, out double val)
{
PointF p;
tableposition = new Point();
int rowcount = 0;
val = 0;
List<System.Data.DataRow> rows = new List<System.Data.DataRow>();
foreach (System.Data.DataRow r in m_mapdata.Rows) rows.Add(r);
//rows.Reverse();
foreach (System.Data.DataRow dr in rows)
{
int colcount = 0;
List<object> cols = new List<object>();
foreach (object c in dr.ItemArray) cols.Add(c);
cols.Reverse();
foreach (object o in cols)
{
try
{
p = Project((double)colcount, (double)rowcount, Convert.ToDouble(o));
// Console.WriteLine(rowcount.ToString() + " / " + colcount.ToString() + " = " + Convert.ToDouble(o).ToString() + " x = " + p.X.ToString() + " y = " + p.Y.ToString());
int xdiff = (int)Math.Abs(x - p.X);
int ydiff = (int)Math.Abs(y - p.Y);
if (xdiff < 5 && ydiff < 5)
{
// System.Diagnostics.Trace.Write(string.Format("\nrow: {0} - col: {1} - val: {2}", rowcount, colcount, Convert.ToDouble(o) * (1 / m_correction_percentage)));
//Console.WriteLine(rowcount.ToString() + " / " + colcount.ToString() + " = " + Convert.ToDouble(o).ToString() + " x = " + p.X.ToString() + " y = " + p.Y.ToString());
tableposition = new PointF((float)rowcount, (float)colcount);
val = Convert.ToDouble(o) * (1 / m_correction_percentage);
return true;
}
}
catch (Exception E)
{
Console.WriteLine("GetMousePoint: :" + E.Message);
}
colcount++;
}
rowcount++;
}
return false;
/* PointF p;
tableposition = new Point();
int rowcount = 0;
val = 0;
foreach (System.Data.DataRow dr in m_mapdata.Rows)
{
int colcount = 0;
foreach (object o in dr.ItemArray)
{
try
{
p = Project((double)colcount, (double)rowcount, Convert.ToDouble(o));
// Console.WriteLine(rowcount.ToString() + " / " + colcount.ToString() + " = " + Convert.ToDouble(o).ToString() + " x = " + p.X.ToString() + " y = " + p.Y.ToString());
int xdiff = (int)Math.Abs(x - p.X);
int ydiff = (int)Math.Abs(y - p.Y);
if (xdiff < 5 && ydiff < 5)
{
//Console.WriteLine(rowcount.ToString() + " / " + colcount.ToString() + " = " + Convert.ToDouble(o).ToString() + " x = " + p.X.ToString() + " y = " + p.Y.ToString());
tableposition = new PointF((float)rowcount, (float)colcount);
val = Convert.ToDouble(o) * (1/m_correction_percentage);
return true;
}
}
catch (Exception E)
{
Console.WriteLine("GetMousePoint: :" + E.Message);
}
colcount++;
}
rowcount++;
}
return false;*/
}
internal void RenderGraph(Graphics graphics)
{
//double tempi = 0;
//double z1, z2;
PointF[] polygon = new PointF[4];
for (int z = 1; z <= (int)Math.Ceiling(m_maxdata_element); z++)
{
string zvalue = z.ToString();
try
{
float dblzvalue = z * (1F / (float)m_correction_percentage);
zvalue = dblzvalue.ToString("F0");
}
catch (Exception E)
{
Console.WriteLine(E.Message);
}
PointF p = Project(0, 0, z);
graphics.DrawString(zvalue, new Font(FontFamily.GenericSansSerif, 6), Brushes.Black, p);
}
graphics.DrawString("0", new Font(FontFamily.GenericSansSerif, 6), Brushes.Black, Project(0,0,0));
for (int y = 1; y <= m_mapdata.Rows.Count; y++)
{
string yvalue = y.ToString();
try
{
yvalue = y_axisvalues.GetValue((y_axisvalues.Length - 1) - (y-1)).ToString();
}
catch (Exception E)
{
Console.WriteLine(E.Message);
}
PointF p = Project(0, y, -1);
graphics.DrawString(yvalue, new Font(FontFamily.GenericSansSerif, 6), Brushes.Black, p);
}
PointF prev_point = new PointF(0, 0);
for (int r = 0; r < m_mapdata.Rows.Count; r++)
{
try
{
if (prev_point.X != 0 && prev_point.Y != 0)
{
graphics.DrawLine(Pens.MidnightBlue, prev_point, Project(0, (r + 1), Convert.ToDouble(m_mapdata.Rows[r][0])));
prev_point = Project(0, (r + 1), Convert.ToDouble(m_mapdata.Rows[r][0]));
}
else
{
prev_point = Project(0, (r + 1), Convert.ToDouble(m_mapdata.Rows[r][0]));
}
}
catch (Exception E)
{
Console.WriteLine(E.Message);
}
}
}
internal void ClearHighlightInGraph()
{
m_highlighted_x_value = -1;
m_highlighted_y_value = -1;
}
internal void ClearSelectionHighlightInGraph()
{
m_highlightedselection_x_value = -1;
m_highlightedselection_y_value = -1;
}
internal void HighlightInGraph(int x_index, int y_index)
{
m_highlighted_x_value = (x_axisvalues.Length - 1) - x_index;
m_highlighted_y_value = (y_axisvalues.Length - 1) - y_index;
}
internal void HighlightSelectionInGraph(int x_index, int y_index)
{
m_highlightedselection_x_value = (x_axisvalues.Length - 1) - x_index;
m_highlightedselection_y_value = (y_axisvalues.Length - 1) - y_index;
}
}
public delegate double RendererFunction(double x, double y);
public struct Point3D
{
public double x, y, z;
public Point3D(double x, double y, double z)
{
this.x = x;
this.y = y;
this.z = z;
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
// ------------------------------------------------------------------------------
// Changes to this file must follow the http://aka.ms/api-review process.
// ------------------------------------------------------------------------------
namespace System.Reflection
{
public sealed partial class AmbiguousMatchException : System.Exception
{
public AmbiguousMatchException() { }
public AmbiguousMatchException(string message) { }
public AmbiguousMatchException(string message, System.Exception inner) { }
}
public abstract partial class Assembly
{
internal Assembly() { }
public virtual System.Collections.Generic.IEnumerable<System.Reflection.CustomAttributeData> CustomAttributes { get { return default(System.Collections.Generic.IEnumerable<System.Reflection.CustomAttributeData>); } }
public abstract System.Collections.Generic.IEnumerable<System.Reflection.TypeInfo> DefinedTypes { get; }
public virtual System.Collections.Generic.IEnumerable<System.Type> ExportedTypes { get { return default(System.Collections.Generic.IEnumerable<System.Type>); } }
public virtual string FullName { get { return default(string); } }
public virtual bool IsDynamic { get { return default(bool); } }
public virtual System.Reflection.Module ManifestModule { get { return default(System.Reflection.Module); } }
public abstract System.Collections.Generic.IEnumerable<System.Reflection.Module> Modules { get; }
public override bool Equals(object o) { return default(bool); }
public override int GetHashCode() { return default(int); }
public virtual System.Reflection.ManifestResourceInfo GetManifestResourceInfo(string resourceName) { return default(System.Reflection.ManifestResourceInfo); }
public virtual string[] GetManifestResourceNames() { return default(string[]); }
public virtual System.IO.Stream GetManifestResourceStream(string name) { return default(System.IO.Stream); }
public virtual System.Reflection.AssemblyName GetName() { return default(System.Reflection.AssemblyName); }
public virtual System.Type GetType(string name) { return default(System.Type); }
public virtual System.Type GetType(string name, bool throwOnError, bool ignoreCase) { return default(System.Type); }
public static System.Reflection.Assembly Load(System.Reflection.AssemblyName assemblyRef) { return default(System.Reflection.Assembly); }
public virtual string Location { get { return default(string); } }
public override string ToString() { return default(string); }
}
public enum AssemblyContentType
{
Default = 0,
WindowsRuntime = 1,
}
public sealed partial class AssemblyName
{
public AssemblyName() { }
public AssemblyName(string assemblyName) { }
public System.Reflection.AssemblyContentType ContentType { get { return default(System.Reflection.AssemblyContentType); } set { } }
public string CultureName { get { return default(string); } set { } }
public System.Reflection.AssemblyNameFlags Flags { get { return default(System.Reflection.AssemblyNameFlags); } set { } }
public string FullName { get { return default(string); } }
public string Name { get { return default(string); } set { } }
public System.Reflection.ProcessorArchitecture ProcessorArchitecture { get { return default(System.Reflection.ProcessorArchitecture); } set { } }
public System.Version Version { get { return default(System.Version); } set { } }
public byte[] GetPublicKey() { return default(byte[]); }
public byte[] GetPublicKeyToken() { return default(byte[]); }
public void SetPublicKey(byte[] publicKey) { }
public void SetPublicKeyToken(byte[] publicKeyToken) { }
public override string ToString() { return default(string); }
}
public abstract partial class ConstructorInfo : System.Reflection.MethodBase
{
public static readonly string ConstructorName;
public static readonly string TypeConstructorName;
internal ConstructorInfo() { }
public override bool Equals(object obj) { return default(bool); }
public override int GetHashCode() { return default(int); }
public virtual object Invoke(object[] parameters) { return default(object); }
}
public partial class CustomAttributeData
{
internal CustomAttributeData() { }
public virtual System.Type AttributeType { get { return default(System.Type); } }
public virtual System.Collections.Generic.IList<System.Reflection.CustomAttributeTypedArgument> ConstructorArguments { get { return default(System.Collections.Generic.IList<System.Reflection.CustomAttributeTypedArgument>); } }
public virtual System.Collections.Generic.IList<System.Reflection.CustomAttributeNamedArgument> NamedArguments { get { return default(System.Collections.Generic.IList<System.Reflection.CustomAttributeNamedArgument>); } }
}
[System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)]
public partial struct CustomAttributeNamedArgument
{
public bool IsField { get { return default(bool); } }
public string MemberName { get { return default(string); } }
public System.Reflection.CustomAttributeTypedArgument TypedValue { get { return default(System.Reflection.CustomAttributeTypedArgument); } }
}
[System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)]
public partial struct CustomAttributeTypedArgument
{
public System.Type ArgumentType { get { return default(System.Type); } }
public object Value { get { return default(object); } }
}
public abstract partial class EventInfo : System.Reflection.MemberInfo
{
internal EventInfo() { }
public virtual System.Reflection.MethodInfo AddMethod { get { return default(System.Reflection.MethodInfo); } }
public abstract System.Reflection.EventAttributes Attributes { get; }
public virtual System.Type EventHandlerType { get { return default(System.Type); } }
public bool IsSpecialName { get { return default(bool); } }
public virtual System.Reflection.MethodInfo RaiseMethod { get { return default(System.Reflection.MethodInfo); } }
public virtual System.Reflection.MethodInfo RemoveMethod { get { return default(System.Reflection.MethodInfo); } }
public virtual void AddEventHandler(object target, System.Delegate handler) { }
public override bool Equals(object obj) { return default(bool); }
public override int GetHashCode() { return default(int); }
public virtual void RemoveEventHandler(object target, System.Delegate handler) { }
}
public abstract partial class FieldInfo : System.Reflection.MemberInfo
{
internal FieldInfo() { }
public abstract System.Reflection.FieldAttributes Attributes { get; }
public abstract System.Type FieldType { get; }
public bool IsAssembly { get { return default(bool); } }
public bool IsFamily { get { return default(bool); } }
public bool IsFamilyAndAssembly { get { return default(bool); } }
public bool IsFamilyOrAssembly { get { return default(bool); } }
public bool IsInitOnly { get { return default(bool); } }
public bool IsLiteral { get { return default(bool); } }
public bool IsPrivate { get { return default(bool); } }
public bool IsPublic { get { return default(bool); } }
public bool IsSpecialName { get { return default(bool); } }
public bool IsStatic { get { return default(bool); } }
public override bool Equals(object obj) { return default(bool); }
public static System.Reflection.FieldInfo GetFieldFromHandle(System.RuntimeFieldHandle handle) { return default(System.Reflection.FieldInfo); }
public static System.Reflection.FieldInfo GetFieldFromHandle(System.RuntimeFieldHandle handle, System.RuntimeTypeHandle declaringType) { return default(System.Reflection.FieldInfo); }
public override int GetHashCode() { return default(int); }
public abstract object GetValue(object obj);
public virtual void SetValue(object obj, object value) { }
}
public static partial class IntrospectionExtensions
{
public static System.Reflection.TypeInfo GetTypeInfo(this System.Type type) { return default(System.Reflection.TypeInfo); }
}
public partial interface IReflectableType
{
System.Reflection.TypeInfo GetTypeInfo();
}
public partial class LocalVariableInfo
{
protected LocalVariableInfo() { }
public virtual bool IsPinned { get { return default(bool); } }
public virtual int LocalIndex { get { return default(int); } }
public virtual System.Type LocalType { get { return default(System.Type); } }
public override string ToString() { return default(string); }
}
public partial class ManifestResourceInfo
{
public ManifestResourceInfo(System.Reflection.Assembly containingAssembly, string containingFileName, System.Reflection.ResourceLocation resourceLocation) { }
public virtual string FileName { get { return default(string); } }
public virtual System.Reflection.Assembly ReferencedAssembly { get { return default(System.Reflection.Assembly); } }
public virtual System.Reflection.ResourceLocation ResourceLocation { get { return default(System.Reflection.ResourceLocation); } }
}
public abstract partial class MemberInfo
{
internal MemberInfo() { }
public virtual System.Collections.Generic.IEnumerable<System.Reflection.CustomAttributeData> CustomAttributes { get { return default(System.Collections.Generic.IEnumerable<System.Reflection.CustomAttributeData>); } }
public abstract System.Type DeclaringType { get; }
public virtual System.Reflection.Module Module { get { return default(System.Reflection.Module); } }
public abstract string Name { get; }
public override bool Equals(object obj) { return default(bool); }
public override int GetHashCode() { return default(int); }
}
public abstract partial class MethodBase : System.Reflection.MemberInfo
{
internal MethodBase() { }
public abstract System.Reflection.MethodAttributes Attributes { get; }
public virtual System.Reflection.CallingConventions CallingConvention { get { return default(System.Reflection.CallingConventions); } }
public virtual bool ContainsGenericParameters { get { return default(bool); } }
public bool IsAbstract { get { return default(bool); } }
public bool IsAssembly { get { return default(bool); } }
public bool IsConstructor { get { return default(bool); } }
public bool IsFamily { get { return default(bool); } }
public bool IsFamilyAndAssembly { get { return default(bool); } }
public bool IsFamilyOrAssembly { get { return default(bool); } }
public bool IsFinal { get { return default(bool); } }
public virtual bool IsGenericMethod { get { return default(bool); } }
public virtual bool IsGenericMethodDefinition { get { return default(bool); } }
public bool IsHideBySig { get { return default(bool); } }
public bool IsPrivate { get { return default(bool); } }
public bool IsPublic { get { return default(bool); } }
public bool IsSpecialName { get { return default(bool); } }
public bool IsStatic { get { return default(bool); } }
public bool IsVirtual { get { return default(bool); } }
public abstract System.Reflection.MethodImplAttributes MethodImplementationFlags { get; }
public override bool Equals(object obj) { return default(bool); }
public virtual System.Type[] GetGenericArguments() { return default(System.Type[]); }
public override int GetHashCode() { return default(int); }
public static System.Reflection.MethodBase GetMethodFromHandle(System.RuntimeMethodHandle handle) { return default(System.Reflection.MethodBase); }
public static System.Reflection.MethodBase GetMethodFromHandle(System.RuntimeMethodHandle handle, System.RuntimeTypeHandle declaringType) { return default(System.Reflection.MethodBase); }
public abstract System.Reflection.ParameterInfo[] GetParameters();
public virtual object Invoke(object obj, object[] parameters) { return default(object); }
}
public abstract partial class MethodInfo : System.Reflection.MethodBase
{
internal MethodInfo() { }
public virtual System.Reflection.ParameterInfo ReturnParameter { get { return default(System.Reflection.ParameterInfo); } }
public virtual System.Type ReturnType { get { return default(System.Type); } }
public virtual System.Delegate CreateDelegate(System.Type delegateType) { return default(System.Delegate); }
public virtual System.Delegate CreateDelegate(System.Type delegateType, object target) { return default(System.Delegate); }
public override bool Equals(object obj) { return default(bool); }
public override System.Type[] GetGenericArguments() { return default(System.Type[]); }
public virtual System.Reflection.MethodInfo GetGenericMethodDefinition() { return default(System.Reflection.MethodInfo); }
public override int GetHashCode() { return default(int); }
public virtual System.Reflection.MethodInfo MakeGenericMethod(params System.Type[] typeArguments) { return default(System.Reflection.MethodInfo); }
}
public abstract partial class Module
{
internal Module() { }
public virtual System.Reflection.Assembly Assembly { get { return default(System.Reflection.Assembly); } }
public virtual System.Collections.Generic.IEnumerable<System.Reflection.CustomAttributeData> CustomAttributes { get { return default(System.Collections.Generic.IEnumerable<System.Reflection.CustomAttributeData>); } }
public virtual string FullyQualifiedName { get { return default(string); } }
public virtual string Name { get { return default(string); } }
public override bool Equals(object o) { return default(bool); }
public override int GetHashCode() { return default(int); }
public virtual System.Type GetType(string className, bool throwOnError, bool ignoreCase) { return default(System.Type); }
public override string ToString() { return default(string); }
}
public partial class ParameterInfo
{
internal ParameterInfo() { }
public virtual System.Reflection.ParameterAttributes Attributes { get { return default(System.Reflection.ParameterAttributes); } }
public virtual System.Collections.Generic.IEnumerable<System.Reflection.CustomAttributeData> CustomAttributes { get { return default(System.Collections.Generic.IEnumerable<System.Reflection.CustomAttributeData>); } }
public virtual object DefaultValue { get { return default(object); } }
public virtual bool HasDefaultValue { get { return default(bool); } }
public bool IsIn { get { return default(bool); } }
public bool IsOptional { get { return default(bool); } }
public bool IsOut { get { return default(bool); } }
public bool IsRetval { get { return default(bool); } }
public virtual System.Reflection.MemberInfo Member { get { return default(System.Reflection.MemberInfo); } }
public virtual string Name { get { return default(string); } }
public virtual System.Type ParameterType { get { return default(System.Type); } }
public virtual int Position { get { return default(int); } }
}
public abstract partial class PropertyInfo : System.Reflection.MemberInfo
{
internal PropertyInfo() { }
public abstract System.Reflection.PropertyAttributes Attributes { get; }
public abstract bool CanRead { get; }
public abstract bool CanWrite { get; }
public virtual System.Reflection.MethodInfo GetMethod { get { return default(System.Reflection.MethodInfo); } }
public bool IsSpecialName { get { return default(bool); } }
public abstract System.Type PropertyType { get; }
public virtual System.Reflection.MethodInfo SetMethod { get { return default(System.Reflection.MethodInfo); } }
public override bool Equals(object obj) { return default(bool); }
public virtual object GetConstantValue() { return default(object); }
public override int GetHashCode() { return default(int); }
public abstract System.Reflection.ParameterInfo[] GetIndexParameters();
public object GetValue(object obj) { return default(object); }
public virtual object GetValue(object obj, object[] index) { return default(object); }
public void SetValue(object obj, object value) { }
public virtual void SetValue(object obj, object value, object[] index) { }
}
public abstract partial class ReflectionContext
{
protected ReflectionContext() { }
public virtual System.Reflection.TypeInfo GetTypeForObject(object value) { return default(System.Reflection.TypeInfo); }
public abstract System.Reflection.Assembly MapAssembly(System.Reflection.Assembly assembly);
public abstract System.Reflection.TypeInfo MapType(System.Reflection.TypeInfo type);
}
public sealed partial class ReflectionTypeLoadException : System.Exception
{
public ReflectionTypeLoadException(System.Type[] classes, System.Exception[] exceptions) { }
public ReflectionTypeLoadException(System.Type[] classes, System.Exception[] exceptions, string message) { }
public System.Exception[] LoaderExceptions { get { return default(System.Exception[]); } }
public System.Type[] Types { get { return default(System.Type[]); } }
}
[System.FlagsAttribute]
public enum ResourceLocation
{
ContainedInAnotherAssembly = 2,
ContainedInManifestFile = 4,
Embedded = 1,
}
public sealed partial class TargetInvocationException : System.Exception
{
public TargetInvocationException(System.Exception inner) { }
public TargetInvocationException(string message, System.Exception inner) { }
}
public sealed partial class TargetParameterCountException : System.Exception
{
public TargetParameterCountException() { }
public TargetParameterCountException(string message) { }
public TargetParameterCountException(string message, System.Exception inner) { }
}
public abstract partial class TypeInfo : System.Reflection.MemberInfo, System.Reflection.IReflectableType
{
internal TypeInfo() { }
public virtual System.Collections.Generic.IEnumerable<System.Reflection.ConstructorInfo> DeclaredConstructors { get { return default(System.Collections.Generic.IEnumerable<System.Reflection.ConstructorInfo>); } }
public virtual System.Collections.Generic.IEnumerable<System.Reflection.EventInfo> DeclaredEvents { get { return default(System.Collections.Generic.IEnumerable<System.Reflection.EventInfo>); } }
public virtual System.Collections.Generic.IEnumerable<System.Reflection.FieldInfo> DeclaredFields { get { return default(System.Collections.Generic.IEnumerable<System.Reflection.FieldInfo>); } }
public virtual System.Collections.Generic.IEnumerable<System.Reflection.MemberInfo> DeclaredMembers { get { return default(System.Collections.Generic.IEnumerable<System.Reflection.MemberInfo>); } }
public virtual System.Collections.Generic.IEnumerable<System.Reflection.MethodInfo> DeclaredMethods { get { return default(System.Collections.Generic.IEnumerable<System.Reflection.MethodInfo>); } }
public virtual System.Collections.Generic.IEnumerable<System.Reflection.TypeInfo> DeclaredNestedTypes { get { return default(System.Collections.Generic.IEnumerable<System.Reflection.TypeInfo>); } }
public virtual System.Collections.Generic.IEnumerable<System.Reflection.PropertyInfo> DeclaredProperties { get { return default(System.Collections.Generic.IEnumerable<System.Reflection.PropertyInfo>); } }
public virtual System.Type[] GenericTypeParameters { get { return default(System.Type[]); } }
public virtual System.Collections.Generic.IEnumerable<System.Type> ImplementedInterfaces { get { return default(System.Collections.Generic.IEnumerable<System.Type>); } }
public virtual System.Type AsType() { return default(System.Type); }
public virtual System.Reflection.EventInfo GetDeclaredEvent(string name) { return default(System.Reflection.EventInfo); }
public virtual System.Reflection.FieldInfo GetDeclaredField(string name) { return default(System.Reflection.FieldInfo); }
public virtual System.Reflection.MethodInfo GetDeclaredMethod(string name) { return default(System.Reflection.MethodInfo); }
public virtual System.Collections.Generic.IEnumerable<System.Reflection.MethodInfo> GetDeclaredMethods(string name) { return default(System.Collections.Generic.IEnumerable<System.Reflection.MethodInfo>); }
public virtual System.Reflection.TypeInfo GetDeclaredNestedType(string name) { return default(System.Reflection.TypeInfo); }
public virtual System.Reflection.PropertyInfo GetDeclaredProperty(string name) { return default(System.Reflection.PropertyInfo); }
public virtual bool IsAssignableFrom(System.Reflection.TypeInfo typeInfo) { return default(bool); }
System.Reflection.TypeInfo System.Reflection.IReflectableType.GetTypeInfo() { return default(System.Reflection.TypeInfo); }
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Data.SQLite;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Data.Sqlite;
using NUnit.Framework;
using Quartz.Impl;
using Quartz.Impl.Calendar;
using Quartz.Impl.Matchers;
using Quartz.Impl.Triggers;
using Quartz.Job;
using Quartz.Logging;
using Quartz.Simpl;
using Quartz.Spi;
using Quartz.Util;
namespace Quartz.Tests.Integration.Impl.AdoJobStore
{
[TestFixture]
[Category("database")]
public class AdoJobStoreSmokeTest
{
private static readonly Dictionary<string, string> dbConnectionStrings = new Dictionary<string, string>();
private bool clearJobs = true;
private bool scheduleJobs = true;
private ILogProvider oldProvider;
private const string KeyResetEvent = "ResetEvent";
static AdoJobStoreSmokeTest()
{
dbConnectionStrings["Oracle"] = "Data Source=(DESCRIPTION=(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)(HOST=localhost)(PORT=1521)))(CONNECT_DATA=(SERVICE_NAME=xe)));User Id=system;Password=oracle;";
dbConnectionStrings["SQLServer"] = TestConstants.SqlServerConnectionString;
dbConnectionStrings["SQLServerMOT"] = TestConstants.SqlServerConnectionStringMOT;
dbConnectionStrings["MySQL"] = "Server = localhost; Database = quartznet; Uid = quartznet; Pwd = quartznet";
dbConnectionStrings["PostgreSQL"] = "Server=127.0.0.1;Port=5432;Userid=quartznet;Password=quartznet;Pooling=true;MinPoolSize=1;MaxPoolSize=20;Timeout=15;SslMode=Disable;Database=quartznet";
dbConnectionStrings["SQLite"] = "Data Source=test.db;Version=3;";
dbConnectionStrings["SQLite-Microsoft"] = "Data Source=test.db;";
dbConnectionStrings["Firebird"] = "User=SYSDBA;Password=masterkey;Database=/firebird/data/quartz.fdb;DataSource=localhost;Port=3050;Dialect=3;Charset=NONE;Role=;Connection lifetime=15;Pooling=true;MinPoolSize=0;MaxPoolSize=50;Packet Size=8192;ServerType=0;";
}
[OneTimeSetUp]
public void FixtureSetUp()
{
// set Adapter to report problems
oldProvider = (ILogProvider) typeof(LogProvider).GetField("s_currentLogProvider", BindingFlags.NonPublic | BindingFlags.Static).GetValue(null);
LogProvider.SetCurrentLogProvider(new FailFastLoggerFactoryAdapter());
}
[OneTimeTearDown]
public void FixtureTearDown()
{
// default back to old
LogProvider.SetCurrentLogProvider(oldProvider);
}
[Test]
[Category("sqlserver")]
[TestCaseSource(nameof(GetSerializerTypes))]
public Task TestSqlServer(string serializerType)
{
var properties = new NameValueCollection
{
["quartz.jobStore.driverDelegateType"] = typeof(Quartz.Impl.AdoJobStore.SqlServerDelegate).AssemblyQualifiedNameWithoutVersion()
};
return RunAdoJobStoreTest(TestConstants.DefaultSqlServerProvider, "SQLServer", serializerType, properties);
}
[Test]
[Category("sqlserver")]
[TestCaseSource(nameof(GetSerializerTypes))]
public Task TestSqlServerMemoryOptimizedTables(string serializerType)
{
var properties = new NameValueCollection
{
["quartz.jobStore.driverDelegateType"] = typeof(Quartz.Impl.AdoJobStore.SqlServerDelegate).AssemblyQualifiedNameWithoutVersion(),
["quartz.jobStore.lockHandler.type"] = typeof(Quartz.Impl.AdoJobStore.UpdateLockRowSemaphoreMOT).AssemblyQualifiedNameWithoutVersion()
};
return RunAdoJobStoreTest(TestConstants.DefaultSqlServerProvider, "SQLServerMOT", serializerType, properties);
}
[Test]
[TestCaseSource(nameof(GetSerializerTypes))]
public Task TestPostgreSql(string serializerType)
{
NameValueCollection properties = new NameValueCollection();
properties["quartz.jobStore.driverDelegateType"] = "Quartz.Impl.AdoJobStore.PostgreSQLDelegate, Quartz";
return RunAdoJobStoreTest("Npgsql", "PostgreSQL", serializerType, properties);
}
[Test]
[TestCaseSource(nameof(GetSerializerTypes))]
public Task TestMySql(string serializerType)
{
NameValueCollection properties = new NameValueCollection();
properties["quartz.jobStore.driverDelegateType"] = "Quartz.Impl.AdoJobStore.MySQLDelegate, Quartz";
return RunAdoJobStoreTest("MySqlConnector", "MySQL", serializerType, properties);
}
[Test]
[TestCaseSource(nameof(GetSerializerTypes))]
public async Task TestSQLiteMicrosoft(string serializerType)
{
var dbFilename = $"test-{serializerType}.db";
if (File.Exists(dbFilename))
{
File.Delete(dbFilename);
}
using (var connection = new SqliteConnection(dbConnectionStrings["SQLite-Microsoft"]))
{
await connection.OpenAsync();
string sql = File.ReadAllText("../../../../database/tables/tables_sqlite.sql");
var command = new SqliteCommand(sql, connection);
command.ExecuteNonQuery();
connection.Close();
}
NameValueCollection properties = new NameValueCollection();
properties["quartz.jobStore.driverDelegateType"] = "Quartz.Impl.AdoJobStore.SQLiteDelegate, Quartz";
await RunAdoJobStoreTest("SQLite-Microsoft", "SQLite-Microsoft", serializerType, properties, clustered: false);
}
[Test]
[TestCaseSource(nameof(GetSerializerTypes))]
public Task TestFirebird(string serializerType)
{
NameValueCollection properties = new NameValueCollection();
properties["quartz.jobStore.driverDelegateType"] = "Quartz.Impl.AdoJobStore.FirebirdDelegate, Quartz";
return RunAdoJobStoreTest("Firebird", "Firebird", serializerType, properties);
}
[Test]
[TestCaseSource(nameof(GetSerializerTypes))]
public Task TestOracleODPManaged(string serializerType)
{
NameValueCollection properties = new NameValueCollection();
properties["quartz.jobStore.driverDelegateType"] = "Quartz.Impl.AdoJobStore.OracleDelegate, Quartz";
return RunAdoJobStoreTest("OracleODPManaged", "Oracle", serializerType, properties);
}
[Test]
[TestCaseSource(nameof(GetSerializerTypes))]
public async Task TestSQLite(string serializerType)
{
var dbFilename = $"test-{serializerType}.db";
while (File.Exists(dbFilename))
{
File.Delete(dbFilename);
}
SQLiteConnection.CreateFile(dbFilename);
using (var connection = new SQLiteConnection(dbConnectionStrings["SQLite"]))
{
await connection.OpenAsync();
string sql = File.ReadAllText("../../../../database/tables/tables_sqlite.sql");
var command = new SQLiteCommand(sql, connection);
command.ExecuteNonQuery();
connection.Close();
}
NameValueCollection properties = new NameValueCollection();
properties["quartz.jobStore.driverDelegateType"] = "Quartz.Impl.AdoJobStore.SQLiteDelegate, Quartz";
await RunAdoJobStoreTest("SQLite", "SQLite", serializerType, properties, clustered: false);
}
public static string[] GetSerializerTypes() => new[] {"json", "binary"};
private Task RunAdoJobStoreTest(string dbProvider, string connectionStringId, string serializerType)
{
return RunAdoJobStoreTest(dbProvider, connectionStringId, serializerType, null);
}
private async Task RunAdoJobStoreTest(
string dbProvider,
string connectionStringId,
string serializerType,
NameValueCollection extraProperties,
bool clustered = true)
{
var config = SchedulerBuilder.Create("instance_one", "TestScheduler");
config.UseDefaultThreadPool(x =>
{
x.MaxConcurrency = 10;
});
config.MisfireThreshold = TimeSpan.FromSeconds(60);
config.UsePersistentStore(store =>
{
store.UseProperties = false;
if (clustered)
{
store.UseClustering(c =>
{
c.CheckinInterval = TimeSpan.FromMilliseconds(1000);
});
}
store.UseGenericDatabase(dbProvider, db =>
db.ConnectionString = dbConnectionStrings[connectionStringId]
);
if (serializerType == "json")
{
store.UseJsonSerializer(j =>
{
j.AddCalendarSerializer<CustomCalendar>(new CustomCalendarSerializer());
});
}
else
{
store.UseBinarySerializer();
}
});
if (extraProperties != null)
{
foreach (string key in extraProperties.Keys)
{
config.SetProperty(key, extraProperties[key]);
}
}
// Clear any old errors from the log
FailFastLoggerFactoryAdapter.Errors.Clear();
// First we must get a reference to a scheduler
IScheduler sched = await config.BuildScheduler();
SmokeTestPerformer performer = new SmokeTestPerformer();
await performer.Test(sched, clearJobs, scheduleJobs);
Assert.IsEmpty(FailFastLoggerFactoryAdapter.Errors, "Found error from logging output");
}
[Test]
[Category("sqlserver")]
public async Task ShouldBeAbleToUseMixedProperties()
{
NameValueCollection properties = new NameValueCollection();
properties["quartz.jobStore.type"] = "Quartz.Impl.AdoJobStore.JobStoreTX, Quartz";
properties["quartz.jobStore.driverDelegateType"] = "Quartz.Impl.AdoJobStore.StdAdoDelegate, Quartz";
properties["quartz.jobStore.dataSource"] = "default";
properties["quartz.jobStore.useProperties"] = false.ToString();
properties["quartz.serializer.type"] = TestConstants.DefaultSerializerType;
dbConnectionStrings.TryGetValue("SQLServer", out var connectionString);
properties["quartz.dataSource.default.connectionString"] = connectionString;
properties["quartz.dataSource.default.provider"] = TestConstants.DefaultSqlServerProvider;
ISchedulerFactory sf = new StdSchedulerFactory(properties);
IScheduler sched = await sf.GetScheduler();
await sched.Clear();
JobDetailImpl jobWithData = new JobDetailImpl("datajob", "jobgroup", typeof(NoOpJob));
jobWithData.JobDataMap["testkey"] = "testvalue";
IOperableTrigger triggerWithData = new SimpleTriggerImpl("datatrigger", "triggergroup", 20, TimeSpan.FromSeconds(5));
triggerWithData.JobDataMap.Add("testkey", "testvalue");
triggerWithData.EndTimeUtc = DateTime.UtcNow.AddYears(10);
triggerWithData.StartTimeUtc = DateTime.Now.AddMilliseconds(1000L);
await sched.ScheduleJob(jobWithData, triggerWithData);
await sched.Shutdown();
// try again with changing the useproperties against same set of data
properties["quartz.jobStore.useProperties"] = true.ToString();
sf = new StdSchedulerFactory(properties);
sched = await sf.GetScheduler();
var triggerWithDataFromDb = await sched.GetTrigger(new TriggerKey("datatrigger", "triggergroup"));
var jobWithDataFromDb = await sched.GetJobDetail(new JobKey("datajob", "jobgroup"));
Assert.That(triggerWithDataFromDb.JobDataMap["testkey"], Is.EqualTo("testvalue"));
Assert.That(jobWithDataFromDb.JobDataMap["testkey"], Is.EqualTo("testvalue"));
// once more
await sched.DeleteJob(jobWithData.Key);
await sched.ScheduleJob(jobWithData, triggerWithData);
await sched.Shutdown();
properties["quartz.jobStore.useProperties"] = false.ToString();
sf = new StdSchedulerFactory(properties);
sched = await sf.GetScheduler();
triggerWithDataFromDb = await sched.GetTrigger(new TriggerKey("datatrigger", "triggergroup"));
jobWithDataFromDb = await sched.GetJobDetail(new JobKey("datajob", "jobgroup"));
Assert.That(triggerWithDataFromDb.JobDataMap["testkey"], Is.EqualTo("testvalue"));
Assert.That(jobWithDataFromDb.JobDataMap["testkey"], Is.EqualTo("testvalue"));
}
[Test]
[Explicit]
[TestCaseSource(nameof(GetSerializerTypes))]
public async Task TestSqlServerStress(string serializerType)
{
NameValueCollection properties = new NameValueCollection();
properties["quartz.scheduler.instanceName"] = "TestScheduler";
properties["quartz.scheduler.instanceId"] = "instance_one";
properties["quartz.serializer.type"] = TestConstants.DefaultSerializerType;
properties["quartz.jobStore.type"] = "Quartz.Impl.AdoJobStore.JobStoreTX, Quartz";
properties["quartz.jobStore.useProperties"] = "false";
properties["quartz.jobStore.dataSource"] = "default";
properties["quartz.jobStore.tablePrefix"] = "QRTZ_";
properties["quartz.jobStore.clustered"] = true.ToString();
properties["quartz.jobStore.driverDelegateType"] = "Quartz.Impl.AdoJobStore.SqlServerDelegate, Quartz";
await RunAdoJobStoreTest(TestConstants.DefaultSqlServerProvider, "SQLServer", serializerType, properties);
if (!dbConnectionStrings.TryGetValue("SQLServer", out var connectionString))
{
throw new Exception("Unknown connection string id: " + "SQLServer");
}
properties["quartz.dataSource.default.connectionString"] = connectionString;
properties["quartz.dataSource.default.provider"] = TestConstants.DefaultSqlServerProvider;
// First we must get a reference to a scheduler
ISchedulerFactory sf = new StdSchedulerFactory(properties);
IScheduler sched = await sf.GetScheduler();
try
{
await sched.Clear();
if (scheduleJobs)
{
ICalendar cronCalendar = new CronCalendar("0/5 * * * * ?");
ICalendar holidayCalendar = new HolidayCalendar();
for (int i = 0; i < 100000; ++i)
{
ITrigger trigger = new SimpleTriggerImpl("calendarsTrigger", "test", SimpleTriggerImpl.RepeatIndefinitely, TimeSpan.FromSeconds(1));
JobDetailImpl jd = new JobDetailImpl("testJob", "test", typeof(NoOpJob));
await sched.ScheduleJob(jd, trigger);
}
}
await sched.Start();
await Task.Delay(TimeSpan.FromSeconds(30));
}
finally
{
await sched.Shutdown(false);
}
}
[Test]
[Category("sqlserver")]
public async Task TestGetTriggerKeysWithLike()
{
var sched = await CreateScheduler(null);
await sched.GetTriggerKeys(GroupMatcher<TriggerKey>.GroupStartsWith("foo"));
}
[Test]
[Category("sqlserver")]
public async Task TestGetTriggerKeysWithEquals()
{
var sched = await CreateScheduler(null);
await sched.GetTriggerKeys(GroupMatcher<TriggerKey>.GroupEquals("bar"));
}
[Test]
[Category("sqlserver")]
public async Task TestGetJobKeysWithLike()
{
var sched = await CreateScheduler(null);
await sched.GetJobKeys(GroupMatcher<JobKey>.GroupStartsWith("foo"));
}
[Test]
[Category("sqlserver")]
public async Task TestGetJobKeysWithEquals()
{
var sched = await CreateScheduler(null);
await sched.GetJobKeys(GroupMatcher<JobKey>.GroupEquals("bar"));
}
[Test]
[Category("sqlserver")]
public async Task JobTypeNotFoundShouldNotBlock()
{
NameValueCollection properties = new NameValueCollection();
properties.Add(StdSchedulerFactory.PropertySchedulerTypeLoadHelperType, typeof(SpecialClassLoadHelper).AssemblyQualifiedName);
var scheduler = await CreateScheduler(properties);
await scheduler.DeleteJobs(new[] {JobKey.Create("bad"), JobKey.Create("good")});
await scheduler.Start();
var manualResetEvent = new ManualResetEventSlim(false);
scheduler.Context.Put(KeyResetEvent, manualResetEvent);
IJobDetail goodJob = JobBuilder.Create<GoodJob>().WithIdentity("good").Build();
IJobDetail badJob = JobBuilder.Create<BadJob>().WithIdentity("bad").Build();
var now = DateTimeOffset.UtcNow;
ITrigger goodTrigger = TriggerBuilder.Create().WithIdentity("good").ForJob(goodJob)
.StartAt(now.AddMilliseconds(1))
.Build();
ITrigger badTrigger = TriggerBuilder.Create().WithIdentity("bad").ForJob(badJob)
.StartAt(now)
.Build();
var toSchedule = new Dictionary<IJobDetail, IReadOnlyCollection<ITrigger>>();
toSchedule.Add(badJob, new List<ITrigger>
{
badTrigger
});
toSchedule.Add(goodJob, new List<ITrigger>
{
goodTrigger
});
await scheduler.ScheduleJobs(toSchedule, true);
manualResetEvent.Wait(TimeSpan.FromSeconds(20));
Assert.That(await scheduler.GetTriggerState(badTrigger.Key), Is.EqualTo(TriggerState.Error));
}
private static async Task<IScheduler> CreateScheduler(NameValueCollection properties)
{
properties ??= new NameValueCollection();
properties["quartz.scheduler.instanceName"] = "TestScheduler";
properties["quartz.scheduler.instanceId"] = "instance_one";
properties["quartz.serializer.type"] = TestConstants.DefaultSerializerType;
properties["quartz.jobStore.type"] = "Quartz.Impl.AdoJobStore.JobStoreTX, Quartz";
properties["quartz.jobStore.useProperties"] = "false";
properties["quartz.jobStore.dataSource"] = "default";
properties["quartz.jobStore.tablePrefix"] = "QRTZ_";
properties["quartz.jobStore.clustered"] = "false";
properties["quartz.jobStore.driverDelegateType"] = "Quartz.Impl.AdoJobStore.SqlServerDelegate, Quartz";
properties["quartz.dataSource.default.connectionString"] = TestConstants.SqlServerConnectionString;
properties["quartz.dataSource.default.provider"] = TestConstants.DefaultSqlServerProvider;
// First we must get a reference to a scheduler
ISchedulerFactory sf = new StdSchedulerFactory(properties);
IScheduler sched = await sf.GetScheduler();
return sched;
}
[Test]
[Explicit]
public async Task StressTest()
{
NameValueCollection properties = new NameValueCollection();
properties["quartz.scheduler.instanceName"] = "TestScheduler";
properties["quartz.scheduler.instanceId"] = "instance_one";
properties["quartz.serializer.type"] = TestConstants.DefaultSerializerType;
properties["quartz.jobStore.misfireThreshold"] = "60000";
properties["quartz.jobStore.type"] = "Quartz.Impl.AdoJobStore.JobStoreTX, Quartz";
properties["quartz.jobStore.useProperties"] = "false";
properties["quartz.jobStore.dataSource"] = "default";
properties["quartz.jobStore.tablePrefix"] = "QRTZ_";
properties["quartz.jobStore.clustered"] = "false";
properties["quartz.jobStore.driverDelegateType"] = "Quartz.Impl.AdoJobStore.SqlServerDelegate, Quartz";
properties["quartz.dataSource.default.connectionString"] = TestConstants.SqlServerConnectionString;
properties["quartz.dataSource.default.provider"] = TestConstants.DefaultSqlServerProvider;
// First we must get a reference to a scheduler
ISchedulerFactory sf = new StdSchedulerFactory(properties);
IScheduler sched = await sf.GetScheduler();
try
{
await sched.Clear();
JobDetailImpl lonelyJob = new JobDetailImpl("lonelyJob", "lonelyGroup", typeof(SimpleRecoveryJob));
lonelyJob.Durable = true;
lonelyJob.RequestsRecovery = true;
await sched.AddJob(lonelyJob, false);
await sched.AddJob(lonelyJob, true);
string schedId = sched.SchedulerInstanceId;
JobDetailImpl job = new JobDetailImpl("job_to_use", schedId, typeof(SimpleRecoveryJob));
for (int i = 0; i < 100000; ++i)
{
IOperableTrigger trigger = new SimpleTriggerImpl("stressing_simple", SimpleTriggerImpl.RepeatIndefinitely, TimeSpan.FromSeconds(1));
trigger.StartTimeUtc = DateTime.Now.AddMilliseconds(i);
await sched.ScheduleJob(job, trigger);
}
for (int i = 0; i < 100000; ++i)
{
IOperableTrigger ct = new CronTriggerImpl("stressing_cron", "0/1 * * * * ?");
ct.StartTimeUtc = DateTime.Now.AddMilliseconds(i);
await sched.ScheduleJob(job, ct);
}
Stopwatch stopwatch = new Stopwatch();
stopwatch.Start();
await sched.Start();
await Task.Delay(TimeSpan.FromMinutes(3));
stopwatch.Stop();
Console.WriteLine("Took: " + stopwatch.Elapsed);
}
finally
{
await sched.Shutdown(false);
}
}
public class BadJob : IJob
{
public Task Execute(IJobExecutionContext context)
{
return Task.CompletedTask;
}
}
public class GoodJob : IJob
{
public Task Execute(IJobExecutionContext context)
{
try
{
((ManualResetEventSlim) context.Scheduler.Context.Get(KeyResetEvent)).Wait(TimeSpan.FromSeconds(20));
return Task.CompletedTask;
}
catch (SchedulerException ex)
{
throw new JobExecutionException(ex);
}
catch (ThreadInterruptedException ex)
{
throw new JobExecutionException(ex);
}
catch (TimeoutException ex)
{
throw new JobExecutionException(ex);
}
}
}
public class SpecialClassLoadHelper : SimpleTypeLoadHelper
{
public override Type LoadType(string name)
{
if (!string.IsNullOrEmpty(name) && typeof(BadJob) == Type.GetType(name))
{
throw new TypeLoadException();
}
return base.LoadType(name);
}
}
}
public class SimpleRecoveryJob : IJob
{
private const string Count = "count";
/// <summary>
/// Called by the <see cref="IScheduler" /> when a
/// <see cref="ITrigger" /> fires that is associated with
/// the <see cref="IJob" />.
/// </summary>
public virtual async Task Execute(IJobExecutionContext context)
{
// delay for ten seconds
await Task.Delay(TimeSpan.FromSeconds(10));
JobDataMap data = context.JobDetail.JobDataMap;
int count;
if (data.ContainsKey(Count))
{
count = data.GetInt(Count);
}
else
{
count = 0;
}
count++;
data.Put(Count, count);
}
}
[DisallowConcurrentExecution]
[PersistJobDataAfterExecution]
public class SimpleRecoveryStatefulJob : SimpleRecoveryJob
{
}
}
| |
// 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.Runtime.InteropServices;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using Microsoft.Win32.SafeHandles;
internal static partial class Interop
{
internal static partial class Crypto
{
internal delegate int X509StoreVerifyCallback(int ok, IntPtr ctx);
[DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_GetX509EvpPublicKey")]
internal static extern SafeEvpPKeyHandle GetX509EvpPublicKey(SafeX509Handle x509);
[DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_DecodeX509Crl")]
internal static extern SafeX509CrlHandle DecodeX509Crl(byte[] buf, int len);
[DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_DecodeX509")]
internal static extern SafeX509Handle DecodeX509(byte[] buf, int len);
[DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_GetX509DerSize")]
internal static extern int GetX509DerSize(SafeX509Handle x);
[DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_EncodeX509")]
internal static extern int EncodeX509(SafeX509Handle x, byte[] buf);
[DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_X509Destroy")]
internal static extern void X509Destroy(IntPtr a);
/// <summary>
/// Clone the input certificate into a new object.
/// </summary>
[DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_X509Duplicate")]
internal static extern SafeX509Handle X509Duplicate(IntPtr handle);
/// <summary>
/// Clone the input certificate into a new object.
/// </summary>
[DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_X509Duplicate")]
internal static extern SafeX509Handle X509Duplicate(SafeX509Handle handle);
/// <summary>
/// Increment the native reference count of the certificate to protect against
/// a free from another pointer-holder.
/// </summary>
[DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_X509UpRef")]
internal static extern SafeX509Handle X509UpRef(IntPtr handle);
/// <summary>
/// Increment the native reference count of the certificate to protect against
/// a free from another pointer-holder.
/// </summary>
[DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_X509UpRef")]
internal static extern SafeX509Handle X509UpRef(SafeX509Handle handle);
[DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_PemReadX509FromBio")]
internal static extern SafeX509Handle PemReadX509FromBio(SafeBioHandle bio);
[DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_X509GetSerialNumber")]
private static extern SafeSharedAsn1IntegerHandle X509GetSerialNumber_private(SafeX509Handle x);
internal static SafeSharedAsn1IntegerHandle X509GetSerialNumber(SafeX509Handle x)
{
CheckValidOpenSslHandle(x);
return SafeInteriorHandle.OpenInteriorHandle(
handle => X509GetSerialNumber_private(handle),
x);
}
[DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_X509GetIssuerName")]
internal static extern IntPtr X509GetIssuerName(SafeX509Handle x);
[DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_X509GetSubjectName")]
internal static extern IntPtr X509GetSubjectName(SafeX509Handle x);
[DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_X509CheckPurpose")]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool X509CheckPurpose(SafeX509Handle x, int id, int ca);
[DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_X509CheckIssued")]
internal static extern int X509CheckIssued(SafeX509Handle issuer, SafeX509Handle subject);
[DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_X509IssuerNameHash")]
internal static extern ulong X509IssuerNameHash(SafeX509Handle x);
[DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_X509GetExtCount")]
internal static extern int X509GetExtCount(SafeX509Handle x);
// Returns a pointer already being tracked by the SafeX509Handle, shouldn't be SafeHandle tracked/freed.
// Bounds checking is in place for "loc", IntPtr.Zero is returned on violations.
[DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_X509GetExt")]
internal static extern IntPtr X509GetExt(SafeX509Handle x, int loc);
// Returns a pointer already being tracked by a SafeX509Handle, shouldn't be SafeHandle tracked/freed.
[DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_X509ExtensionGetOid")]
internal static extern IntPtr X509ExtensionGetOid(IntPtr ex);
// Returns a pointer already being tracked by a SafeX509Handle, shouldn't be SafeHandle tracked/freed.
[DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_X509ExtensionGetData")]
internal static extern IntPtr X509ExtensionGetData(IntPtr ex);
[DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_X509ExtensionGetCritical")]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool X509ExtensionGetCritical(IntPtr ex);
[DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_X509StoreCreate")]
internal static extern SafeX509StoreHandle X509StoreCreate();
[DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_X509StoreDestory")]
internal static extern void X509StoreDestory(IntPtr v);
[DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_X509StoreAddCert")]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool X509StoreAddCert(SafeX509StoreHandle ctx, SafeX509Handle x);
[DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_X509StoreAddCrl")]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool X509StoreAddCrl(SafeX509StoreHandle ctx, SafeX509CrlHandle x);
[DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_X509StoreSetRevocationFlag")]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool X509StoreSetRevocationFlag(SafeX509StoreHandle ctx, X509RevocationFlag revocationFlag);
[DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_X509StoreCtxInit")]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool X509StoreCtxInit(
SafeX509StoreCtxHandle ctx,
SafeX509StoreHandle store,
SafeX509Handle x509,
SafeX509StackHandle extraCerts);
[DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_X509VerifyCert")]
internal static extern int X509VerifyCert(SafeX509StoreCtxHandle ctx);
[DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_X509StoreCtxGetError")]
internal static extern X509VerifyStatusCode X509StoreCtxGetError(SafeX509StoreCtxHandle ctx);
[DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_X509StoreCtxGetErrorDepth")]
internal static extern int X509StoreCtxGetErrorDepth(SafeX509StoreCtxHandle ctx);
[DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_X509StoreCtxSetVerifyCallback")]
internal static extern void X509StoreCtxSetVerifyCallback(SafeX509StoreCtxHandle ctx, X509StoreVerifyCallback callback);
internal static string GetX509VerifyCertErrorString(X509VerifyStatusCode n)
{
return Marshal.PtrToStringAnsi(X509VerifyCertErrorString(n));
}
[DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_X509VerifyCertErrorString")]
private static extern IntPtr X509VerifyCertErrorString(X509VerifyStatusCode n);
[DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_X509CrlDestroy")]
internal static extern void X509CrlDestroy(IntPtr a);
[DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_PemWriteBioX509Crl")]
internal static extern int PemWriteBioX509Crl(SafeBioHandle bio, SafeX509CrlHandle crl);
[DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_PemReadBioX509Crl")]
internal static extern SafeX509CrlHandle PemReadBioX509Crl(SafeBioHandle bio);
[DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_GetX509SubjectPublicKeyInfoDerSize")]
internal static extern int GetX509SubjectPublicKeyInfoDerSize(SafeX509Handle x509);
[DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_EncodeX509SubjectPublicKeyInfo")]
internal static extern int EncodeX509SubjectPublicKeyInfo(SafeX509Handle x509, byte[] buf);
internal enum X509VerifyStatusCode : int
{
X509_V_OK = 0,
X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT = 2,
X509_V_ERR_UNABLE_TO_GET_CRL = 3,
X509_V_ERR_UNABLE_TO_DECRYPT_CRL_SIGNATURE = 5,
X509_V_ERR_UNABLE_TO_DECODE_ISSUER_PUBLIC_KEY = 6,
X509_V_ERR_CERT_SIGNATURE_FAILURE = 7,
X509_V_ERR_CRL_SIGNATURE_FAILURE = 8,
X509_V_ERR_CERT_NOT_YET_VALID = 9,
X509_V_ERR_CERT_HAS_EXPIRED = 10,
X509_V_ERR_CRL_NOT_YET_VALID = 11,
X509_V_ERR_CRL_HAS_EXPIRED = 12,
X509_V_ERR_ERROR_IN_CERT_NOT_BEFORE_FIELD = 13,
X509_V_ERR_ERROR_IN_CERT_NOT_AFTER_FIELD = 14,
X509_V_ERR_ERROR_IN_CRL_LAST_UPDATE_FIELD = 15,
X509_V_ERR_ERROR_IN_CRL_NEXT_UPDATE_FIELD = 16,
X509_V_ERR_OUT_OF_MEM = 17,
X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT = 18,
X509_V_ERR_SELF_SIGNED_CERT_IN_CHAIN = 19,
X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT_LOCALLY = 20,
X509_V_ERR_UNABLE_TO_VERIFY_LEAF_SIGNATURE = 21,
X509_V_ERR_CERT_CHAIN_TOO_LONG = 22,
X509_V_ERR_CERT_REVOKED = 23,
X509_V_ERR_INVALID_CA = 24,
X509_V_ERR_PATH_LENGTH_EXCEEDED = 25,
X509_V_ERR_INVALID_PURPOSE = 26,
X509_V_ERR_CERT_UNTRUSTED = 27,
X509_V_ERR_CERT_REJECTED = 28,
X509_V_ERR_KEYUSAGE_NO_CERTSIGN = 32,
X509_V_ERR_UNABLE_TO_GET_CRL_ISSUER = 33,
X509_V_ERR_UNHANDLED_CRITICAL_EXTENSION = 34,
X509_V_ERR_KEYUSAGE_NO_CRL_SIGN = 35,
X509_V_ERR_UNHANDLED_CRITICAL_CRL_EXTENSION = 36,
X509_V_ERR_INVALID_NON_CA = 37,
X509_V_ERR_KEYUSAGE_NO_DIGITAL_SIGNATURE = 39,
X509_V_ERR_INVALID_EXTENSION = 41,
X509_V_ERR_INVALID_POLICY_EXTENSION = 42,
X509_V_ERR_NO_EXPLICIT_POLICY = 43,
}
}
}
| |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Histacom2.Engine;
using System.Threading;
using System.Media;
using System.IO;
using Histacom2.Engine.Template;
namespace Histacom2.OS.Win95.Win95Apps
{
public partial class WebChat1998 : UserControl
{
int chat_index = 0;
WindowManager wm = new WindowManager();
MessageParser wcmp = new MessageParser();
bool correctname = false;
bool guessing = false;
bool msgsound = true;
bool wimponclose = false;
SoundPlayer join = new SoundPlayer(Properties.Resources.AIMbuddyjoin);
SoundPlayer leave = new SoundPlayer(Properties.Resources.AIMbuddyleave);
SoundPlayer send = new SoundPlayer(Properties.Resources.AIMmessagesent);
SoundPlayer receive = new SoundPlayer(Properties.Resources.AIMmessagereceived);
SoundPlayer file = new SoundPlayer(Properties.Resources.AIMfile);
BSODCreator bc = new BSODCreator();
Win9XBSOD bsod = null;
public WebChat1998()
{
InitializeComponent();
bsod = bc.throw9XBSOD(false, BSODCreator.BSODCauses.WimpEnding);
bsod.Hide();
textBox1.Text = "If you do not agree to the following rules below DO NOT log into the chat:\n\nNo Bullying\nNo Swearing\nNo Hacking\nNo Illegal Files / Piracy\n\nFailure to follow these rules will result in serious irreversible consequences.";
}
private void WebChat1998_Load(object sender, EventArgs e)
{
button5.Hide();
button4.Hide();
button3.Hide();
label5.Hide();
}
private void Button1_Click(object sender, EventArgs e)
{
if (txtscreenname.Text == "") { wm.StartInfobox95("Invalid Username", "Your username cannot be blank.", InfoboxType.Warning, InfoboxButtons.OK); return; }
if (txtscreenname.Text.Length > 12) { wm.StartInfobox95("Invalid Username", "Your username needs to be less than 12 characters.", InfoboxType.Warning, InfoboxButtons.OK); return; }
if (txtscreenname.Text.Contains(" ")) { wm.StartInfobox95("Invalid Username", "Your username cannot contain spaces.", InfoboxType.Warning, InfoboxButtons.OK); return; }
if (txtscreenname.Text == "SkyHigh" | txtscreenname.Text == "rain49" | txtscreenname.Text == "12padams") { wm.StartInfobox95("Invalid Username", "That username is already taken.", InfoboxType.Warning, InfoboxButtons.OK); return; }
ParentForm.AcceptButton = button2;
TitleScreen.username = txtscreenname.Text;
login.Hide();
listBox1.Items.Add(TitleScreen.username);
history.AppendText("System: " + TitleScreen.username + " has joined the chat." + Environment.NewLine);
join.Play();
if (TitleScreen.username == "devspeed") Chat.Interval = 100;
Chat.Start();
}
private void Chat_Tick(object sender, EventArgs e)
{
if (!guessing)
{
if (history.ScrollBars != ScrollBars.None) history.AppendText(wcmp.ParseMessage(Properties.Resources.webchat1998_convo, chat_index, TitleScreen.username));
else history.Text = wcmp.ParseMessage(Properties.Resources.webchat1998_convo, chat_index, TitleScreen.username);
switch (wcmp.GetSpecial(Properties.Resources.webchat1998_convo, chat_index))
{
case "addsh":
listBox1.Items.Add("SkyHigh");
join.Play();
this.ParentForm.FormClosing += WebChatClosing;
wimponclose = true;
break;
case "nameguess":
typechat.Hide();
button2.Hide();
button3.Show();
button4.Show();
Chat.Stop();
guessing = true;
receive.Play();
break;
case "addrain":
listBox1.Items.Add("rain49");
join.Play();
break;
case "addfile":
label5.Show();
button5.Show();
file.Play();
break;
case "addpadams":
listBox1.Items.Add("12padams");
join.Play();
((WinClassic)this.ParentForm).closeDisabled = true;
TitleScreen.frm95.startbutton.Enabled = false;
TitleScreen.frm95.startmenu.Hide();
break;
case "nostart":
TitleScreen.frm95.startbutton.Hide();
TitleScreen.frm95.startmenu.Hide();
receive.Play();
break;
case "removerain":
listBox1.Items.Remove("rain49");
leave.Play();
break;
case "iconsded":
TitleScreen.frm95.desktopicons.Enabled = false;
receive.Play();
break;
case "taskbarded":
TitleScreen.frm95.taskbar.Hide();
receive.Play();
break;
case "iconsgone":
TitleScreen.frm95.desktopicons.Hide();
receive.Play();
break;
case "bigtext":
history.Font = new Font("Arial", 12F, FontStyle.Regular, GraphicsUnit.Point, ((0)));
((WinClassic)this.ParentForm).maximizebutton.Enabled = false;
((WinClassic)this.ParentForm).WindowState = FormWindowState.Maximized;
((WinClassic)this.ParentForm).right.Hide();
((WinClassic)this.ParentForm).left.Hide();
((WinClassic)this.ParentForm).bottom.Hide();
((WinClassic)this.ParentForm).top.Hide();
((WinClassic)this.ParentForm).bottomleftcorner.Hide();
((WinClassic)this.ParentForm).bottomrightcorner.Hide();
((WinClassic)this.ParentForm).topleftcorner.Hide();
((WinClassic)this.ParentForm).toprightcorner.Hide();
((WinClassic)this.ParentForm).Dock = DockStyle.Fill;
((WinClassic)this.ParentForm).max = true;
((WinClassic)this.ParentForm).maximizebutton.Image = Engine.Properties.Resources.WinClassicRestore;
receive.Play();
break;
case "notopbar":
((WinClassic)this.ParentForm).programtopbar.Hide();
receive.Play();
break;
case "filepoof":
label5.Hide();
button5.Hide();
receive.Play();
break;
case "removesky":
listBox1.Items.Remove("SkyHigh");
leave.Play();
break;
case "notype":
typechat.Hide();
button2.Hide();
receive.Play();
break;
case ".labelgone":
label1.Hide();
label6.Hide();
label7.Hide();
break;
case ".blackout":
BackColor = Color.Black;
history.BackColor = Color.Black;
history.ForeColor = Color.White;
break;
case "nosound":
msgsound = false;
break;
case ".fulltext":
foreach (Control c in ((WinClassic)this.ParentForm).program.Controls)
{
if (c.Name != "programContent")
{
c.Hide();
((WinClassic)this.ParentForm).program.Controls.Remove(c);
}
}
((WinClassic)this.ParentForm).programContent.Location = new Point(0, 0);
((WinClassic)this.ParentForm).programContent.Size = ((WinClassic)this.ParentForm).ClientSize;
panel1.Hide();
history.Dock = DockStyle.Fill;
break;
case "noscroll":
history.ScrollBars = ScrollBars.None;
break;
case "nomouse":
Cursor.Hide();
break;
case "type":
history.ReadOnly = false;
break;
case "pixel":
history.Font = new Font(TitleScreen.pfc.Families[1], 16, FontStyle.Regular);
break;
case ".cmd-end":
Chat.Stop();
endingActivate();
break;
default:
if (msgsound) receive.Play();
break;
}
if (TitleScreen.username == "devspeed") Chat.Interval = wcmp.GetMessageDelay(Properties.Resources.webchat1998_convo, chat_index) / 2;
else Chat.Interval = wcmp.GetMessageDelay(Properties.Resources.webchat1998_convo, chat_index);
}
else
{
if (correctname)
{
history.AppendText("SkyHigh: yay you got it right!" + Environment.NewLine);
}
else
{
history.AppendText("SkyHigh: sorry, my name is actually bill" + Environment.NewLine);
}
guessing = false;
receive.Play();
Chat.Interval = wcmp.GetMessageDelay(Properties.Resources.webchat1998_convo, chat_index);
}
chat_index++;
}
private async void endingActivate()
{
history.ReadOnly = true;
history.Text = "";
await Task.Delay(1500);
history.Text = "Starting MS-DOS...";
await Task.Delay(1000);
history.Text = "Starting MS-DOS..." + Environment.NewLine + Environment.NewLine + "C:\\>";
history.ReadOnly = false;
await Task.Delay(5000);
history.ReadOnly = true;
history.Text = "GAME OVER. Your computer has been locked down to MS-DOS because you pirated software. Seriously, what were you thinking?";
await Task.Delay(2000);
Cursor.Show();
SaveSystem.SaveAchievement(0);
new AchievementBox(0);
}
private void WebChatClosing(object sender, FormClosingEventArgs e)
{
if (wimponclose)
{
bsod.FormClosing += new FormClosingEventHandler(Program.title.BSODRewind);
bsod.Show();
bsod.BringToFront();
}
}
private void Button2_Click(object sender, EventArgs e)
{
if (typechat.Text != "") history.AppendText(TitleScreen.username + ": " + typechat.Text + Environment.NewLine);
typechat.Text = "";
if (msgsound) send.Play();
}
private void Button3_Click(object sender, EventArgs e)
{
correctname = false;
button2.Show();
button3.Hide();
button4.Hide();
typechat.Show();
Chat.Start();
}
private void Button4_Click(object sender, EventArgs e)
{
correctname = true;
button2.Show();
button3.Hide();
button4.Hide();
typechat.Show();
Chat.Start();
}
}
}
| |
using System;
using Orleans.Core;
using Orleans.Runtime;
namespace Orleans
{
/// <summary>
/// Extension methods for grains.
/// </summary>
public static class GrainExtensions
{
private const string WRONG_GRAIN_ERROR_MSG = "Passing a half baked grain as an argument. It is possible that you instantiated a grain class explicitly, as a regular object and not via Orleans runtime or via proper test mocking";
internal static GrainReference AsWeaklyTypedReference(this IAddressable grain)
{
ThrowIfNullGrain(grain);
// When called against an instance of a grain reference class, do nothing
var reference = grain as GrainReference;
if (reference != null) return reference;
var grainBase = grain as Grain;
if (grainBase != null)
{
if (grainBase.Data?.GrainReference == null)
{
throw new ArgumentException(WRONG_GRAIN_ERROR_MSG, nameof(grain));
}
return grainBase.Data.GrainReference;
}
var systemTarget = grain as ISystemTargetBase;
if (systemTarget != null) return GrainReference.FromGrainId(systemTarget.GrainId, systemTarget.RuntimeClient, null, systemTarget.Silo);
throw new ArgumentException(
$"AsWeaklyTypedReference has been called on an unexpected type: {grain.GetType().FullName}.",
nameof(grain));
}
/// <summary>
/// Converts this grain to a specific grain interface.
/// </summary>
/// <typeparam name="TGrainInterface">The type of the grain interface.</typeparam>
/// <param name="grain">The grain to convert.</param>
/// <returns>A strongly typed <c>GrainReference</c> of grain interface type TGrainInterface.</returns>
public static TGrainInterface AsReference<TGrainInterface>(this IAddressable grain)
{
ThrowIfNullGrain(grain);
var grainReference = grain.AsWeaklyTypedReference();
return grainReference.RuntimeClient.InternalGrainFactory.Cast<TGrainInterface>(grainReference);
}
/// <summary>
/// Casts a grain to a specific grain interface.
/// </summary>
/// <typeparam name="TGrainInterface">The type of the grain interface.</typeparam>
/// <param name="grain">The grain to cast.</param>
public static TGrainInterface Cast<TGrainInterface>(this IAddressable grain)
{
return grain.AsReference<TGrainInterface>();
}
/// <summary>
/// Binds the grain reference to the provided <see cref="IGrainFactory"/>.
/// </summary>
/// <param name="grain">The grain reference.</param>
/// <param name="grainFactory">The grain factory.</param>
public static void BindGrainReference(this IAddressable grain, IGrainFactory grainFactory)
{
grainFactory.BindGrainReference(grain);
}
internal static GrainId GetGrainId(IAddressable grain)
{
var reference = grain as GrainReference;
if (reference != null)
{
if (reference.GrainId == null)
{
throw new ArgumentException(WRONG_GRAIN_ERROR_MSG, "grain");
}
return reference.GrainId;
}
var grainBase = grain as Grain;
if (grainBase != null)
{
if (grainBase.Data == null || grainBase.Data.Identity == null)
{
throw new ArgumentException(WRONG_GRAIN_ERROR_MSG, "grain");
}
return grainBase.Data.Identity;
}
throw new ArgumentException(String.Format("GetGrainId has been called on an unexpected type: {0}.", grain.GetType().FullName), "grain");
}
public static IGrainIdentity GetGrainIdentity(this IGrain grain)
{
var grainBase = grain as Grain;
if (grainBase != null)
{
if (grainBase.Identity == null)
{
throw new ArgumentException(WRONG_GRAIN_ERROR_MSG, "grain");
}
return grainBase.Identity;
}
var grainReference = grain as GrainReference;
if (grainReference != null)
{
if (grainReference.GrainId == null)
{
throw new ArgumentException(WRONG_GRAIN_ERROR_MSG, "grain");
}
return grainReference.GrainId;
}
throw new ArgumentException(String.Format("GetGrainIdentity has been called on an unexpected type: {0}.", grain.GetType().FullName), "grain");
}
/// <summary>
/// Returns whether part of the primary key is of type long.
/// </summary>
/// <param name="grain">The target grain.</param>
public static bool IsPrimaryKeyBasedOnLong(this IAddressable grain)
{
return GetGrainId(grain).IsLongKey;
}
/// <summary>
/// Returns the long representation of a grain primary key.
/// </summary>
/// <param name="grain">The grain to find the primary key for.</param>
/// <param name="keyExt">The output paramater to return the extended key part of the grain primary key, if extened primary key was provided for that grain.</param>
/// <returns>A long representing the primary key for this grain.</returns>
public static long GetPrimaryKeyLong(this IAddressable grain, out string keyExt)
{
return GetGrainId(grain).GetPrimaryKeyLong(out keyExt);
}
/// <summary>
/// Returns the long representation of a grain primary key.
/// </summary>
/// <param name="grain">The grain to find the primary key for.</param>
/// <returns>A long representing the primary key for this grain.</returns>
public static long GetPrimaryKeyLong(this IAddressable grain)
{
return GetGrainId(grain).GetPrimaryKeyLong();
}
/// <summary>
/// Returns the Guid representation of a grain primary key.
/// </summary>
/// <param name="grain">The grain to find the primary key for.</param>
/// <param name="keyExt">The output paramater to return the extended key part of the grain primary key, if extened primary key was provided for that grain.</param>
/// <returns>A Guid representing the primary key for this grain.</returns>
public static Guid GetPrimaryKey(this IAddressable grain, out string keyExt)
{
return GetGrainId(grain).GetPrimaryKey(out keyExt);
}
/// <summary>
/// Returns the Guid representation of a grain primary key.
/// </summary>
/// <param name="grain">The grain to find the primary key for.</param>
/// <returns>A Guid representing the primary key for this grain.</returns>
public static Guid GetPrimaryKey(this IAddressable grain)
{
return GetGrainId(grain).GetPrimaryKey();
}
/// <summary>
/// Returns the string primary key of the grain.
/// </summary>
/// <param name="grain">The grain to find the primary key for.</param>
/// <returns>A string representing the primary key for this grain.</returns>
public static string GetPrimaryKeyString(this IAddressable grain)
{
return GetGrainId(grain).GetPrimaryKeyString();
}
public static long GetPrimaryKeyLong(this IGrain grain, out string keyExt)
{
return GetGrainIdentity(grain).GetPrimaryKeyLong(out keyExt);
}
public static long GetPrimaryKeyLong(this IGrain grain)
{
return GetGrainIdentity(grain).PrimaryKeyLong;
}
public static Guid GetPrimaryKey(this IGrain grain, out string keyExt)
{
return GetGrainIdentity(grain).GetPrimaryKey(out keyExt);
}
public static Guid GetPrimaryKey(this IGrain grain)
{
return GetGrainIdentity(grain).PrimaryKey;
}
public static string GetPrimaryKeyString(this IGrainWithStringKey grain)
{
return GetGrainIdentity(grain).PrimaryKeyString;
}
private static void ThrowIfNullGrain(IAddressable grain)
{
if (grain == null)
{
throw new ArgumentNullException(nameof(grain));
}
}
}
}
| |
using Xunit;
namespace Jint.Tests.Ecma
{
public class Test_12_14 : EcmaTest
{
[Fact]
[Trait("Category", "12.14")]
public void CatchDoesnTChangeDeclarationScopeVarInitializerInCatchWithSameNameAsCatchParameterChangesParameter()
{
RunTest(@"TestCases/ch12/12.14/12.14-1.js", false);
}
[Fact]
[Trait("Category", "12.14")]
public void CatchIntroducesScopeNameLookupFindsFunctionParameter()
{
RunTest(@"TestCases/ch12/12.14/12.14-10.js", false);
}
[Fact]
[Trait("Category", "12.14")]
public void CatchIntroducesScopeNameLookupFindsInnerVariable()
{
RunTest(@"TestCases/ch12/12.14/12.14-11.js", false);
}
[Fact]
[Trait("Category", "12.14")]
public void CatchIntroducesScopeNameLookupFindsProperty()
{
RunTest(@"TestCases/ch12/12.14/12.14-12.js", false);
}
[Fact]
[Trait("Category", "12.14")]
public void CatchIntroducesScopeUpdatesAreBasedOnScope()
{
RunTest(@"TestCases/ch12/12.14/12.14-13.js", false);
}
[Fact]
[Trait("Category", "12.14")]
public void ExceptionObjectIsAFunctionWhenAnExceptionParameterIsCalledAsAFunctionInCatchBlockGlobalObjectIsPassedAsTheThisValue()
{
RunTest(@"TestCases/ch12/12.14/12.14-14.js", false);
}
[Fact]
[Trait("Category", "12.14")]
public void ExceptionObjectIsAFunctionWhichIsAPropertyOfAnObjectWhenAnExceptionParameterIsCalledAsAFunctionInCatchBlockGlobalObjectIsPassedAsTheThisValue()
{
RunTest(@"TestCases/ch12/12.14/12.14-15.js", false);
}
[Fact]
[Trait("Category", "12.14")]
public void ExceptionObjectIsAFunctionWhichUpdateInCatchBlockWhenAnExceptionParameterIsCalledAsAFunctionInCatchBlockGlobalObjectIsPassedAsTheThisValue()
{
RunTest(@"TestCases/ch12/12.14/12.14-16.js", false);
}
[Fact]
[Trait("Category", "12.14")]
public void CatchDoesnTChangeDeclarationScopeVarInitializerInCatchWithSameNameAsCatchParameterChangesParameter2()
{
RunTest(@"TestCases/ch12/12.14/12.14-2.js", false);
}
[Fact]
[Trait("Category", "12.14")]
public void LocalVarsMustNotBeVisibleOutsideWithBlockLocalFunctionsMustNotBeVisibleOutsideWithBlockLocalFunctionExpresssionsShouldNotBeVisibleOutsideWithBlockLocalVarsMustShadowOuterVarsLocalFunctionsMustShadowOuterFunctionsLocalFunctionExpresssionsMustShadowOuterFunctionExpressionsEvalShouldUseTheAppendedObjectToTheScopeChain()
{
RunTest(@"TestCases/ch12/12.14/12.14-3.js", false);
}
[Fact]
[Trait("Category", "12.14")]
public void LocalVarsMustNotBeVisibleOutsideWithBlockLocalFunctionsMustNotBeVisibleOutsideWithBlockLocalFunctionExpresssionsShouldNotBeVisibleOutsideWithBlockLocalVarsMustShadowOuterVarsLocalFunctionsMustShadowOuterFunctionsLocalFunctionExpresssionsMustShadowOuterFunctionExpressionsEvalShouldUseTheAppendedObjectToTheScopeChain2()
{
RunTest(@"TestCases/ch12/12.14/12.14-4.js", false);
}
[Fact]
[Trait("Category", "12.14")]
public void LocalVarsMustNotBeVisibleOutsideWithBlockLocalFunctionsMustNotBeVisibleOutsideWithBlockLocalFunctionExpresssionsShouldNotBeVisibleOutsideWithBlockLocalVarsMustShadowOuterVarsLocalFunctionsMustShadowOuterFunctionsLocalFunctionExpresssionsMustShadowOuterFunctionExpressionsEvalShouldUseTheAppendedObjectToTheScopeChain3()
{
RunTest(@"TestCases/ch12/12.14/12.14-6.js", false);
}
[Fact]
[Trait("Category", "12.14")]
public void LocalVarsMustNotBeVisibleOutsideWithBlockLocalFunctionsMustNotBeVisibleOutsideWithBlockLocalFunctionExpresssionsShouldNotBeVisibleOutsideWithBlockLocalVarsMustShadowOuterVarsLocalFunctionsMustShadowOuterFunctionsLocalFunctionExpresssionsMustShadowOuterFunctionExpressionsEvalShouldUseTheAppendedObjectToTheScopeChain4()
{
RunTest(@"TestCases/ch12/12.14/12.14-7.js", false);
}
[Fact]
[Trait("Category", "12.14")]
public void LocalVarsMustNotBeVisibleOutsideWithBlockLocalFunctionsMustNotBeVisibleOutsideWithBlockLocalFunctionExpresssionsShouldNotBeVisibleOutsideWithBlockLocalVarsMustShadowOuterVarsLocalFunctionsMustShadowOuterFunctionsLocalFunctionExpresssionsMustShadowOuterFunctionExpressionsEvalShouldUseTheAppendedObjectToTheScopeChain5()
{
RunTest(@"TestCases/ch12/12.14/12.14-8.js", false);
}
[Fact]
[Trait("Category", "12.14")]
public void CatchIntroducesScopeNameLookupFindsOuterVariable()
{
RunTest(@"TestCases/ch12/12.14/12.14-9.js", false);
}
[Fact]
[Trait("Category", "12.14")]
public void TheProductionTrystatementTryBlockCatchIsEvaluatedAsFollows2IfResult1TypeIsNotThrowReturnResult1()
{
RunTest(@"TestCases/ch12/12.14/S12.14_A1.js", false);
}
[Fact]
[Trait("Category", "12.14")]
public void UsingTryWithCatchOrFinallyStatementWithinWithoutAWhileStatement()
{
RunTest(@"TestCases/ch12/12.14/S12.14_A10_T1.js", false);
}
[Fact]
[Trait("Category", "12.14")]
public void UsingTryWithCatchOrFinallyStatementWithinWithoutAWhileStatement2()
{
RunTest(@"TestCases/ch12/12.14/S12.14_A10_T2.js", false);
}
[Fact]
[Trait("Category", "12.14")]
public void UsingTryWithCatchOrFinallyStatementWithinWithoutAWhileStatement3()
{
RunTest(@"TestCases/ch12/12.14/S12.14_A10_T3.js", false);
}
[Fact]
[Trait("Category", "12.14")]
public void UsingTryWithCatchOrFinallyStatementWithinWithoutAWhileStatement4()
{
RunTest(@"TestCases/ch12/12.14/S12.14_A10_T4.js", false);
}
[Fact]
[Trait("Category", "12.14")]
public void UsingTryWithCatchOrFinallyStatementWithinWithoutAWhileStatement5()
{
RunTest(@"TestCases/ch12/12.14/S12.14_A10_T5.js", false);
}
[Fact]
[Trait("Category", "12.14")]
public void UsingTryWithCatchOrFinallyStatementWithinWithoutAForStatement()
{
RunTest(@"TestCases/ch12/12.14/S12.14_A11_T1.js", false);
}
[Fact]
[Trait("Category", "12.14")]
public void UsingTryWithCatchOrFinallyStatementWithinWithoutAForStatement2()
{
RunTest(@"TestCases/ch12/12.14/S12.14_A11_T2.js", false);
}
[Fact]
[Trait("Category", "12.14")]
public void UsingTryWithCatchOrFinallyStatementWithinWithoutAForStatement3()
{
RunTest(@"TestCases/ch12/12.14/S12.14_A11_T3.js", false);
}
[Fact]
[Trait("Category", "12.14")]
public void UsingTryWithCatchOrFinallyStatementWithinWithoutAForStatement4()
{
RunTest(@"TestCases/ch12/12.14/S12.14_A11_T4.js", false);
}
[Fact]
[Trait("Category", "12.14")]
public void UsingTryWithCatchOrFinallyStatementWithinWithoutAForInStatement()
{
RunTest(@"TestCases/ch12/12.14/S12.14_A12_T1.js", false);
}
[Fact]
[Trait("Category", "12.14")]
public void UsingTryWithCatchOrFinallyStatementWithinWithoutAForInStatement2()
{
RunTest(@"TestCases/ch12/12.14/S12.14_A12_T2.js", false);
}
[Fact]
[Trait("Category", "12.14")]
public void UsingTryWithCatchOrFinallyStatementWithinWithoutAForInStatement3()
{
RunTest(@"TestCases/ch12/12.14/S12.14_A12_T3.js", false);
}
[Fact]
[Trait("Category", "12.14")]
public void UsingTryWithCatchOrFinallyStatementWithinWithoutAForInStatement4()
{
RunTest(@"TestCases/ch12/12.14/S12.14_A12_T4.js", false);
}
[Fact]
[Trait("Category", "12.14")]
public void UsingTryWithCatchOrFinallyStatementWithAReturnStatement()
{
RunTest(@"TestCases/ch12/12.14/S12.14_A13_T1.js", false);
}
[Fact]
[Trait("Category", "12.14")]
public void UsingTryWithCatchOrFinallyStatementWithAReturnStatement2()
{
RunTest(@"TestCases/ch12/12.14/S12.14_A13_T2.js", false);
}
[Fact]
[Trait("Category", "12.14")]
public void UsingTryWithCatchOrFinallyStatementWithAReturnStatement3()
{
RunTest(@"TestCases/ch12/12.14/S12.14_A13_T3.js", false);
}
[Fact]
[Trait("Category", "12.14")]
public void UsingTryWithCatchOrFinallyStatementWithinWithoutAWithStatement()
{
RunTest(@"TestCases/ch12/12.14/S12.14_A14.js", false);
}
[Fact]
[Trait("Category", "12.14")]
public void UsingTryWithCatchOrFinallyStatementWithinWithoutASwitchStatement()
{
RunTest(@"TestCases/ch12/12.14/S12.14_A15.js", false);
}
[Fact]
[Trait("Category", "12.14")]
public void TrystatementTryBlockCatchOrTryBlockFinallyOrTryBlockCatchFinally()
{
RunTest(@"TestCases/ch12/12.14/S12.14_A16_T1.js", true);
}
[Fact]
[Trait("Category", "12.14")]
public void TrystatementTryBlockCatchOrTryBlockFinallyOrTryBlockCatchFinally2()
{
RunTest(@"TestCases/ch12/12.14/S12.14_A16_T10.js", true);
}
[Fact]
[Trait("Category", "12.14")]
public void TrystatementTryBlockCatchOrTryBlockFinallyOrTryBlockCatchFinally3()
{
RunTest(@"TestCases/ch12/12.14/S12.14_A16_T11.js", true);
}
[Fact]
[Trait("Category", "12.14")]
public void TrystatementTryBlockCatchOrTryBlockFinallyOrTryBlockCatchFinally4()
{
RunTest(@"TestCases/ch12/12.14/S12.14_A16_T12.js", true);
}
[Fact]
[Trait("Category", "12.14")]
public void TrystatementTryBlockCatchOrTryBlockFinallyOrTryBlockCatchFinally5()
{
RunTest(@"TestCases/ch12/12.14/S12.14_A16_T13.js", true);
}
[Fact]
[Trait("Category", "12.14")]
public void TrystatementTryBlockCatchOrTryBlockFinallyOrTryBlockCatchFinally6()
{
RunTest(@"TestCases/ch12/12.14/S12.14_A16_T14.js", true);
}
[Fact]
[Trait("Category", "12.14")]
public void TrystatementTryBlockCatchOrTryBlockFinallyOrTryBlockCatchFinally7()
{
RunTest(@"TestCases/ch12/12.14/S12.14_A16_T15.js", true);
}
[Fact]
[Trait("Category", "12.14")]
public void TrystatementTryBlockCatchOrTryBlockFinallyOrTryBlockCatchFinally8()
{
RunTest(@"TestCases/ch12/12.14/S12.14_A16_T2.js", true);
}
[Fact]
[Trait("Category", "12.14")]
public void TrystatementTryBlockCatchOrTryBlockFinallyOrTryBlockCatchFinally9()
{
RunTest(@"TestCases/ch12/12.14/S12.14_A16_T3.js", true);
}
[Fact]
[Trait("Category", "12.14")]
public void TrystatementTryBlockCatchOrTryBlockFinallyOrTryBlockCatchFinally10()
{
RunTest(@"TestCases/ch12/12.14/S12.14_A16_T4.js", true);
}
[Fact]
[Trait("Category", "12.14")]
public void TrystatementTryBlockCatchOrTryBlockFinallyOrTryBlockCatchFinally11()
{
RunTest(@"TestCases/ch12/12.14/S12.14_A16_T5.js", true);
}
[Fact]
[Trait("Category", "12.14")]
public void TrystatementTryBlockCatchOrTryBlockFinallyOrTryBlockCatchFinally12()
{
RunTest(@"TestCases/ch12/12.14/S12.14_A16_T6.js", true);
}
[Fact]
[Trait("Category", "12.14")]
public void TrystatementTryBlockCatchOrTryBlockFinallyOrTryBlockCatchFinally13()
{
RunTest(@"TestCases/ch12/12.14/S12.14_A16_T7.js", true);
}
[Fact]
[Trait("Category", "12.14")]
public void TrystatementTryBlockCatchOrTryBlockFinallyOrTryBlockCatchFinally14()
{
RunTest(@"TestCases/ch12/12.14/S12.14_A16_T8.js", true);
}
[Fact]
[Trait("Category", "12.14")]
public void TrystatementTryBlockCatchOrTryBlockFinallyOrTryBlockCatchFinally15()
{
RunTest(@"TestCases/ch12/12.14/S12.14_A16_T9.js", true);
}
[Fact]
[Trait("Category", "12.14")]
public void UsingTryWithCatchOrFinallyStatementInAConstructor()
{
RunTest(@"TestCases/ch12/12.14/S12.14_A17.js", false);
}
[Fact]
[Trait("Category", "12.14")]
public void CatchingObjectsWithTryCatchFinallyStatement()
{
RunTest(@"TestCases/ch12/12.14/S12.14_A18_T1.js", false);
}
[Fact]
[Trait("Category", "12.14")]
public void CatchingObjectsWithTryCatchFinallyStatement2()
{
RunTest(@"TestCases/ch12/12.14/S12.14_A18_T2.js", false);
}
[Fact]
[Trait("Category", "12.14")]
public void CatchingObjectsWithTryCatchFinallyStatement3()
{
RunTest(@"TestCases/ch12/12.14/S12.14_A18_T3.js", false);
}
[Fact]
[Trait("Category", "12.14")]
public void CatchingObjectsWithTryCatchFinallyStatement4()
{
RunTest(@"TestCases/ch12/12.14/S12.14_A18_T4.js", false);
}
[Fact]
[Trait("Category", "12.14")]
public void CatchingObjectsWithTryCatchFinallyStatement5()
{
RunTest(@"TestCases/ch12/12.14/S12.14_A18_T5.js", false);
}
[Fact]
[Trait("Category", "12.14")]
public void CatchingObjectsWithTryCatchFinallyStatement6()
{
RunTest(@"TestCases/ch12/12.14/S12.14_A18_T6.js", false);
}
[Fact]
[Trait("Category", "12.14")]
public void CatchingObjectsWithTryCatchFinallyStatement7()
{
RunTest(@"TestCases/ch12/12.14/S12.14_A18_T7.js", false);
}
[Fact]
[Trait("Category", "12.14")]
public void CatchingSystemExceptionsOfDifferentTypesWithTryStatement()
{
RunTest(@"TestCases/ch12/12.14/S12.14_A19_T1.js", false);
}
[Fact]
[Trait("Category", "12.14")]
public void CatchingSystemExceptionsOfDifferentTypesWithTryStatement2()
{
RunTest(@"TestCases/ch12/12.14/S12.14_A19_T2.js", false);
}
[Fact]
[Trait("Category", "12.14")]
public void ThrowingExceptionWithThrowAndCatchingItWithTryStatement()
{
RunTest(@"TestCases/ch12/12.14/S12.14_A2.js", false);
}
[Fact]
[Trait("Category", "12.14")]
public void CatchingSystemExceptionWithTryStatement()
{
RunTest(@"TestCases/ch12/12.14/S12.14_A3.js", false);
}
[Fact]
[Trait("Category", "12.14")]
public void SanityTestForCatchIndetifierStatement()
{
RunTest(@"TestCases/ch12/12.14/S12.14_A4.js", false);
}
[Fact]
[Trait("Category", "12.14")]
public void TheProductionTrystatementTryBlockFinallyAndTheProductionTrystatementTryBlockCatchFinally()
{
RunTest(@"TestCases/ch12/12.14/S12.14_A5.js", false);
}
[Fact]
[Trait("Category", "12.14")]
public void TheProductionTrystatementTryBlockCatchFinally()
{
RunTest(@"TestCases/ch12/12.14/S12.14_A6.js", false);
}
[Fact]
[Trait("Category", "12.14")]
public void EvaluatingTheNestedProductionsTrystatement()
{
RunTest(@"TestCases/ch12/12.14/S12.14_A7_T1.js", false);
}
[Fact]
[Trait("Category", "12.14")]
public void EvaluatingTheNestedProductionsTrystatement2()
{
RunTest(@"TestCases/ch12/12.14/S12.14_A7_T2.js", false);
}
[Fact]
[Trait("Category", "12.14")]
public void EvaluatingTheNestedProductionsTrystatement3()
{
RunTest(@"TestCases/ch12/12.14/S12.14_A7_T3.js", false);
}
[Fact]
[Trait("Category", "12.14")]
public void TryWithCatchOrFinallyStatementWithinWithoutAnIfStatement()
{
RunTest(@"TestCases/ch12/12.14/S12.14_A8.js", false);
}
[Fact]
[Trait("Category", "12.14")]
public void TryWithCatchOrFinallyStatementWithinWithoutAnDoWhileStatement()
{
RunTest(@"TestCases/ch12/12.14/S12.14_A9_T1.js", false);
}
[Fact]
[Trait("Category", "12.14")]
public void TryWithCatchOrFinallyStatementWithinWithoutAnDoWhileStatement2()
{
RunTest(@"TestCases/ch12/12.14/S12.14_A9_T2.js", false);
}
[Fact]
[Trait("Category", "12.14")]
public void TryWithCatchOrFinallyStatementWithinWithoutAnDoWhileStatement3()
{
RunTest(@"TestCases/ch12/12.14/S12.14_A9_T3.js", false);
}
[Fact]
[Trait("Category", "12.14")]
public void TryWithCatchOrFinallyStatementWithinWithoutAnDoWhileStatement4()
{
RunTest(@"TestCases/ch12/12.14/S12.14_A9_T4.js", false);
}
[Fact]
[Trait("Category", "12.14")]
public void TryWithCatchOrFinallyStatementWithinWithoutAnDoWhileStatement5()
{
RunTest(@"TestCases/ch12/12.14/S12.14_A9_T5.js", false);
}
}
}
| |
//-----------------------------------------------------------------------
// <copyright file="EntityModel.cs" company="Genesys Source">
// Copyright (c) Genesys Source. All rights reserved.
// 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.
// </copyright>
//-----------------------------------------------------------------------
using Genesys.Extensions;
using Genesys.Extras.Serialization;
using Genesys.Framework.Text;
using Genesys.Framework.Validation;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Serialization;
namespace Genesys.Framework.Data
{
/// <summary>
/// ModelBase
/// </summary>
/// <remarks>ModelBase</remarks>
public abstract class EntityModel<TEntity> : IEntity, ISerializable<TEntity>, IValidatable<TEntity>, INotifyPropertyChanged where TEntity : EntityModel<TEntity>, new()
{
private int id = TypeExtension.DefaultInteger;
private Guid key = TypeExtension.DefaultGuid;
private Guid activityContextKey = TypeExtension.DefaultGuid;
private DateTime createdDate = TypeExtension.DefaultDate;
private DateTime modifiedDate = TypeExtension.DefaultDate;
/// <summary>
/// Id of record
/// </summary>
public virtual int Id { get => id; set => SetField(ref id, value); }
/// <summary>
/// Guid of record
/// </summary>
public virtual Guid Key { get => key; set => SetField(ref key, value); }
/// <summary>
/// Workflow activity that created this record
/// </summary>
public virtual Guid ActivityContextKey { get => activityContextKey; set => SetField(ref activityContextKey, value); }
/// <summary>
/// Date record was created
/// </summary>
public virtual DateTime CreatedDate { get => createdDate; set => SetField(ref createdDate, value); }
/// <summary>
/// Date record was modified
/// </summary>
public virtual DateTime ModifiedDate { get => modifiedDate; set => SetField(ref modifiedDate, value); }
/// <summary>
/// Status of this record
/// </summary>
public virtual Guid State { get; set; } = RecordStates.Default;
/// <summary>
/// Is this a new object not yet committed to the database
/// </summary>
public virtual bool IsNew => (this.Id == TypeExtension.DefaultInteger);
/// <summary>
/// Rules that failed validation
/// </summary>
public IList<ITextMessage> FailedRules { get; set; } = new List<ITextMessage>();
/// <summary>
/// Rules used by the validator for Data Validation and Business Validation
/// </summary>
public virtual IList<IValidationRule<TEntity>> Rules() { return new List<IValidationRule<TEntity>>(); }
/// <summary>
/// Constructor
/// </summary>
public EntityModel() : base() { }
/// <summary>
/// Property changed event handler for INotifyPropertyChanged
/// </summary>
public event PropertyChangedEventHandler PropertyChanged;
/// <summary>
/// Property changed event for INotifyPropertyChanged
/// </summary>
/// <param name="propertyName">String name of property</param>
protected void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
/// <summary>
/// Fills this object with another object's data (of the same type)
/// </summary>
/// <param name="newItem"></param>
/// <remarks></remarks>
public bool Equals(TEntity newItem)
{
bool returnValue = TypeExtension.DefaultBoolean;
Type newObjectType = newItem.GetType();
// Start True
returnValue = true;
// Loop through all new item's properties
foreach (var newObjectProperty in newObjectType.GetRuntimeProperties())
{
// Copy the data using reflection
PropertyInfo currentProperty = typeof(TEntity).GetRuntimeProperty(newObjectProperty.Name);
if (currentProperty != null && currentProperty.CanWrite)
{
// Check for equivalence
if (object.Equals(currentProperty.GetValue(this, null), newObjectProperty.GetValue(newItem, null)) == false)
{
returnValue = false;
break;
}
}
}
// Return data
return returnValue;
}
/// <summary>
/// Serializes this object into a Json string
/// </summary>
/// <returns></returns>
public IEnumerable<ITextMessage> Validate()
{
var validator = new EntityValidator<TEntity>(this.CastSafe<TEntity>());
return validator.Validate();
}
/// <summary>
/// De-serializes a string into this object
/// </summary>
/// <returns></returns>
public bool IsValid()
{
var validator = new EntityValidator<TEntity>(this.CastSafe<TEntity>());
return validator.IsValid();
}
/// <summary>
/// Serializes this object into a Json string
/// </summary>
/// <returns></returns>
public string Serialize()
{
var serializer = new JsonSerializer<TEntity>(this.CastSafe<TEntity>());
return serializer.Serialize();
}
/// <summary>
/// De-serializes a string into this object
/// </summary>
/// <returns></returns>
public TEntity Deserialize(string data)
{
var serializer = new JsonSerializer<TEntity>(data);
return serializer.Deserialize();
}
/// <summary>
/// Null-safe cast to the type TEntity
/// </summary>
/// <returns>This object casted to type TEntity</returns>
public TEntity ToEntity()
{
return this.CastOrFill<TEntity>();
}
/// <summary>
/// Start with Id as string representation
/// </summary>
/// <returns></returns>
/// <remarks></remarks>
public override string ToString()
{
return Key.ToString();
}
/// <summary>
/// Sets the property data as well as fired OnPropertyChanged() for INotifyPropertyChanged
/// </summary>
/// <typeparam name="TField"></typeparam>
/// <param name="field"></param>
/// <param name="value"></param>
/// <param name="propertyName"></param>
/// <returns></returns>
protected bool SetField<TField>(ref TField field, TField value,
[CallerMemberName] string propertyName = null)
{
var returnValue = TypeExtension.DefaultBoolean;
if (EqualityComparer<TField>.Default.Equals(field, value) == false)
{
field = value;
OnPropertyChanged(propertyName);
returnValue = true;
}
return returnValue;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using Diadoc.Api.Com;
using Diadoc.Api.Proto.Documents;
namespace Diadoc.Api.Proto.Events
{
[ComVisible(true)]
[Guid("ABF440A3-BC33-4DF4-80CF-6889F7B004A3")]
public interface IMessage
{
string MessageId { get; }
string FromBoxId { get; }
string FromTitle { get; }
string ToBoxId { get; }
string ToTitle { get; }
bool IsDraft { get; }
bool IsDeleted { get; }
bool IsTest { get; }
bool IsInternal { get; }
ReadonlyList EntitiesList { get; }
bool DraftIsLocked { get; }
bool DraftIsRecycled { get; }
string CreatedFromDraftId { get; }
string DraftIsTransformedToMessageId { get; }
DateTime Timestamp { get; }
DateTime LastPatchTimestamp { get; }
}
[ComVisible(true)]
[Guid("26C32890-61DE-4FB9-9EED-B815E41050B7")]
[ClassInterface(ClassInterfaceType.None)]
[ComDefaultInterface(typeof (IMessage))]
public partial class Message : SafeComObject, IMessage
{
public string DraftIsTransformedToMessageId
{
get { return DraftIsTransformedToMessageIdList.FirstOrDefault(); }
}
public DateTime Timestamp
{
get { return new DateTime(TimestampTicks, DateTimeKind.Utc); }
}
public DateTime LastPatchTimestamp
{
get { return new DateTime(LastPatchTimestampTicks, DateTimeKind.Utc); }
}
public ReadonlyList EntitiesList
{
get { return new ReadonlyList(Entities); }
}
}
[ComVisible(true)]
[Guid("DFF0AEBA-4DCC-4910-B34A-200F1B919F4E")]
public interface IEntity
{
string EntityId { get; }
string ParentEntityId { get; }
Com.EntityType EntityTypeValue { get; }
Com.AttachmentType AttachmentTypeValue { get; }
string FileName { get; }
bool NeedRecipientSignature { get; }
bool NeedReceipt { get; }
Content Content { get; }
Document DocumentInfo { get; }
ResolutionInfo ResolutionInfo { get; }
string SignerBoxId { get; }
string SignerDepartmentId { get; }
DateTime CreationTime { get; }
string NotDeliveredEventId { get; }
ResolutionRouteAssignmentInfo ResolutionRouteAssignmentInfo { get; }
ResolutionRouteRemovalInfo ResolutionRouteRemovalInfo { get; }
CancellationInfo CancellationInfo { get; }
ReadonlyList LabelsList { get; }
void AddLabel(string label);
}
[ComVisible(true)]
[Guid("E7D82A2C-A0BF-4D0B-9466-9E8DA15B99B7")]
[ClassInterface(ClassInterfaceType.None)]
[ComDefaultInterface(typeof (IEntity))]
public partial class Entity : SafeComObject, IEntity
{
public DateTime CreationTime
{
get { return new DateTime(RawCreationDate, DateTimeKind.Utc); }
}
public Com.EntityType EntityTypeValue
{
get { return (Com.EntityType) ((int) EntityType); }
}
public Com.AttachmentType AttachmentTypeValue
{
get { return (Com.AttachmentType) ((int) AttachmentType); }
}
public ReadonlyList LabelsList
{
get { return new ReadonlyList(Labels); }
}
public void AddLabel(string label)
{
Labels.Add(label);
}
}
[ComVisible(true)]
[Guid("D3BD7130-16A6-4202-B1CE-5FB1A9AFD4EF")]
public interface IEntityPatch
{
string EntityId { get; }
bool DocumentIsDeleted { get; }
string MovedToDepartment { get; }
bool DocumentIsRestored { get; }
bool ContentIsPatched { get; }
}
[ComVisible(true)]
[Guid("4C05AB1C-5385-41A2-8C04-8855FC7E8341")]
[ClassInterface(ClassInterfaceType.None)]
[ComDefaultInterface(typeof (IEntityPatch))]
public partial class EntityPatch : SafeComObject, IEntityPatch
{
}
[ComVisible(true)]
[Guid("AE4037C5-DA6E-4D69-A738-5E6B64490492")]
public interface IBoxEvent
{
string EventId { get; }
string MessageId { get; }
DateTime Timestamp { get; }
ReadonlyList EntitiesList { get; }
bool HasMessage { get; }
bool HasPatch { get; }
Message Message { get; }
MessagePatch Patch { get; }
}
[ComVisible(true)]
[Guid("C59A22CF-9744-457A-8359-3569B19A31C8")]
[ClassInterface(ClassInterfaceType.None)]
[ComDefaultInterface(typeof (IBoxEvent))]
public partial class BoxEvent : SafeComObject, IBoxEvent
{
public string MessageId
{
get
{
return (Message != null ? Message.MessageId : null)
?? (Patch != null ? Patch.MessageId : null);
}
}
public DateTime Timestamp
{
get
{
if (Message != null)
return Message.Timestamp;
if (Patch != null)
return Patch.Timestamp;
return default(DateTime);
}
}
public ReadonlyList EntitiesList
{
get
{
var entities = (Message != null ? Message.Entities : null)
?? (Patch != null ? Patch.Entities : null);
return entities != null
? new ReadonlyList(entities)
: null;
}
}
public List<Entity> Entities
{
get
{
var entities = (Message != null ? Message.Entities : null)
?? (Patch != null ? Patch.Entities : null);
return entities != null
? new List<Entity>(entities)
: new List<Entity>();
}
}
public bool HasMessage
{
get { return Message != null; }
}
public bool HasPatch
{
get { return Patch != null; }
}
}
[ComVisible(true)]
[Guid("581C269C-67A5-4CDF-AC77-CDB2D05E03A0")]
public interface IBoxEventList
{
int TotalCount { get; }
ReadonlyList EventsList { get; }
}
[ComVisible(true)]
[Guid("793E451E-3F4A-4A3E-BDBB-F47ED13305F5")]
[ClassInterface(ClassInterfaceType.None)]
[ComDefaultInterface(typeof (IBoxEventList))]
public partial class BoxEventList : SafeComObject, IBoxEventList
{
public ReadonlyList EventsList
{
get { return new ReadonlyList(Events); }
}
}
[ComVisible(true)]
[Guid("527CD64F-A219-4B45-8219-CC48586D521B")]
public interface IMessagePatch
{
string MessageId { get; }
ReadonlyList EntitiesList { get; }
ReadonlyList EntityPatchesList { get; }
DateTime Timestamp { get; }
bool ForDraft { get; }
bool DraftIsRecycled { get; }
string DraftIsTransformedToMessageId { get; }
bool DraftIsLocked { get; }
bool MessageIsDeleted { get; }
bool MessageIsRestored { get; }
bool MessageIsDelivered { get; }
string DeliveredPatchId { get; }
string PatchId { get; }
}
[ComVisible(true)]
[Guid("949C9C09-DD1A-4787-A5AD-94D8677A5439")]
[ClassInterface(ClassInterfaceType.None)]
[ComDefaultInterface(typeof (IMessagePatch))]
public partial class MessagePatch : SafeComObject, IMessagePatch
{
public DateTime Timestamp
{
get { return new DateTime(TimestampTicks, DateTimeKind.Utc); }
}
public string DraftIsTransformedToMessageId
{
get { return DraftIsTransformedToMessageIdList.FirstOrDefault(); }
}
public ReadonlyList EntitiesList
{
get { return new ReadonlyList(Entities); }
}
public ReadonlyList EntityPatchesList
{
get { return new ReadonlyList(EntityPatches); }
}
}
[ComVisible(true)]
[Guid("32176AA9-AF39-4E0C-A47B-0CEA3C1DA211")]
public interface IGeneratedFile
{
string FileName { get; }
byte[] Content { get; }
void SaveContentToFile(string path);
}
[ComVisible(true)]
[Guid("D4E7012E-1A64-42EC-AD5E-B27754AC24FE")]
[ClassInterface(ClassInterfaceType.None)]
[ComDefaultInterface(typeof (IGeneratedFile))]
public class GeneratedFile : SafeComObject, IGeneratedFile
{
private readonly string fileName;
private readonly byte[] content;
public GeneratedFile(string fileName, byte[] content)
{
this.fileName = fileName;
this.content = content;
}
public void SaveContentToFile(string path)
{
File.WriteAllBytes(path, Content);
}
public string FileName
{
get { return fileName; }
}
public byte[] Content
{
get { return content; }
}
}
[ComVisible(true)]
[Guid("34FD4B0B-CE38-41CE-AB76-4C6234A6C542")]
public interface IMessageToPost
{
string FromBoxId { get; set; }
string FromDepartmentId { get; set; }
string ToBoxId { get; set; }
string ToDepartmentId { get; set; }
bool IsInternal { get; set; }
bool IsDraft { get; set; }
bool LockDraft { get; set; }
bool LockPacket { get; set; }
bool StrictDraftValidation { get; set; }
bool DelaySend { get; set; }
TrustConnectionRequestAttachment TrustConnectionRequest { get; set; }
void AddInvoice([MarshalAs(UnmanagedType.IDispatch)] object attachment);
void AddXmlTorg12SellerTitle([MarshalAs(UnmanagedType.IDispatch)] object attachment);
void AddXmlAcceptanceCertificateSellerTitle([MarshalAs(UnmanagedType.IDispatch)] object attachment);
void AddAttachment([MarshalAs(UnmanagedType.IDispatch)] object attachment);
void AddTorg12([MarshalAs(UnmanagedType.IDispatch)] object attachment);
void AddAcceptanceCertificate([MarshalAs(UnmanagedType.IDispatch)] object attachment);
void AddProformaInvoice([MarshalAs(UnmanagedType.IDispatch)] object attachment);
void AddStructuredData([MarshalAs(UnmanagedType.IDispatch)] object attachment);
void AddPriceList([MarshalAs(UnmanagedType.IDispatch)] object attachment);
void AddPriceListAgreement([MarshalAs(UnmanagedType.IDispatch)] object attachment);
void AddCertificateRegistry([MarshalAs(UnmanagedType.IDispatch)] object attachment);
void AddReconciliationAct([MarshalAs(UnmanagedType.IDispatch)] object attachment);
void AddContract([MarshalAs(UnmanagedType.IDispatch)] object attachment);
void AddTorg13([MarshalAs(UnmanagedType.IDispatch)] object attachment);
void AddServiceDetails([MarshalAs(UnmanagedType.IDispatch)] object attachment);
void AddSupplementaryAgreement([MarshalAs(UnmanagedType.IDispatch)] object supplementaryAgreement);
void AddUniversalTransferDocumentSellerTitle([MarshalAs(UnmanagedType.IDispatch)] object attachment);
void AddDocumentAttachment([MarshalAs(UnmanagedType.IDispatch)] object attachment);
}
[ComVisible(true)]
[ProgId("Diadoc.Api.MessageToPost")]
[Guid("6EABD544-6DDC-49b4-95A1-0D7936C08C31")]
[ClassInterface(ClassInterfaceType.None)]
[ComDefaultInterface(typeof (IMessageToPost))]
public partial class MessageToPost : SafeComObject, IMessageToPost
{
//That property was deletes from proto description, but we can't delete this property here because COM need continuous sequence of methods
public TrustConnectionRequestAttachment TrustConnectionRequest
{
get { return null; }
set { }
}
public void AddInvoice(object attachment)
{
Invoices.Add((XmlDocumentAttachment)attachment);
}
public void AddXmlTorg12SellerTitle(object attachment)
{
XmlTorg12SellerTitles.Add((XmlDocumentAttachment)attachment);
}
public void AddXmlAcceptanceCertificateSellerTitle(object attachment)
{
XmlAcceptanceCertificateSellerTitles.Add((XmlDocumentAttachment)attachment);
}
public void AddAttachment(object attachment)
{
NonformalizedDocuments.Add((NonformalizedAttachment)attachment);
}
public void AddTorg12(object attachment)
{
Torg12Documents.Add((BasicDocumentAttachment)attachment);
}
public void AddAcceptanceCertificate(object attachment)
{
AcceptanceCertificates.Add((AcceptanceCertificateAttachment) attachment);
}
public void AddProformaInvoice(object attachment)
{
ProformaInvoices.Add((BasicDocumentAttachment) attachment);
}
public void AddStructuredData(object attachment)
{
StructuredDataAttachments.Add((StructuredDataAttachment) attachment);
}
public void AddPriceList(object attachment)
{
PriceLists.Add((PriceListAttachment) attachment);
}
public void AddPriceListAgreement(object attachment)
{
PriceListAgreements.Add((NonformalizedAttachment) attachment);
}
public void AddCertificateRegistry(object attachment)
{
CertificateRegistries.Add((NonformalizedAttachment) attachment);
}
public void AddReconciliationAct(object attachment)
{
ReconciliationActs.Add((ReconciliationActAttachment) attachment);
}
public void AddContract(object attachment)
{
Contracts.Add((ContractAttachment) attachment);
}
public void AddTorg13(object attachment)
{
Torg13Documents.Add((Torg13Attachment) attachment);
}
public void AddServiceDetails(object attachment)
{
ServiceDetailsDocuments.Add((ServiceDetailsAttachment) attachment);
}
public void AddSupplementaryAgreement(object supplementaryAgreement)
{
SupplementaryAgreements.Add((SupplementaryAgreementAttachment)supplementaryAgreement);
}
public void AddUniversalTransferDocumentSellerTitle(object attachment)
{
UniversalTransferDocumentSellerTitles.Add((XmlDocumentAttachment)attachment);
}
public void AddDocumentAttachment(object attachment)
{
DocumentAttachments.Add((DocumentAttachment)attachment);
}
}
[ComVisible(true)]
[Guid("107A6BD4-7E69-4084-8BBA-1211771F3391")]
public interface ITemplateToPost
{
string FromBoxId { get; set; }
string ToBoxId { get; set; }
string MessageFromBoxId { get; set; }
string MessageToBoxId { get; set; }
string MessageToDepartmentId { get; set; }
void AddDocumentAttachment([MarshalAs(UnmanagedType.IDispatch)] object attachment);
}
[ComVisible(true)]
[ProgId("Diadoc.Api.TemplateToPost")]
[Guid("F828570E-9C29-41D7-A20C-BDF2742642C5")]
[ClassInterface(ClassInterfaceType.None)]
[ComDefaultInterface(typeof(ITemplateToPost))]
public partial class TemplateToPost : SafeComObject, ITemplateToPost
{
public void AddDocumentAttachment(object attachment)
{
DocumentAttachments.Add((TemplateDocumentAttachment)attachment);
}
}
[ComVisible(true)]
[Guid("A7EC7941-1995-4B9B-A941-ED2344034A60")]
public interface ITemplateDocumentAttachment
{
UnsignedContent UnsignedContent { get; set; }
string Comment { get; set; }
string TypeNamedId { get; set; }
string Function { get; set; }
string Version { get; set; }
int WorkflowId { get; set; }
string CustomDocumentId { get; set; }
string EditingSettingId { get; set; }
bool NeedRecipientSignature { get; set; }
void SetUnsignedContent([MarshalAs(UnmanagedType.IDispatch)] object unsignedContent);
void AddMetadataItem([MarshalAs(UnmanagedType.IDispatch)] object metadataItem);
}
[ComVisible(true)]
[ProgId("Diadoc.Api.TemplateDocumentAttachment")]
[Guid("C45108E0-D1D0-46E5-B4BD-8F2AB31449B9")]
[ClassInterface(ClassInterfaceType.None)]
[ComDefaultInterface(typeof(ITemplateDocumentAttachment))]
public partial class TemplateDocumentAttachment : SafeComObject, ITemplateDocumentAttachment
{
public void SetUnsignedContent(object unsignedContent)
{
UnsignedContent = (UnsignedContent)unsignedContent;
}
public void AddMetadataItem(object metadataItem)
{
Metadata.Add((MetadataItem)metadataItem);
}
}
[ComVisible(true)]
[Guid("E23434B2-F8F8-40DA-991E-E233B976519A")]
public interface IUnsignedContent
{
byte[] Content { get; set; }
string NameOnShelf { get; set; }
void LoadContentFromFile(string fileName);
void SaveContentToFile(string fileName);
}
[ComVisible(true)]
[ProgId("Diadoc.Api.UnsignedContent")]
[Guid("7D31AA0E-DB66-4691-A9BF-B3AA98D10743")]
[ClassInterface(ClassInterfaceType.None)]
[ComDefaultInterface(typeof(IUnsignedContent))]
public partial class UnsignedContent : SafeComObject, IUnsignedContent
{
public void LoadContentFromFile(string fileName)
{
Content = File.ReadAllBytes(fileName);
}
public void SaveContentToFile(string fileName)
{
if (Content != null)
File.WriteAllBytes(fileName, Content);
}
}
[ComVisible(true)]
[Guid("0964EA37-0ACB-4BBC-9614-121303A0F373")]
public interface ITemplate
{
string MessageId { get; set; }
long TimestampTicks { get; set; }
string FromBoxId { get; set; }
string ToBoxId { get; set; }
string MessageFromBoxId { get; set; }
string MessageToBoxId { get; set; }
ReadonlyList EntitiesList { get; }
bool IsDeleted { get; set; }
}
[ComVisible(true)]
[ProgId("Diadoc.Api.Template")]
[Guid("A68E6735-893F-4B5B-8091-0B28236086B9")]
[ClassInterface(ClassInterfaceType.None)]
[ComDefaultInterface(typeof(ITemplate))]
public partial class Template : SafeComObject, ITemplate
{
public ReadonlyList EntitiesList
{
get { return new ReadonlyList(Entities); }
}
}
[ComVisible(true)]
[Guid("94ECB2DA-6C59-4130-85F4-1D63060D63F9")]
public interface ITemplateTransformationToPost
{
string BoxId { get; set; }
string TemplateId { get; set; }
void AddDocumentTransformation([MarshalAs(UnmanagedType.IDispatch)] object documentTransformation);
}
[ComVisible(true)]
[ProgId("Diadoc.Api.TemplateTransformationToPost")]
[Guid("C8339EB5-4C65-4447-8A5F-815DAEDD7A23")]
[ClassInterface(ClassInterfaceType.None)]
[ComDefaultInterface(typeof(ITemplateTransformationToPost))]
public partial class TemplateTransformationToPost : SafeComObject, ITemplateTransformationToPost
{
public void AddDocumentTransformation(object documentTransformation)
{
DocumentTransformations.Add((DocumentTransformation) documentTransformation);
}
}
[ComVisible(true)]
[Guid("7AFECE94-D0CC-4C3A-8D2C-54F41A1279FE")]
public interface IDocumentTransformation
{
string DocumentId { get; set; }
string CustomDocumentId { get; set; }
}
[ComVisible(true)]
[ProgId("Diadoc.Api.DocumentTransformation")]
[Guid("59A35A0A-5884-407C-AF4F-F9B24FBAC460")]
[ClassInterface(ClassInterfaceType.None)]
[ComDefaultInterface(typeof(IDocumentTransformation))]
public partial class DocumentTransformation : SafeComObject, IDocumentTransformation
{
}
[ComVisible(true)]
[Guid("A0C93B1F-5FD2-4738-B8F9-994AE05B5B63")]
public interface ISupplementaryAgreementAttachment
{
SignedContent SignedContent { get; set; }
string FileName { get; set; }
string Comment { get; set; }
void AddInitialDocumentId([MarshalAs(UnmanagedType.IDispatch)] object documentId);
void AddSubordinateDocumentId([MarshalAs(UnmanagedType.IDispatch)] object documentId);
string CustomDocumentId { get; set; }
string DocumentDate { get; set; }
string DocumentNumber { get; set; }
string Total { get; set; }
string ContractNumber { get; set; }
string ContractDate { get; set; }
string ContractType { get; set; }
bool NeedReceipt { get; set; }
void AddCustomDataItem([MarshalAs(UnmanagedType.IDispatch)] object customDataItem);
}
[ComVisible(true)]
[ProgId("Diadoc.Api.SupplementaryAgreementAttachment")]
[Guid("9AA39127-85C9-4B40-A456-9C18D5BF8348")]
[ClassInterface(ClassInterfaceType.None)]
[ComDefaultInterface(typeof(ISupplementaryAgreementAttachment))]
public partial class SupplementaryAgreementAttachment : SafeComObject, ISupplementaryAgreementAttachment
{
public void AddInitialDocumentId(object documentId)
{
InitialDocumentIds.Add((DocumentId)documentId);
}
public void AddSubordinateDocumentId(object documentId)
{
SubordinateDocumentIds.Add((DocumentId)documentId);
}
public void AddCustomDataItem(object customDataItem)
{
CustomData.Add((CustomDataItem)customDataItem);
}
}
[ComVisible(true)]
[Guid("0D648002-53CC-4EAB-969B-68364BB4F3CE")]
public interface IMessagePatchToPost
{
string BoxId { get; set; }
string MessageId { get; set; }
void AddReceipt([MarshalAs(UnmanagedType.IDispatch)] object receipt);
void AddCorrectionRequest([MarshalAs(UnmanagedType.IDispatch)] object correctionRequest);
void AddSignature([MarshalAs(UnmanagedType.IDispatch)] object signature);
void AddRequestedSignatureRejection(
[MarshalAs(UnmanagedType.IDispatch)] object signatureRejection);
void AddXmlTorg12BuyerTitle([MarshalAs(UnmanagedType.IDispatch)] object attachment);
void AddXmlAcceptanceCertificateBuyerTitle([MarshalAs(UnmanagedType.IDispatch)] object attachment);
void AddResolution([MarshalAs(UnmanagedType.IDispatch)] object attachment);
void AddRevocationRequestAttachment([MarshalAs(UnmanagedType.IDispatch)] object attachment);
void AddXmlSignatureRejectionAttachment([MarshalAs(UnmanagedType.IDispatch)] object attachment);
void AddUniversalTransferDocumentBuyerTitleAttachment([MarshalAs(UnmanagedType.IDispatch)] object attachment);
void AddResolutionRouteAssignment([MarshalAs(UnmanagedType.IDispatch)] object attachment);
void AddResolutoinRouteRemoval([MarshalAs(UnmanagedType.IDispatch)] object attachment);
void AddRecipientTitle([MarshalAs(UnmanagedType.IDispatch)] object attachment);
void AddCustomDataPatch([MarshalAs(UnmanagedType.IDispatch)] object editingPatch);
void AddEditingPatch([MarshalAs(UnmanagedType.IDispatch)] object editingPatch);
}
[ComVisible(true)]
[ProgId("Diadoc.Api.MessagePatchToPost")]
[Guid("F917FD6D-AEE9-4b21-A79F-11981E805F5D")]
[ClassInterface(ClassInterfaceType.None)]
[ComDefaultInterface(typeof (IMessagePatchToPost))]
public partial class MessagePatchToPost : SafeComObject, IMessagePatchToPost
{
public void AddReceipt(object receipt)
{
Receipts.Add((ReceiptAttachment)receipt);
}
public void AddCorrectionRequest(object correctionRequest)
{
CorrectionRequests.Add((CorrectionRequestAttachment)correctionRequest);
}
public void AddSignature(object signature)
{
Signatures.Add((DocumentSignature)signature);
}
public void AddRequestedSignatureRejection(object signatureRejection)
{
RequestedSignatureRejections.Add((RequestedSignatureRejection)signatureRejection);
}
public void AddXmlTorg12BuyerTitle(object attachment)
{
XmlTorg12BuyerTitles.Add((ReceiptAttachment)attachment);
}
public void AddXmlAcceptanceCertificateBuyerTitle(object attachment)
{
XmlAcceptanceCertificateBuyerTitles.Add((ReceiptAttachment)attachment);
}
public void AddUniversalTransferDocumentBuyerTitle(object attachment)
{
UniversalTransferDocumentBuyerTitles.Add((ReceiptAttachment)attachment);
}
public void AddResolution(object attachment)
{
Resolutions.Add((ResolutionAttachment)attachment);
}
public void AddResolutionRequestAttachment(object attachment)
{
ResolutionRequests.Add((ResolutionRequestAttachment)attachment);
}
public void AddResolutionRequestCancellationAttachment(object attachment)
{
ResolutionRequestCancellations.Add((ResolutionRequestCancellationAttachment)attachment);
}
public void AddResolutionRequestDenialAttachment(object attachment)
{
ResolutionRequestDenials.Add((ResolutionRequestDenialAttachment)attachment);
}
public void AddResolutionRequestDenialCancellationAttachment(object attachment)
{
ResolutionRequestDenialCancellations.Add((ResolutionRequestDenialCancellationAttachment)attachment);
}
public void AddRevocationRequestAttachment(object attachment)
{
RevocationRequests.Add((RevocationRequestAttachment)attachment);
}
public void AddXmlSignatureRejectionAttachment(object attachment)
{
XmlSignatureRejections.Add((XmlSignatureRejectionAttachment)attachment);
}
public void AddUniversalTransferDocumentBuyerTitleAttachment(object attachment)
{
UniversalTransferDocumentBuyerTitles.Add((ReceiptAttachment)attachment);
}
public void AddResolutionRouteAssignment(object attachment)
{
ResolutionRouteAssignments.Add((ResolutionRouteAssignment)attachment);
}
public void AddResolutoinRouteRemoval(object attachment)
{
ResolutionRouteRemovals.Add((ResolutionRouteRemoval)attachment);
}
public void AddRecipientTitle(object attachment)
{
RecipientTitles.Add((ReceiptAttachment)attachment);
}
public void AddCustomDataPatch(object editingPatch)
{
CustomDataPatches.Add((CustomDataPatch)editingPatch);
}
public void AddEditingPatch(object editingPatch)
{
EditingPatches.Add((CustomDataPatch)editingPatch);
}
}
[ComVisible(true)]
[Guid("10AC1159-A121-4F3E-9437-7CF22A1B60A1")]
public interface IXmlDocumentAttachment
{
string CustomDocumentId { get; set; }
SignedContent SignedContent { get; set; }
string Comment { get; set; }
void SetSignedContent([MarshalAs(UnmanagedType.IDispatch)] object signedContent);
void AddInitialDocumentId([MarshalAs(UnmanagedType.IDispatch)] object documentId);
void AddSubordinateDocumentId([MarshalAs(UnmanagedType.IDispatch)] object documentId);
}
[ComVisible(true)]
[ProgId("Diadoc.Api.XmlDocumentAttachment")]
[Guid("E6B32174-37DE-467d-A947-B88AEDC2ECEC")]
[ClassInterface(ClassInterfaceType.None)]
[ComDefaultInterface(typeof (IXmlDocumentAttachment))]
public partial class XmlDocumentAttachment : SafeComObject, IXmlDocumentAttachment
{
public void SetSignedContent(object signedContent)
{
SignedContent = (SignedContent) signedContent;
}
public void AddInitialDocumentId(object documentId)
{
InitialDocumentIds.Add((DocumentId) documentId);
}
public void AddSubordinateDocumentId(object documentId)
{
SubordinateDocumentIds.Add((DocumentId)documentId);
}
}
[ComVisible(true)]
[Guid("B43D2BF4-E100-4F49-8F8F-D87EA3ECE453")]
public interface INonformalizedAttachment
{
string CustomDocumentId { get; set; }
string FileName { get; set; }
string DocumentNumber { get; set; }
string DocumentDate { get; set; }
bool NeedRecipientSignature { get; set; }
string Comment { get; set; }
SignedContent SignedContent { get; set; }
void SetSignedContent([MarshalAs(UnmanagedType.IDispatch)] object signedContent);
void AddInitialDocumentId([MarshalAs(UnmanagedType.IDispatch)] object documentId);
void AddSubordinateDocumentId([MarshalAs(UnmanagedType.IDispatch)] object documentId);
}
[ComVisible(true)]
[ProgId("Diadoc.Api.NonformalizedAttachment")]
[Guid("9904995A-1EF3-4182-8C3E-61DBEADC159C")]
[ClassInterface(ClassInterfaceType.None)]
[ComDefaultInterface(typeof (INonformalizedAttachment))]
public partial class NonformalizedAttachment : SafeComObject, INonformalizedAttachment
{
public void SetSignedContent(object signedContent)
{
SignedContent = (SignedContent) signedContent;
}
public void AddInitialDocumentId(object documentId)
{
InitialDocumentIds.Add((DocumentId) documentId);
}
public void AddSubordinateDocumentId(object documentId)
{
SubordinateDocumentIds.Add((DocumentId) documentId);
}
}
[ComVisible(true)]
[Guid("8FC16D12-EEE7-44F1-AD9C-ACD907EF286D")]
public interface IBasicDocumentAttachment
{
string CustomDocumentId { get; set; }
string FileName { get; set; }
string DocumentNumber { get; set; }
string DocumentDate { get; set; }
string Total { get; set; }
string Vat { get; set; }
string Grounds { get; set; }
string Comment { get; set; }
SignedContent SignedContent { get; set; }
void SetSignedContent([MarshalAs(UnmanagedType.IDispatch)] object signedContent);
void AddInitialDocumentId([MarshalAs(UnmanagedType.IDispatch)] object documentId);
void AddSubordinateDocumentId([MarshalAs(UnmanagedType.IDispatch)] object documentId);
}
[ComVisible(true)]
[Guid("E7DA152C-B651-4F3A-B9D7-25F6E5BABC1D")]
public interface IAcceptanceCertificateAttachment
{
string CustomDocumentId { get; set; }
string FileName { get; set; }
string DocumentNumber { get; set; }
string DocumentDate { get; set; }
string Total { get; set; }
string Vat { get; set; }
string Grounds { get; set; }
string Comment { get; set; }
SignedContent SignedContent { get; set; }
bool NeedRecipientSignature { get; set; }
void SetSignedContent([MarshalAs(UnmanagedType.IDispatch)] object signedContent);
void AddInitialDocumentId([MarshalAs(UnmanagedType.IDispatch)] object documentId);
void AddSubordinateDocumentId([MarshalAs(UnmanagedType.IDispatch)] object documentId);
}
[ComVisible(true)]
[ProgId("Diadoc.Api.BasicDocumentAttachment")]
[Guid("776261C4-361D-42BF-929C-8B368DEE917D")]
[ClassInterface(ClassInterfaceType.None)]
[ComDefaultInterface(typeof (IBasicDocumentAttachment))]
public partial class BasicDocumentAttachment : SafeComObject, IBasicDocumentAttachment
{
public void SetSignedContent(object signedContent)
{
SignedContent = (SignedContent)signedContent;
}
public void AddInitialDocumentId(object documentId)
{
InitialDocumentIds.Add((DocumentId)documentId);
}
public void AddSubordinateDocumentId(object documentId)
{
SubordinateDocumentIds.Add((DocumentId)documentId);
}
}
[ComVisible(true)]
[ProgId("Diadoc.Api.AcceptanceCertificateAttachment")]
[Guid("9BCBE1E4-11C5-45BF-887A-FE63D074D71A")]
[ClassInterface(ClassInterfaceType.None)]
[ComDefaultInterface(typeof (IAcceptanceCertificateAttachment))]
public partial class AcceptanceCertificateAttachment : SafeComObject, IAcceptanceCertificateAttachment
{
public void SetSignedContent(object signedContent)
{
SignedContent = (SignedContent) signedContent;
}
public void AddInitialDocumentId(object documentId)
{
InitialDocumentIds.Add((DocumentId) documentId);
}
public void AddSubordinateDocumentId(object documentId)
{
SubordinateDocumentIds.Add((DocumentId) documentId);
}
}
[ComVisible(true)]
[Guid("2860C8D8-72C3-4D83-A3EB-DF36A2A8EB2E")]
public interface ITrustConnectionRequestAttachment
{
string FileName { get; set; }
string Comment { get; set; }
SignedContent SignedContent { get; set; }
void SetSignedContent([MarshalAs(UnmanagedType.IDispatch)] object signedContent);
}
[ComVisible(true)]
[ProgId("Diadoc.Api.TrustConnectionRequestAttachment")]
[Guid("139BB7DA-D92A-49F0-840A-3FB541323632")]
[ClassInterface(ClassInterfaceType.None)]
[ComDefaultInterface(typeof (ITrustConnectionRequestAttachment))]
public partial class TrustConnectionRequestAttachment : SafeComObject, ITrustConnectionRequestAttachment
{
public void SetSignedContent(object signedContent)
{
SignedContent = (SignedContent) signedContent;
}
}
[ComVisible(true)]
[Guid("DA50195B-0B15-42DB-AFE3-35C1280C9EA6")]
public interface IStructuredDataAttachment
{
string ParentCustomDocumentId { get; set; }
string FileName { get; set; }
byte[] Content { get; set; }
}
[ComVisible(true)]
[ProgId("Diadoc.Api.StructuredDataAttachment")]
[Guid("E35327B6-F774-476A-93B4-CC68DE7432D1")]
[ClassInterface(ClassInterfaceType.None)]
[ComDefaultInterface(typeof (IStructuredDataAttachment))]
public partial class StructuredDataAttachment : SafeComObject, IStructuredDataAttachment
{
}
[ComVisible(true)]
[Guid("4D8D636A-91D8-4734-8371-913E144FED66")]
public interface ISignedContent
{
byte[] Content { get; set; }
byte[] Signature { get; set; }
[Obsolete]
bool SignByAttorney { get; set; }
bool SignWithTestSignature { get; set; }
string NameOnShelf { get; set; }
void LoadContentFromFile(string fileName);
void SaveContentToFile(string fileName);
void LoadSignatureFromFile(string fileName);
void SaveSignatureToFile(string fileName);
}
[ComVisible(true)]
[Guid("A42D43EB-C083-4765-86C2-A5BD7DE58C3E")]
public interface IPriceListAttachment
{
string CustomDocumentId { get; set; }
string FileName { get; set; }
string DocumentNumber { get; set; }
string DocumentDate { get; set; }
string PriceListEffectiveDate { get; set; }
string ContractDocumentDate { get; set; }
string ContractDocumentNumber { get; set; }
string Comment { get; set; }
SignedContent SignedContent { get; set; }
void SetSignedContent([MarshalAs(UnmanagedType.IDispatch)] object signedContent);
void AddInitialDocumentId([MarshalAs(UnmanagedType.IDispatch)] object documentId);
void AddSubordinateDocumentId([MarshalAs(UnmanagedType.IDispatch)] object documentId);
}
[ComVisible(true)]
[ProgId("Diadoc.Api.PriceListAttachment")]
[Guid("2D0A054F-E3FA-4FBD-A64F-9C4EB73901BB")]
[ClassInterface(ClassInterfaceType.None)]
[ComDefaultInterface(typeof (IPriceListAttachment))]
public partial class PriceListAttachment : SafeComObject, IPriceListAttachment
{
public void SetSignedContent(object signedContent)
{
SignedContent = (SignedContent) signedContent;
}
public void AddInitialDocumentId(object documentId)
{
InitialDocumentIds.Add((DocumentId) documentId);
}
public void AddSubordinateDocumentId(object documentId)
{
SubordinateDocumentIds.Add((DocumentId) documentId);
}
}
[ComVisible(true)]
[ProgId("Diadoc.Api.SignedContent")]
[Guid("0EC71E3F-F203-4c49-B1D6-4DA6BFDD279B")]
[ClassInterface(ClassInterfaceType.None)]
[ComDefaultInterface(typeof (ISignedContent))]
public partial class SignedContent : SafeComObject, ISignedContent
{
public bool SignByAttorney
{
get { return false; }
set { }
}
public void LoadContentFromFile(string fileName)
{
Content = File.ReadAllBytes(fileName);
}
public void SaveContentToFile(string fileName)
{
if (Content != null)
File.WriteAllBytes(fileName, Content);
}
public void LoadSignatureFromFile(string fileName)
{
Signature = File.ReadAllBytes(fileName);
}
public void SaveSignatureToFile(string fileName)
{
File.WriteAllBytes(fileName, Signature);
}
}
[ComVisible(true)]
[Guid("BD1E9A9B-E74C-41AD-94CE-199601346DDB")]
public interface IDocumentSignature
{
string ParentEntityId { get; set; }
byte[] Signature { get; set; }
[Obsolete]
bool SignByAttorney { get; set; }
bool SignWithTestSignature { get; set; }
void LoadFromFile(string fileName);
}
[ComVisible(true)]
[ProgId("Diadoc.Api.DocumentSignature")]
[Guid("28373DE6-3147-4d8b-B166-6D653F50EED3")]
[ClassInterface(ClassInterfaceType.None)]
[ComDefaultInterface(typeof (IDocumentSignature))]
public partial class DocumentSignature : SafeComObject, IDocumentSignature
{
public bool SignByAttorney
{
get { return false; }
set { }
}
public void LoadFromFile(string fileName)
{
Signature = File.ReadAllBytes(fileName);
}
}
[ComVisible(true)]
[Guid("F60296C5-6981-48A7-9E93-72B819B81172")]
public interface IRequestedSignatureRejection
{
string ParentEntityId { get; set; }
SignedContent SignedContent { get; set; }
void SetSignedContent([MarshalAs(UnmanagedType.IDispatch)] object signedContent);
void LoadComment(string commentFileName, string signatureFileName);
ReadonlyList LabelsList { get; }
void AddLabel(string label);
}
[ComVisible(true)]
[ProgId("Diadoc.Api.RequestedSignatureRejection")]
[Guid("C0106095-AF9F-462A-AEC0-A3E0B1ACAC6B")]
[ClassInterface(ClassInterfaceType.None)]
[ComDefaultInterface(typeof (IRequestedSignatureRejection))]
public partial class RequestedSignatureRejection : SafeComObject, IRequestedSignatureRejection
{
public void SetSignedContent(object signedContent)
{
SignedContent = (SignedContent) signedContent;
}
public void LoadComment(string commentFileName, string signatureFileName)
{
SignedContent = new SignedContent
{
Content = File.ReadAllBytes(commentFileName),
Signature = File.ReadAllBytes(signatureFileName)
};
}
public ReadonlyList LabelsList
{
get { return new ReadonlyList(Labels); }
}
public void AddLabel(string label)
{
Labels.Add(label);
}
}
[ComVisible(true)]
[Guid("8E18ECC8-18B4-4A9C-B322-1CF03DB3E07F")]
public interface IReceiptAttachment
{
string ParentEntityId { get; set; }
SignedContent SignedContent { get; set; }
void SetSignedContent([MarshalAs(UnmanagedType.IDispatch)] object signedContent);
ReadonlyList LabelsList { get; }
void AddLabel(string label);
}
[ComVisible(true)]
[ProgId("Diadoc.Api.ReceiptAttachment")]
[Guid("45053335-83C3-4e62-9973-D6CC1872A60A")]
[ClassInterface(ClassInterfaceType.None)]
[ComDefaultInterface(typeof (IReceiptAttachment))]
public partial class ReceiptAttachment : SafeComObject, IReceiptAttachment
{
public void SetSignedContent(object signedContent)
{
SignedContent = (SignedContent) signedContent;
}
public ReadonlyList LabelsList
{
get { return new ReadonlyList(Labels); }
}
public void AddLabel(string label)
{
Labels.Add(label);
}
}
[ComVisible(true)]
[Guid("5902A325-F31B-4B9B-978E-99C1CC7C9209")]
public interface IResolutionAttachment
{
string InitialDocumentId { get; set; }
Com.ResolutionType ResolutionTypeValue { get; set; }
string Comment { get; set; }
ReadonlyList LabelsList { get; }
void AddLabel(string label);
}
[ComVisible(true)]
[ProgId("Diadoc.Api.ResolutionAttachment")]
[Guid("89D739B0-03F1-4E6C-8301-E3FEA9FD2AD6")]
[ClassInterface(ClassInterfaceType.None)]
[ComDefaultInterface(typeof (IResolutionAttachment))]
public partial class ResolutionAttachment : SafeComObject, IResolutionAttachment
{
public Com.ResolutionType ResolutionTypeValue
{
get { return (Com.ResolutionType) ResolutionType; }
set { ResolutionType = (ResolutionType) value; }
}
public ReadonlyList LabelsList
{
get { return new ReadonlyList(Labels); }
}
public void AddLabel(string label)
{
Labels.Add(label);
}
}
[ComVisible(true)]
[Guid("F19CEEBD-ECE5-49D2-A0FC-FE8C4B1B9E4C")]
public interface IResolutionRequestAttachment
{
string InitialDocumentId { get; set; }
Com.ResolutionRequestType RequestType { get; set; }
string TargetUserId { get; set; }
string TargetDepartmentId { get; set; }
string Comment { get; set; }
ReadonlyList LabelsList { get; }
void AddLabel(string label);
}
[ComVisible(true)]
[ProgId("Diadoc.Api.ResolutionRequest")]
[Guid("6043455B-3087-4A63-9870-66D54E8E34FB")]
[ClassInterface(ClassInterfaceType.None)]
[ComDefaultInterface(typeof (IResolutionRequestAttachment))]
public partial class ResolutionRequestAttachment : SafeComObject, IResolutionRequestAttachment
{
public Com.ResolutionRequestType RequestType
{
get { return (Com.ResolutionRequestType) Type; }
set { Type = (ResolutionRequestType) value; }
}
public ReadonlyList LabelsList
{
get { return new ReadonlyList(Labels); }
}
public void AddLabel(string label)
{
Labels.Add(label);
}
}
[ComVisible(true)]
[Guid("F23FCA9D-4FD3-4AE7-A431-275CAB51C7A1")]
public interface IResolutionRequestCancellationAttachment
{
string InitialResolutionRequestId { get; set; }
string Comment { get; set; }
ReadonlyList LabelsList { get; }
void AddLabel(string label);
}
[ComVisible(true)]
[ProgId("Diadoc.Api.ResolutionRequestCancellation")]
[Guid("E80B8699-9883-4259-AA67-B84B03DD5F09")]
[ClassInterface(ClassInterfaceType.None)]
[ComDefaultInterface(typeof (IResolutionRequestCancellationAttachment))]
public partial class ResolutionRequestCancellationAttachment : SafeComObject, IResolutionRequestCancellationAttachment
{
public ReadonlyList LabelsList
{
get { return new ReadonlyList(Labels); }
}
public void AddLabel(string label)
{
Labels.Add(label);
}
}
[ComVisible(true)]
[Guid("96F3613E-9DAA-4F2E-B8AB-7A8895D9E3AE")]
public interface IResolutionRequestDenialAttachment
{
string InitialResolutionRequestId { get; set; }
string Comment { get; set; }
ReadonlyList LabelsList { get; }
void AddLabel(string label);
}
[ComVisible(true)]
[ProgId("Diadoc.Api.ResolutionRequestDenial")]
[Guid("BD79962A-D6AC-4831-9498-162C36AFD6E1")]
[ClassInterface(ClassInterfaceType.None)]
[ComDefaultInterface(typeof (IResolutionRequestDenialAttachment))]
public partial class ResolutionRequestDenialAttachment : SafeComObject, IResolutionRequestDenialAttachment
{
public ReadonlyList LabelsList
{
get { return new ReadonlyList(Labels); }
}
public void AddLabel(string label)
{
Labels.Add(label);
}
}
[ComVisible(true)]
[Guid("39F44156-E889-4EFB-9368-350D1ED40B2F")]
public interface IResolutionRequestDenialCancellationAttachment
{
string InitialResolutionRequestDenialId { get; set; }
}
[ComVisible(true)]
[ProgId("Diadoc.Api.ResolutionRequestDenialCancellation")]
[Guid("4E8A0DEF-B6F7-4820-9CBE-D94A38E34DFC")]
[ClassInterface(ClassInterfaceType.None)]
[ComDefaultInterface(typeof (IResolutionRequestDenialCancellationAttachment))]
public partial class ResolutionRequestDenialCancellationAttachment : SafeComObject,
IResolutionRequestDenialCancellationAttachment
{
}
[ComVisible(true)]
[Guid("4BA8315A-FDAA-4D4F-BB14-9707E12DFA39")]
public interface ICorrectionRequestAttachment
{
string ParentEntityId { get; set; }
SignedContent SignedContent { get; set; }
void SetSignedContent([MarshalAs(UnmanagedType.IDispatch)] object signedContent);
ReadonlyList LabelsList { get; }
void AddLabel(string label);
}
[ComVisible(true)]
[ProgId("Diadoc.Api.CorrectionRequestAttachment")]
[Guid("D78FC023-2BEF-49a4-BDBE-3B791168CE98")]
[ClassInterface(ClassInterfaceType.None)]
[ComDefaultInterface(typeof (ICorrectionRequestAttachment))]
public partial class CorrectionRequestAttachment : SafeComObject, ICorrectionRequestAttachment
{
public void SetSignedContent(object signedContent)
{
SignedContent = (SignedContent)signedContent;
}
public ReadonlyList LabelsList
{
get { return new ReadonlyList(Labels); }
}
public void AddLabel(string label)
{
Labels.Add(label);
}
}
[ComVisible(true)]
[Guid("D9B32F6D-C203-49DB-B224-6B30BB1F2BAA")]
public interface IDocumentSenderSignature
{
string ParentEntityId { get; set; }
byte[] Signature { get; set; }
bool SignWithTestSignature { get; set; }
void LoadFromFile(string fileName);
}
[ComVisible(true)]
[ProgId("Diadoc.Api.DocumentSenderSignature")]
[Guid("19CB816D-F518-4E91-94A2-F19B0CF7CC71")]
[ClassInterface(ClassInterfaceType.None)]
[ComDefaultInterface(typeof(IDocumentSenderSignature))]
public partial class DocumentSenderSignature : SafeComObject, IDocumentSenderSignature
{
public void LoadFromFile(string fileName)
{
Signature = File.ReadAllBytes(fileName);
}
}
[ComVisible(true)]
[Guid("BDCD849E-F6A9-4EA4-8B84-482E10173DED")]
public interface IDraftToSend
{
string BoxId { get; set; }
string DraftId { get; set; }
string ToBoxId { get; set; }
string ToDepartmentId { get; set; }
void AddDocumentSignature([MarshalAs(UnmanagedType.IDispatch)] object signature);
}
[ComVisible(true)]
[ProgId("Diadoc.Api.DraftToSend")]
[Guid("37127975-95FC-4247-8393-052EF27D1575")]
[ClassInterface(ClassInterfaceType.None)]
[ComDefaultInterface(typeof (IDraftToSend))]
public partial class DraftToSend : SafeComObject, IDraftToSend
{
public void AddDocumentSignature(object signature)
{
DocumentSignatures.Add((DocumentSenderSignature) signature);
}
}
[ComVisible(true)]
[Guid("0A28FEDA-8108-49CE-AC56-31B16B2D036B")]
public interface IRevocationRequestAttachment
{
string ParentEntityId { get; set; }
SignedContent SignedContent { get; set; }
void SetSignedContent([MarshalAs(UnmanagedType.IDispatch)] object signedContent);
ReadonlyList LabelsList { get; }
void AddLabel(string label);
}
[ComVisible(true)]
[ProgId("Diadoc.Api.RevocationRequestAttachment")]
[Guid("D2616BCD-A691-42B5-9707-6CE12742C5D3")]
[ClassInterface(ClassInterfaceType.None)]
[ComDefaultInterface(typeof (IRevocationRequestAttachment))]
public partial class RevocationRequestAttachment : SafeComObject, IRevocationRequestAttachment
{
public void SetSignedContent(object signedContent)
{
SignedContent = (SignedContent)signedContent;
}
public ReadonlyList LabelsList
{
get { return new ReadonlyList(Labels); }
}
public void AddLabel(string label)
{
Labels.Add(label);
}
}
[ComVisible(true)]
[Guid("4EED1BE6-7136-4B46-86C7-44F9A0FFD530")]
public interface IXmlSignatureRejectionAttachment
{
string ParentEntityId { get; set; }
SignedContent SignedContent { get; set; }
void SetSignedContent([MarshalAs(UnmanagedType.IDispatch)] object signedContent);
ReadonlyList LabelsList { get; }
void AddLabel(string label);
}
[ComVisible(true)]
[ProgId("Diadoc.Api.XmlSignatureRejectionAttachment")]
[Guid("553DC13F-81B4-4010-886C-260DBD60D486")]
[ClassInterface(ClassInterfaceType.None)]
[ComDefaultInterface(typeof (IXmlSignatureRejectionAttachment))]
public partial class XmlSignatureRejectionAttachment : SafeComObject, IXmlSignatureRejectionAttachment
{
public void SetSignedContent(object signedContent)
{
SignedContent = (SignedContent) signedContent;
}
public ReadonlyList LabelsList
{
get { return new ReadonlyList(Labels); }
}
public void AddLabel(string label)
{
Labels.Add(label);
}
}
[ComVisible(true)]
[Guid("B0D2DEF2-E5B3-41FA-9D2C-10E464000141")]
public interface ICustomDataPatch
{
string ParentEntityId { get; set; }
Com.CustomDataPatchOperation OperationValue { get; set; }
string Key { get; set; }
string Value { get; set; }
}
[ComVisible(true)]
[ProgId("Diadoc.Api.CustomDataPatch")]
[Guid("784FE09D-CD92-433D-A15C-9E2F4D5E16D5")]
[ClassInterface(ClassInterfaceType.None)]
[ComDefaultInterface(typeof(ICustomDataPatch))]
public partial class CustomDataPatch : SafeComObject, ICustomDataPatch
{
public Com.CustomDataPatchOperation OperationValue
{
get { return (Com.CustomDataPatchOperation)((int)Operation); }
set { Operation = (CustomDataPatchOperation)((int)value); }
}
}
[ComVisible(true)]
[Guid("1B7169E9-455A-47C8-BD0F-5227B436CC61")]
public interface IResolutionRouteAssignment
{
string InitialDocumentId { get; set; }
string RouteId { get; set; }
string Comment { get; set; }
ReadonlyList LabelsList { get; }
void AddLabel(string label);
}
[ComVisible(true)]
[ProgId("Diadoc.Api.ResolutionRouteAssignment")]
[Guid("B4C90587-3DB9-4BFB-84A0-E1A8E082978D")]
[ClassInterface(ClassInterfaceType.None)]
[ComDefaultInterface(typeof(IResolutionRouteAssignment))]
public partial class ResolutionRouteAssignment : SafeComObject, IResolutionRouteAssignment
{
public ReadonlyList LabelsList
{
get { return new ReadonlyList(Labels); }
}
public void AddLabel(string label)
{
Labels.Add(label);
}
}
[ComVisible(true)]
[Guid("DBCE6766-25F7-4EAB-9C4F-C59AB0054E57")]
public interface IResolutionRouteRemoval
{
string ParentEntityId { get; set; }
string RouteId { get; set; }
string Comment { get; set; }
ReadonlyList LabelsList { get; }
void AddLabel(string label);
}
[ComVisible(true)]
[ProgId("Diadoc.Api.ResolutionRouteRemoval")]
[Guid("F1356D51-625B-4A24-AF11-3402D72908C8")]
[ClassInterface(ClassInterfaceType.None)]
[ComDefaultInterface(typeof(IResolutionRouteRemoval))]
public partial class ResolutionRouteRemoval : SafeComObject, IResolutionRouteRemoval
{
public ReadonlyList LabelsList
{
get { return new ReadonlyList(Labels); }
}
public void AddLabel(string label)
{
Labels.Add(label);
}
}
[ComVisible(true)]
[Guid("12A46076-9F0F-4E89-8E49-68E3C5FC8C04")]
public interface IResolutionRouteAssignmentInfo
{
string RouteId { get; }
string Author { get; }
}
[ComVisible(true)]
[Guid("AF775D73-D1BB-40C7-9DF5-D0305B606DC7")]
[ClassInterface(ClassInterfaceType.None)]
[ComDefaultInterface(typeof(IResolutionRouteAssignmentInfo))]
public partial class ResolutionRouteAssignmentInfo : SafeComObject, IResolutionRouteAssignmentInfo
{
}
[ComVisible(true)]
[Guid("180C7D5E-7E8B-48ED-BAA4-AAA29D9467CC")]
public interface IResolutionRouteRemovalInfo
{
string RouteId { get; }
string Author { get; }
}
[ComVisible(true)]
[Guid("AAB466D3-6BF3-4DB4-B7C9-DA7BD8F74837")]
[ClassInterface(ClassInterfaceType.None)]
[ComDefaultInterface(typeof(IResolutionRouteRemovalInfo))]
public partial class ResolutionRouteRemovalInfo : SafeComObject, IResolutionRouteRemovalInfo
{
}
[ComVisible(true)]
[Guid("B3A43DB5-2E18-4647-AFA5-7D90E694E59F")]
public interface IDocumentAttachment
{
SignedContent SignedContent { get; set; }
string Comment { get; set; }
bool NeedRecipientSignature { get; set; }
string CustomDocumentId { get; set; }
bool NeedReceipt { get; set; }
string TypeNamedId { get; set; }
string Function { get; set; }
string Version { get; set; }
int WorkflowId { get; set; }
bool IsEncrypted { get; set; }
void SetSignedContent([MarshalAs(UnmanagedType.IDispatch)] object signedContent);
void AddInitialDocumentId([MarshalAs(UnmanagedType.IDispatch)] object documentId);
void AddSubordinateDocumentId([MarshalAs(UnmanagedType.IDispatch)] object documentId);
void AddCustomDataItem([MarshalAs(UnmanagedType.IDispatch)] object customDataItem);
void AddMetadataItem([MarshalAs(UnmanagedType.IDispatch)] object metadataItem);
}
[ComVisible(true)]
[ProgId("Diadoc.Api.DocumentAttachment")]
[Guid("DA67FAFF-F129-4E88-BCCC-FD068EFEAC2C")]
[ClassInterface(ClassInterfaceType.None)]
[ComDefaultInterface(typeof(IDocumentAttachment))]
public partial class DocumentAttachment : SafeComObject, IDocumentAttachment
{
public void SetSignedContent(object signedContent)
{
SignedContent = (SignedContent) signedContent;
}
public void AddInitialDocumentId(object documentId)
{
InitialDocumentIds.Add((DocumentId) documentId);
}
public void AddSubordinateDocumentId(object documentId)
{
SubordinateDocumentIds.Add((DocumentId)documentId);
}
public void AddCustomDataItem(object customDataItem)
{
CustomData.Add((CustomDataItem) customDataItem);
}
public void AddMetadataItem(object metadataItem)
{
Metadata.Add((MetadataItem)metadataItem);
}
}
[ComVisible(true)]
[Guid("52727EB8-F0DD-4F50-B49F-A2825E1582A6")]
public interface IMetadataItem
{
string Key { get; set; }
string Value { get; set; }
}
[ComVisible(true)]
[ProgId("Diadoc.Api.MetadataItem")]
[Guid("8E27602B-0E75-4543-866A-8861B1C2D632")]
[ClassInterface(ClassInterfaceType.None)]
[ComDefaultInterface(typeof(IMetadataItem))]
public partial class MetadataItem : SafeComObject, IMetadataItem
{
public MetadataItem(string key, string value)
{
if (string.IsNullOrEmpty(key)) throw new ArgumentException("Key is empty");
if (string.IsNullOrEmpty(value)) throw new ArgumentException("Value is empty");
Key = key;
Value = value;
}
}
}
| |
using UnityEngine;
using System.Collections;
using System;
#if UNITY_ANDROID
public class NextpeerAndroid : INextpeer
{
private AndroidJavaClass _nextpeer;
#region Android-only interface
public void onStart()
{
if (isNextpeerInitialized())
{
_nextpeer.CallStatic("onStart");
}
}
public void onStop(Action forfeitCallback)
{
if (isNextpeerInitialized() && IsCurrentlyInTournament())
{
ReportForfeitForCurrentTournament();
// Temporary workaround until NP-167 is implemented - when we auto-forfeit the tournament, we must report it to the user.
forfeitCallback();
}
}
public bool isNextpeerInitialized()
{
return _nextpeer.CallStatic<bool>("isNextpeerInitialized");
}
#endregion
public NextpeerAndroid()
{
if (Application.platform == RuntimePlatform.Android)
{
// AndroidJNIHelper.debug = true; // Turn on only during JNI debugging sessions.
_nextpeer = new AndroidJavaClass("com.nextpeer.unity.NextpeerUnity");
}
}
public bool IsNextpeerSupported()
{
return _nextpeer.CallStatic<bool>("isNextpeerSupported");
}
public string ReleaseVersionString()
{
return _nextpeer.CallStatic<string>("getNextpeerVersion");
}
public void Init(string GameKey, NPGameSettings? Settings=null)
{
if (Settings == null)
{
_nextpeer.CallStatic("initialize", GameKey);
}
else
{
AndroidJavaObject javaSettings = new AndroidJavaObject("com.nextpeer.android.NextpeerSettings");
if (Settings.Value.NotificationPosition != null)
{
AndroidJavaClass javaNotificationPosition = new AndroidJavaClass("com.nextpeer.android.NextpeerSettings$NextpeerRankingDisplayPosition");
switch (Settings.Value.NotificationPosition.Value)
{
case NPNotificationPosition.NPNotificationPosition_TOP:
javaSettings.Set<AndroidJavaObject>("inGameNotificationPosition", javaNotificationPosition.GetStatic<AndroidJavaObject>("TOP"));
break;
case NPNotificationPosition.NPNotificationPosition_BOTTOM:
javaSettings.Set<AndroidJavaObject>("inGameNotificationPosition", javaNotificationPosition.GetStatic<AndroidJavaObject>("BOTTOM"));
break;
case NPNotificationPosition.NPNotificationPosition_LEFT:
javaSettings.Set<AndroidJavaObject>("inGameNotificationPosition", javaNotificationPosition.GetStatic<AndroidJavaObject>("LEFT"));
break;
case NPNotificationPosition.NPNotificationPosition_RIGHT:
javaSettings.Set<AndroidJavaObject>("inGameNotificationPosition", javaNotificationPosition.GetStatic<AndroidJavaObject>("RIGHT"));
break;
case NPNotificationPosition.NPNotificationPosition_TOP_LEFT:
javaSettings.Set<AndroidJavaObject>("inGameNotificationPosition", javaNotificationPosition.GetStatic<AndroidJavaObject>("TOP_LEFT"));
break;
case NPNotificationPosition.NPNotificationPosition_TOP_RIGHT:
javaSettings.Set<AndroidJavaObject>("inGameNotificationPosition", javaNotificationPosition.GetStatic<AndroidJavaObject>("TOP_RIGHT"));
break;
case NPNotificationPosition.NPNotificationPosition_BOTTOM_LEFT:
javaSettings.Set<AndroidJavaObject>("inGameNotificationPosition", javaNotificationPosition.GetStatic<AndroidJavaObject>("BOTTOM_LEFT"));
break;
case NPNotificationPosition.NPNotificationPosition_BOTTOM_RIGHT:
javaSettings.Set<AndroidJavaObject>("inGameNotificationPosition", javaNotificationPosition.GetStatic<AndroidJavaObject>("BOTTOM_RIGHT"));
break;
default:
break;
}
}
if (Settings.Value.RankingDisplayStyle != null)
{
AndroidJavaClass javaNotificationStyle = new AndroidJavaClass("com.nextpeer.android.NextpeerSettings$NextpeerRankingDisplayStyle");
switch (Settings.Value.RankingDisplayStyle.Value)
{
case NPRankingDisplayStyle.List:
javaSettings.Set<AndroidJavaObject>("inGameNotificationStyle", javaNotificationStyle.GetStatic<AndroidJavaObject>("LIST"));
break;
case NPRankingDisplayStyle.Solo:
javaSettings.Set<AndroidJavaObject>("inGameNotificationStyle", javaNotificationStyle.GetStatic<AndroidJavaObject>("SOLO"));
break;
default:
break;
}
}
if (Settings.Value.RankingDisplayAlignment != null)
{
AndroidJavaClass javaNotificationAlignment = new AndroidJavaClass("com.nextpeer.android.NextpeerSettings$NextpeerRankingDisplayAlignment");
switch (Settings.Value.RankingDisplayAlignment.Value)
{
case NPRankingDisplayAlignment.Horizontal:
javaSettings.Set<AndroidJavaObject>("inGameNotificationAlignment", javaNotificationAlignment.GetStatic<AndroidJavaObject>("HORIZONTAL"));
break;
case NPRankingDisplayAlignment.Vertical:
javaSettings.Set<AndroidJavaObject>("inGameNotificationAlignment", javaNotificationAlignment.GetStatic<AndroidJavaObject>("VERTICAL"));
break;
default:
break;
}
}
// shouldShowStatusBar will be set to false in Unity.
_nextpeer.CallStatic("initialize", GameKey, javaSettings);
}
// Force Unity to initialize our native plugin
NextpeerAndroidScreenshotHandler.SetScreenSize (Screen.width, Screen.height);
}
public void LaunchDashboard()
{
_nextpeer.CallStatic("launch");
}
public bool IsCurrentlyInTournament()
{
return _nextpeer.CallStatic<bool>("isCurrentlyInTournament");
}
public void ReportScoreForCurrentTournament(UInt32 score)
{
_nextpeer.CallStatic("reportScoreForCurrentTournament", (int)score);
}
public void ReportControlledTournamentOverWithScore(UInt32 score)
{
_nextpeer.CallStatic("reportControlledTournamentOverWithScore", (int)score);
}
public void ReportForfeitForCurrentTournament()
{
_nextpeer.CallStatic("reportForfeitForCurrentTournament");
}
public void PushDataToOtherPlayers(byte[] data)
{
_nextpeer.CallStatic("pushDataToOtherPlayers", data);
}
public void UnreliablePushDataToOtherPlayers(byte[] data)
{
_nextpeer.CallStatic("unreliablePushDataToOtherPlayers", data);
}
public void AddWhitelistTournament(string tournamentId)
{
_nextpeer.CallStatic("addWhitelistTournament", tournamentId);
}
public void RemoveWhitelistTournament(string tournamentId)
{
_nextpeer.CallStatic("removeWhitelistTournament", tournamentId);
}
public void ClearTournamentWhitelist()
{
_nextpeer.CallStatic("clearTournamentWhitelist");
}
public void AddBlacklistTournament(string tournamentId)
{
_nextpeer.CallStatic("addBlacklistTournament", tournamentId);
}
public void RemoveBlacklistTournament(string tournamentId)
{
_nextpeer.CallStatic("removeBlacklistTournament", tournamentId);
}
public void ClearTournamentBlacklist()
{
_nextpeer.CallStatic("clearTournamentBlacklist");
}
public NPGamePlayerContainer GetCurrentPlayerDetails()
{
AndroidJavaObject javaPlayer = _nextpeer.CallStatic<AndroidJavaObject>("getCurrentPlayerDetails");
NPGamePlayerContainer result = new NPGamePlayerContainer();
result.PlayerName = javaPlayer.Get<string>("playerName");
result.ProfileImageURL = javaPlayer.Get<string>("playerImageUrl");
result.PlayerId = javaPlayer.Get<string>("playerId");
return result;
}
public void EnableRankingDisplay(bool enableRankingDisplay)
{
_nextpeer.CallStatic("enableRankingDisplay", enableRankingDisplay);
}
public void SetNextpeerNotSupportedShouldShowCustomErrors(Boolean ShowError)
{
}
public NPTournamentStartDataContainer GetTournamentStartData()
{
AndroidJavaObject javaStartData = _nextpeer.CallStatic<AndroidJavaObject>("getTournamentStartData");
NPTournamentStartDataContainer result = new NPTournamentStartDataContainer();
result.TournamentUUID = javaStartData.Get<string>("tournamentUuid");
result.TournamentRandomSeed = unchecked( (uint)javaStartData.Get<int>("tournamentRandomSeed") );
result.TournamentName = javaStartData.Get<string>("tournamentName");
result.TournamentNumberOfPlayers = (uint)javaStartData.Get<int>("numberOfPlayers");
result.CurrentPlayer = GetTournamentPlayer(javaStartData.Get<AndroidJavaObject>("currentPlayer"));
AndroidJavaObject javaOpponents = javaStartData.Get<AndroidJavaObject>("opponents");
result.Opponents = new NPTournamentPlayer[result.TournamentNumberOfPlayers - 1];
for (int opponentIndex = 0; opponentIndex < result.TournamentNumberOfPlayers - 1; opponentIndex++)
{
result.Opponents[opponentIndex] = GetTournamentPlayer(javaOpponents.Call<AndroidJavaObject>("get", opponentIndex));
}
return result;
}
public NPTournamentCustomMessageContainer ConsumeReliableCustomMessage(String id)
{
return ConsumeCustomMessage<NPTournamentCustomMessageContainer>(id);
}
public NPTournamentUnreliableCustomMessageContainer ConsumeUnreliableCustomMessage(String id)
{
return ConsumeCustomMessage<NPTournamentUnreliableCustomMessageContainer>(id);
}
private TMessage ConsumeCustomMessage<TMessage>(String messageKey)
where TMessage : NPTournamentCustomMessageBase, new()
{
AndroidJavaObject javaMessage = null;
try
{
javaMessage = _nextpeer.CallStatic<AndroidJavaObject>("retrieveObjectWithId", messageKey);
}
catch (Exception e)
{
// Probably the object is not there and we got "null" from Java.
return null;
}
TMessage result = new TMessage();
result.Message = javaMessage.Get<byte[]>("customMessage");
result.PlayerID = javaMessage.Get<string>("playerId");
result.ProfileImageUrl = javaMessage.Get<string>("playerImageUrl");
result.PlayerIsBot = javaMessage.Get<bool>("playerIsBot");
result.PlayerName = javaMessage.Get<string>("playerName");
return result;
}
public NPTournamentStatusInfo? ConsumeTournamentStatusInfo(String messageKey)
{
AndroidJavaObject javaTournamentStatus = null;
try
{
javaTournamentStatus = _nextpeer.CallStatic<AndroidJavaObject>("retrieveObjectWithId", messageKey);
}
catch (Exception e)
{
// Probably the object is not there and we got "null" from Java.
return null;
}
AndroidJavaObject javaSortedResults = javaTournamentStatus.Get<AndroidJavaObject>("sortedResults");
int resultsCount = javaSortedResults.Call<int>("size");
NPTournamentPlayerResults[] sortedResults = new NPTournamentPlayerResults[resultsCount];
for (int resultsIndex = 0; resultsIndex < resultsCount; resultsIndex++)
{
AndroidJavaObject javaPlayerResult = javaSortedResults.Call<AndroidJavaObject>("get", resultsIndex);
AndroidJavaObject javaPlayer = javaPlayerResult.Get<AndroidJavaObject>("player");
NPTournamentPlayerResults playerResult = new NPTournamentPlayerResults();
playerResult.Player = GetTournamentPlayer(javaPlayer);
playerResult.DidForfeit = javaPlayerResult.Get<bool>("didForfeit");
playerResult.IsStillPlaying = javaPlayerResult.Get<bool>("isStillPlaying");
playerResult.Score = (uint)javaPlayerResult.Get<int>("score");
sortedResults[resultsIndex] = playerResult;
}
NPTournamentStatusInfo result = new NPTournamentStatusInfo();
result.SortedResults = sortedResults;
return result;
}
public void RemoveStoredObjectWithId(String MessageID)
{
_nextpeer.CallStatic("removeStoredObjectWithId", MessageID);
}
public NPTournamentEndDataContainer GetTournamentResult()
{
AndroidJavaObject javaEndData = _nextpeer.CallStatic<AndroidJavaObject>("getTournamentResult");
NPTournamentEndDataContainer result = new NPTournamentEndDataContainer();
result.TournamentUUID = javaEndData.Get<string>("tournamentUuid");
result.TournamentTotalPlayers = (uint)javaEndData.Get<int>("tournamentTotalPlayers");
AndroidJavaObject javaCurrentPlayer = javaEndData.Get<AndroidJavaObject>("currentPlayer");
result.PlayerName = javaCurrentPlayer.Get<string>("playerName");
return result;
}
public void RegisterToSyncEvent(string eventName, TimeSpan timeout)
{
_nextpeer.CallStatic("registerToSynchronizedEvent", eventName, (int)timeout.TotalSeconds);
}
public void CaptureMoment()
{
_nextpeer.CallStatic("captureMoment");
}
public bool ConsumeSyncEventInfo(string syncEventInfoId, ref string eventName, ref NPSynchronizedEventFireReason fireReason)
{
AndroidJavaObject javaMessage = null;
try
{
javaMessage = _nextpeer.CallStatic<AndroidJavaObject>("retrieveObjectWithId", syncEventInfoId);
}
catch (Exception e)
{
// Probably the object is not there and we got "null" from Java.
return false;
}
eventName = javaMessage.Call<String>("getEventName");
AndroidJavaObject javaFireReason = javaMessage.Call<AndroidJavaObject>("getFireReason");
AndroidJavaClass javaFireReasonEnum = new AndroidJavaClass("com.nextpeer.android.NextpeerSynchronizedEventFire");
if (javaFireReason.Call<bool>("equals", javaFireReasonEnum.GetStatic<AndroidJavaObject>("ALL_REACHED")))
{
fireReason = NPSynchronizedEventFireReason.AllReached;
}
else if (javaFireReason.Call<bool>("equals", javaFireReasonEnum.GetStatic<AndroidJavaObject>("ALREADY_FIRED")))
{
fireReason = NPSynchronizedEventFireReason.AlreadyFired;
}
else if (javaFireReason.Call<bool>("equals", javaFireReasonEnum.GetStatic<AndroidJavaObject>("TIMEOUT")))
{
fireReason = NPSynchronizedEventFireReason.Timeout;
}
return true;
}
private NPTournamentPlayer GetTournamentPlayer(AndroidJavaObject javaPlayer)
{
NPTournamentPlayer player = new NPTournamentPlayer();
player.IsCurrentUser = javaPlayer.Call<bool>("isCurrentUser");
player.PlayerIsBot = javaPlayer.Get<bool>("playerIsBot");
player.PlayerId = javaPlayer.Get<string>("playerId");
player.PlayerImageUrl = javaPlayer.Get<string>("playerImageUrl");
player.PlayerName = javaPlayer.Get<string>("playerName");
return player;
}
//Recording manipulation
public void ReportScoreModifier (String userId, Int32 scoreModifier){
_nextpeer.CallStatic("reportScoreModifier", userId, scoreModifier);
}
public void RequestFastForwardRecording (String userId, TimeSpan timeDelta){
_nextpeer.CallStatic("requestFastForwardRecording", userId, (int)timeDelta.TotalMilliseconds);
}
public void RequestPauseRecording (String userId){
_nextpeer.CallStatic("requestPauseRecording", userId);
}
public void RequestResumeRecording (String userId){
_nextpeer.CallStatic("requestResumeRecording", userId);
}
public void RequestRewindRecording(String userId, TimeSpan timeDelta){
_nextpeer.CallStatic("requestRewindRecording", userId, (int)timeDelta.TotalMilliseconds);
}
public void RequestStopRecording(String userId){
_nextpeer.CallStatic("requestStopRecording", userId);
}
}
#endif
| |
// Copyright (c) 2011 Smarkets Limited
//
// 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.Generic;
#if NET40
using System.Collections.Concurrent;
#else
using IronSmarkets.System.Collections.Concurrent;
#endif
using System.Diagnostics;
using System.Linq;
using System.Threading;
using log4net;
using IronSmarkets.Events;
using IronSmarkets.Exceptions;
using IronSmarkets.Messages;
using IronSmarkets.Proto.Seto;
using IronSmarkets.Sockets;
using Eto = IronSmarkets.Proto.Eto;
namespace IronSmarkets.Sessions
{
public sealed class SeqSession : IDisposable, ISession<Payload>
{
private static readonly ILog Log = LogManager.GetLogger(typeof(SeqSession));
private readonly ISocket<Payload> _socket;
private readonly ISessionSettings _settings;
private readonly ConcurrentQueue<Payload> _sendBuffer =
new ConcurrentQueue<Payload>();
private readonly ManualResetEvent _logoutReceived =
new ManualResetEvent(false);
private readonly object _reader = new object();
private readonly object _writer = new object();
private int _disposed;
private ulong _inSequence;
private ulong _outSequence;
private string _sessionId;
private bool _loginSent;
private Predicate<Payload> _payloadHandler;
public ulong InSequence { get { return _inSequence; } }
public ulong OutSequence { get { return _outSequence; } }
public string SessionId { get { return _sessionId; } }
public event EventHandler<PayloadReceivedEventArgs<Payload>> PayloadReceived;
public event EventHandler<PayloadReceivedEventArgs<Payload>> PayloadSent;
public SeqSession(
ISocket<Payload> socket,
ISessionSettings sessionSettings)
{
_socket = socket;
_settings = sessionSettings;
_inSequence = _settings.InSequence;
_outSequence = _settings.OutSequence;
}
public bool IsDisposed
{
get
{
return Thread.VolatileRead(ref _disposed) == 1;
}
}
~SeqSession()
{
Dispose(false);
}
public ulong Login()
{
if (IsDisposed)
throw new ObjectDisposedException(
"SeqSession",
"Called Login on disposed object");
if (_loginSent)
{
throw new InvalidOperationException(
"Login payload has already been sent, " +
"ignoring Login() call.");
}
if (Log.IsDebugEnabled) Log.Debug("Opening socket connection");
_socket.Connect();
var loginPayload = Payloads.Login(_settings.Username,
_settings.Password);
if (_settings.SessionId != null)
{
if (Log.IsDebugEnabled) Log.Debug("Adding session id to payload");
// We are resuming a session
loginPayload.EtoPayload.Login = new Eto.Login {
Session = _settings.SessionId
};
}
if (Log.IsDebugEnabled) Log.Debug("Sending login payload");
var loginSeq = Send(loginPayload).Last();
if (Log.IsDebugEnabled) Log.Debug("Receiving login response payload");
var response = Receive();
_loginSent = true;
_logoutReceived.Reset();
if (response.EtoPayload.Type == Eto.PayloadType.PAYLOADLOGOUT)
{
string message;
switch (response.EtoPayload.Logout.Reason) {
case Eto.LogoutReason.LOGOUTLOGINTIMEOUT:
message = "Login timeout";
break;
case Eto.LogoutReason.LOGOUTUNKNOWNSESSION:
message = "Unknown session ID";
break;
case Eto.LogoutReason.LOGOUTUNAUTHORISED:
message = "Bad username/password";
break;
case Eto.LogoutReason.LOGOUTSERVICETEMPORARILYUNAVAILABLE:
message = "Service temporarily unavailable";
break;
default:
message = "Login failed (see reason enum)";
break;
}
Log.Warn(
string.Format(
"Received a logout payload after login sent: {0}",
response.EtoPayload.Logout.Reason));
throw new LoginFailedException(message, response.EtoPayload.Logout.Reason);
}
if (response.EtoPayload.Type == Eto.PayloadType.PAYLOADLOGINRESPONSE)
{
_sessionId = response.EtoPayload.LoginResponse.Session;
_outSequence = response.EtoPayload.LoginResponse.Reset;
if (Log.IsInfoEnabled) Log.Info(
string.Format(
"Login response received with session {0}, reset {1}",
_sessionId, _outSequence));
}
return loginSeq;
}
public ulong Logout()
{
if (!_loginSent)
throw new NotLoggedInException();
var logoutPayload = Payloads.Logout();
if (Log.IsDebugEnabled) Log.Debug(
"Sending logout payload with 'none' reason");
Send(logoutPayload);
// Block
_logoutReceived.WaitOne();
return logoutPayload.EtoPayload.Seq;
}
public void SendPayload(Payload payload)
{
Send(payload);
}
public IEnumerable<ulong> Send(Payload payload)
{
return Send(payload, true);
}
public IEnumerable<ulong> Send(Payload payload, bool flush)
{
if (IsDisposed)
throw new ObjectDisposedException(
"SeqSession",
"Called Send on disposed object");
if (payload.EtoPayload == null)
payload.EtoPayload = new Eto.Payload();
if (Log.IsDebugEnabled) Log.Debug(
string.Format(
"Buffering payload {0} / {1}",
payload.Type, payload.EtoPayload.Type));
_sendBuffer.Enqueue(payload);
if (flush)
{
if (Log.IsDebugEnabled) Log.Debug(
"Flushing payloads after buffering");
return Flush();
}
return Enumerable.Empty<ulong>();
}
public IEnumerable<ulong> Flush()
{
if (IsDisposed)
throw new ObjectDisposedException(
"SeqSession",
"Called Send on disposed object");
bool writerAcquired = false;
try
{
if (Log.IsDebugEnabled) Log.Debug("Acquiring writer lock");
#if NET40
Monitor.Enter(_writer, ref writerAcquired);
#else
writerAcquired = Monitor.TryEnter(_writer);
#endif
if (Log.IsDebugEnabled) Log.Debug("Writer lock acquired");
var seqs = new List<ulong>(_sendBuffer.Count);
if (Log.IsDebugEnabled) Log.Debug(
string.Format(
"Flushing send buffer of size {0}",
_sendBuffer.Count));
Payload outPayload;
while (_sendBuffer.TryDequeue(out outPayload))
{
outPayload.EtoPayload.Seq = _outSequence;
if (Log.IsDebugEnabled) Log.Debug(
string.Format(
"Writing payload out:{0}",
_outSequence));
_socket.Write(outPayload);
OnPayloadSent(outPayload);
seqs.Add(_outSequence++);
}
_socket.Flush();
return seqs;
}
finally
{
if (writerAcquired)
{
if (Log.IsDebugEnabled) Log.Debug(
"Releasing writer lock");
Monitor.Exit(_writer);
}
}
}
public Payload Receive()
{
if (IsDisposed)
throw new ObjectDisposedException(
"SeqSession",
"Called Receive on disposed object");
bool readerAcquired = false;
try
{
if (Log.IsDebugEnabled) Log.Debug("Acquiring reader lock");
#if NET40
Monitor.Enter(_reader, ref readerAcquired);
#else
readerAcquired = Monitor.TryEnter(_reader);
#endif
if (Log.IsDebugEnabled) Log.Debug(
"Reading next payload from socket...");
var payload = _socket.Read();
if (payload == null)
{
throw new MessageStreamException(
"Empty payload was received. " +
"Socket was probably closed prematurely");
}
if (!OnPayloadReceived(payload))
{
throw new MessageStreamException(
"Payload pipeline aborted by handler");
}
if (Log.IsDebugEnabled) Log.Debug(
string.Format(
"Received payload {0} / {1}", payload.Type,
payload.EtoPayload.Type));
if (payload.EtoPayload.Seq == _inSequence)
{
_inSequence++;
if (payload.IsLogoutConfirmation())
_logoutReceived.Set();
if (payload.EtoPayload.Type == Eto.PayloadType.PAYLOADHEARTBEAT)
{
if (Log.IsDebugEnabled) Log.Debug(
string.Format(
"Received heartbeat, sending heartbeat"));
Send(Payloads.Heartbeat());
}
return payload;
}
if (payload.EtoPayload.Type == Eto.PayloadType.PAYLOADREPLAY)
{
// Replay message
return payload;
}
if (payload.EtoPayload.Seq > _inSequence)
{
var replayPayload = Payloads.Replay(_inSequence);
// Do not flush the send because we do not want a
// deadlock.
Log.Warn(
string.Format(
"Received sequence {0} but expected {1}; " +
"buffering a replay payload",
payload.EtoPayload.Seq, _inSequence));
Send(replayPayload, false);
}
}
finally
{
if (readerAcquired)
{
if (Log.IsDebugEnabled) Log.Debug(
"Releasing reader lock");
Monitor.Exit(_reader);
}
}
// TODO: Provide some more information here
throw new MessageStreamException(
"Unable to handle payload received.");
}
public void Disconnect()
{
if (Log.IsInfoEnabled) Log.Info("Disconnecting socket");
var disp = _socket as IDisposable;
if (disp != null)
disp.Dispose();
}
public void AddPayloadHandler(Predicate<Payload> predicate)
{
if (null == _payloadHandler)
{
_payloadHandler = predicate;
}
else
{
_payloadHandler += predicate;
}
}
public void RemovePayloadHandler(Predicate<Payload> predicate)
{
Debug.Assert(_payloadHandler != null, "_payloadHandler != null");
_payloadHandler -= predicate;
}
private bool OnPayloadReceived(Payload payload)
{
EventHandler<PayloadReceivedEventArgs<Payload>> ev = PayloadReceived;
if (ev != null)
ev(this, new PayloadReceivedEventArgs<Payload>(
payload.EtoPayload.Seq,
payload));
if (_payloadHandler == null)
throw new NoHandlerException();
return _payloadHandler.GetInvocationList().Cast<Predicate<Payload>>().All(handler => handler(payload));
}
private void OnPayloadSent(Payload payload)
{
EventHandler<PayloadReceivedEventArgs<Payload>> ev = PayloadSent;
if (ev != null)
ev(this, new PayloadReceivedEventArgs<Payload>(
payload.EtoPayload.Seq,
payload));
}
private void Dispose(bool disposing)
{
if (Interlocked.CompareExchange(ref _disposed, 1, 0) == 0)
{
if (disposing)
{
Disconnect();
}
}
}
void IDisposable.Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
}
}
| |
using Cosmos.Debug.Kernel;
using IL2CPU.API.Attribs;
using System;
using System.Collections.Generic;
namespace Cosmos.Core_Plugs.System.Collections.Generic
{
[Plug("System.Collections.Generic.ComparerHelpers, System.Private.CoreLib")]
public static class ComparerHelpersImpl
{
private static readonly Debugger mDebugger = new Debugger("Core", "ComparerHelpersImpl");
public static object CreateDefaultComparer(Type aType)
{
//TODO: Do application level testing to determine the most frequent comparisons and do those type checks first.
if (aType == typeof(byte))
{
return new ByteComparer();
}
//if (aType == typeof(Byte?))
//{
// return new NullableByteComparer();
//}
if (aType == typeof(sbyte))
{
return new SByteComparer();
}
//if (aType == typeof(SByte?))
//{
// return new NullableSByteComparer();
//}
if (aType == typeof(string))
{
return new StringComparer();
}
if (aType == typeof(int))
{
return new Int32Comparer();
}
//if (aType == typeof(Int32?))
//{
// return new NullableInt32Comparer();
//}
if (aType == typeof(uint))
{
return new UInt32Comparer();
}
//if (aType == typeof(UInt32?))
//{
// return new NullableUInt32Comparer();
//}
if (aType == typeof(long))
{
return new Int64Comparer();
}
//if (aType == typeof(Int64?))
//{
// return new NullableInt64Comparer();
//}
if (aType == typeof(ulong))
{
return new UInt64Comparer();
}
//if (aType == typeof(UInt64?))
//{
// return new NullableUInt64Comparer();
//}
if (aType == typeof(char))
{
return new CharComparer();
}
//if (aType == typeof(Char?))
//{
// return new NullableCharComparer();
//}
if (aType == typeof(short))
{
return new Int16Comparer();
}
//if (aType == typeof(Int16?))
//{
// return new NullableInt16Comparer();
//}
if (aType == typeof(ushort))
{
return new UInt16Comparer();
}
//if (aType == typeof(UInt16?))
//{
// return new NullableUInt16Comparer();
//}
if (aType == typeof(Guid))
{
return new GuidComparer();
}
//if (aType == typeof(Guid?))
//{
// return new NullableGuidComparer();
//}
if (aType.IsEnum)
{
switch (Type.GetTypeCode(Enum.GetUnderlyingType(aType)))
{
case TypeCode.SByte:
return new SByteComparer();
case TypeCode.Byte:
return new ByteComparer();
case TypeCode.Int16:
return new Int16Comparer();
case TypeCode.UInt16:
return new UInt16Comparer();
case TypeCode.Int32:
return new Int32Comparer();
case TypeCode.UInt32:
return new UInt32Comparer();
case TypeCode.Int64:
return new Int64Comparer();
case TypeCode.UInt64:
return new UInt64Comparer();
default:
return null;
}
}
//MS framework falls back to address compare so we'll do the same.
//mDebugger.Send($"No Comparer for type {aType}");
return new ObjectComparer();
}
public static object CreateDefaultEqualityComparer(Type aType)
{
//TODO: Do application level testing to determine the most frequent comparisons and do those type checks first.
if (aType == typeof(byte))
{
return new ByteEqualityComparer();
}
//if (aType == typeof(Byte?))
//{
// return new NullableByteEqualityComparer();
//}
if (aType == typeof(sbyte))
{
return new SByteEqualityComparer();
}
//if (aType == typeof(SByte?))
//{
// return new NullableSByteEqualityComparer();
//}
if (aType == typeof(string))
{
return new StringEqualityComparer();
}
if (aType == typeof(int))
{
return new Int32EqualityComparer();
}
//if (aType == typeof(Int32?))
//{
// return new NullableInt32EqualityComparer();
//}
if (aType == typeof(uint))
{
return new UInt32EqualityComparer();
}
//if (aType == typeof(UInt32?))
//{
// return new NullableUInt32EqualityComparer();
//}
if (aType == typeof(long))
{
return new Int64EqualityComparer();
}
//if (aType == typeof(Int64?))
//{
// return new NullableInt64EqualityComparer();
//}
if (aType == typeof(ulong))
{
return new UInt64EqualityComparer();
}
//if (aType == typeof(UInt64?))
//{
// return new NullableUInt64EqualityComparer();
//}
if (aType == typeof(char))
{
return new CharEqualityComparer();
}
//if (aType == typeof(Char?))
//{
// return new NullableCharEqualityComparer();
//}
if (aType == typeof(short))
{
return new Int16EqualityComparer();
}
//if (aType == typeof(Int16?))
//{
// return new NullableInt16EqualityComparer();
//}
if (aType == typeof(ushort))
{
return new UInt16EqualityComparer();
}
//if (aType == typeof(UInt16?))
//{
// return new NullableUInt16EqualityComparer();
//}
if (aType == typeof(Guid))
{
return new GuidEqualityComparer();
}
//if (aType == typeof(Guid?))
//{
// return new NullableGuidEqualityComparer();
//}
//if (aType.IsEnum)
//{
// switch (Type.GetTypeCode(Enum.GetUnderlyingType(aType)))
// {
// case TypeCode.SByte:
// return new SByteEqualityComparer();
// case TypeCode.Byte:
// return new ByteEqualityComparer();
// case TypeCode.Int16:
// return new Int16EqualityComparer();
// case TypeCode.UInt16:
// return new UInt16EqualityComparer();
// case TypeCode.Int32:
// return new Int32EqualityComparer();
// case TypeCode.UInt32:
// return new UInt32EqualityComparer();
// case TypeCode.Int64:
// return new Int64EqualityComparer();
// case TypeCode.UInt64:
// return new UInt64EqualityComparer();
// default:
// return null;
// }
//}
//MS framework falls back to address compare so we'll do the same.
//mDebugger.Send($"No EqualityComparer for type {aType}");
//return null;
return new ObjectEqualityComparer();
}
}
#region "Comparer"
public class StringComparer : Comparer<string>
{
public override int Compare(string x, string y)
{
return String.Compare(x, y);
}
}
public class CharComparer : Comparer<char>
{
public override int Compare(char x, char y)
{
return x.CompareTo(y);
}
}
//public class NullableCharComparer : Comparer<Char?>
//{
// public override int Compare(Char? x, Char? y)
// {
// if (x.HasValue && y.HasValue)
// {
// return x.Value.CompareTo(y.Value);
// }
// if (!x.HasValue)
// {
// return -1;
// }
// if (!y.HasValue)
// {
// return 1;
// }
// return 0;
// }
//}
public class ByteComparer : Comparer<byte>
{
public override int Compare(byte x, byte y)
{
return x.CompareTo(y);
}
}
//public class NullableByteComparer : Comparer<Byte?>
//{
// public override int Compare(Byte? x, Byte? y)
// {
// if (x.HasValue && y.HasValue)
// {
// return x.Value.CompareTo(y.Value);
// }
// if (!x.HasValue)
// {
// return -1;
// }
// if (!y.HasValue)
// {
// return 1;
// }
// return 0;
// }
//}
public class SByteComparer : Comparer<sbyte>
{
public override int Compare(sbyte x, sbyte y)
{
return x.CompareTo(y);
}
}
//public class NullableSByteComparer : Comparer<SByte?>
//{
// public override int Compare(SByte? x, SByte? y)
// {
// if (x.HasValue && y.HasValue)
// {
// return x.Value.CompareTo(y.Value);
// }
// if (!x.HasValue)
// {
// return -1;
// }
// if (!y.HasValue)
// {
// return 1;
// }
// return 0;
// }
//}
public class Int16Comparer : Comparer<short>
{
public override int Compare(short x, short y)
{
return x.CompareTo(y);
}
}
//public class NullableInt16Comparer : Comparer<Int16?>
//{
// public override int Compare(Int16? x, Int16? y)
// {
// if (x.HasValue && y.HasValue)
// {
// return x.Value.CompareTo(y.Value);
// }
// if (!x.HasValue)
// {
// return -1;
// }
// if (!y.HasValue)
// {
// return 1;
// }
// return 0;
// }
//}
public class UInt16Comparer : Comparer<ushort>
{
public override int Compare(ushort x, ushort y)
{
return x.CompareTo(y);
}
}
//public class NullableUInt16Comparer : Comparer<UInt16?>
//{
// public override int Compare(UInt16? x, UInt16? y)
// {
// if (x.HasValue && y.HasValue)
// {
// return x.Value.CompareTo(y.Value);
// }
// if (!x.HasValue)
// {
// return -1;
// }
// if (!y.HasValue)
// {
// return 1;
// }
// return 0;
// }
//}
public class Int32Comparer : Comparer<int>
{
public override int Compare(int x, int y)
{
return x.CompareTo(y);
}
}
//public class NullableInt32Comparer : Comparer<Int32?>
//{
// public override int Compare(Int32? x, Int32? y)
// {
// if (x.HasValue && y.HasValue)
// {
// return x.Value.CompareTo(y.Value);
// }
// if (!x.HasValue)
// {
// return -1;
// }
// if (!y.HasValue)
// {
// return 1;
// }
// return 0;
// }
//}
public class UInt32Comparer : Comparer<uint>
{
public override int Compare(uint x, uint y)
{
return x.CompareTo(y);
}
}
//public class NullableUInt32Comparer : Comparer<UInt32?>
//{
// public override int Compare(UInt32? x, UInt32? y)
// {
// if (x.HasValue && y.HasValue)
// {
// return x.Value.CompareTo(y.Value);
// }
// if (!x.HasValue)
// {
// return -1;
// }
// if (!y.HasValue)
// {
// return 1;
// }
// return 0;
// }
//}
public class Int64Comparer : Comparer<long>
{
public override int Compare(long x, long y)
{
return x.CompareTo(y);
}
}
//public class NullableInt64Comparer : Comparer<Int64?>
//{
// public override int Compare(Int64? x, Int64? y)
// {
// if (x.HasValue && y.HasValue)
// {
// return x.Value.CompareTo(y.Value);
// }
// if (!x.HasValue)
// {
// return -1;
// }
// if (!y.HasValue)
// {
// return 1;
// }
// return 0;
// }
//}
public class UInt64Comparer : Comparer<ulong>
{
public override int Compare(ulong x, ulong y)
{
return x.CompareTo(y);
}
}
//public class NullableUInt64Comparer : Comparer<UInt64?>
//{
// public override int Compare(UInt64? x, UInt64? y)
// {
// if (x.HasValue && y.HasValue)
// {
// return x.Value.CompareTo(y.Value);
// }
// if (!x.HasValue)
// {
// return -1;
// }
// if (!y.HasValue)
// {
// return 1;
// }
// return 0;
// }
//}
public class GuidComparer : Comparer<Guid>
{
public override int Compare(Guid x, Guid y)
{
return x.CompareTo(y);
}
}
//public class NullableGuidComparer : Comparer<Guid?>
//{
// public override int Compare(Guid? x, Guid? y)
// {
// if (x.HasValue && y.HasValue)
// {
// return x.Value.CompareTo(y.Value);
// }
// if (!x.HasValue)
// {
// return -1;
// }
// if (!y.HasValue)
// {
// return 1;
// }
// return 0;
// }
//}
public class ObjectComparer : Comparer<object>
{
public override int Compare(object x, object y)
{
if (x == null && y == null)
{
return 0;
}
string text = x as string;
string text2 = y as string;
if (text != null && text2 != null)
{
return String.Compare(text, text2);
}
IComparable comparable = x as IComparable;
if (comparable != null)
{
return comparable.CompareTo(y);
}
IComparable comparable2 = y as IComparable;
if (comparable2 != null)
{
return -comparable2.CompareTo(x);
}
throw new NotImplementedException();
}
}
#endregion
#region "EqualityComparer"
public class StringEqualityComparer : EqualityComparer<string>
{
public override bool Equals(string x, string y)
{
return String.Equals(x, y);
}
public override int GetHashCode(string obj)
{
return obj.GetHashCode();
}
}
public class CharEqualityComparer : EqualityComparer<char>
{
public override bool Equals(char x, char y)
{
return Char.Equals(x, y);
}
public override int GetHashCode(char val)
{
return val.GetHashCode();
}
}
//public class NullableCharEqualityComparer : EqualityComparer<Char?>
//{
// public override bool Equals(Char? x, Char? y)
// {
// if (x.HasValue)
// {
// if (y.HasValue)
// {
// return Char.Equals(x.Value, y.Value);
// }
// return false;
// }
// if (y.HasValue)
// {
// return false;
// }
// return true;
// }
// public override int GetHashCode(Char? val)
// {
// return val.HasValue ? val.Value.GetHashCode() : 0;
// }
//}
public class ByteEqualityComparer : EqualityComparer<byte>
{
public override bool Equals(byte x, byte y)
{
return Byte.Equals(x, y);
}
public override int GetHashCode(byte val)
{
return val.GetHashCode();
}
}
//public class NullableByteEqualityComparer : EqualityComparer<Byte?>
//{
// public override bool Equals(Byte? x, Byte? y)
// {
// if (x.HasValue)
// {
// if (y.HasValue)
// {
// return Byte.Equals(x.Value, y.Value);
// }
// return false;
// }
// if (y.HasValue)
// {
// return false;
// }
// return true;
// }
// public override int GetHashCode(Byte? val)
// {
// return val.HasValue ? val.Value.GetHashCode() : 0;
// }
//}
public class SByteEqualityComparer : EqualityComparer<sbyte>
{
public override bool Equals(sbyte x, sbyte y)
{
return SByte.Equals(x, y);
}
public override int GetHashCode(sbyte val)
{
return val.GetHashCode();
}
}
//public class NullableSByteEqualityComparer : EqualityComparer<SByte?>
//{
// public override bool Equals(SByte? x, SByte? y)
// {
// if (x.HasValue)
// {
// if (y.HasValue)
// {
// return SByte.Equals(x.Value, y.Value);
// }
// return false;
// }
// if (y.HasValue)
// {
// return false;
// }
// return true;
// }
// public override int GetHashCode(SByte? val)
// {
// return val.HasValue ? val.Value.GetHashCode() : 0;
// }
//}
public class Int16EqualityComparer : EqualityComparer<short>
{
public override bool Equals(short x, short y)
{
return Int16.Equals(x, y);
}
public override int GetHashCode(short val)
{
return val.GetHashCode();
}
}
//public class NullableInt16EqualityComparer : EqualityComparer<Int16?>
//{
// public override bool Equals(Int16? x, Int16? y)
// {
// if (x.HasValue)
// {
// if (y.HasValue)
// {
// return Int16.Equals(x.Value, y.Value);
// }
// return false;
// }
// if (y.HasValue)
// {
// return false;
// }
// return true;
// }
// public override int GetHashCode(Int16? val)
// {
// return val.HasValue ? val.Value.GetHashCode() : 0;
// }
//}
public class UInt16EqualityComparer : EqualityComparer<ushort>
{
public override bool Equals(ushort x, ushort y)
{
return UInt16.Equals(x, y);
}
public override int GetHashCode(ushort val)
{
return val.GetHashCode();
}
}
//public class NullableUInt16EqualityComparer : EqualityComparer<UInt16?>
//{
// public override bool Equals(UInt16? x, UInt16? y)
// {
// if (x.HasValue)
// {
// if (y.HasValue)
// {
// return UInt16.Equals(x.Value, y.Value);
// }
// return false;
// }
// if (y.HasValue)
// {
// return false;
// }
// return true;
// }
// public override int GetHashCode(UInt16? val)
// {
// return val.HasValue ? val.Value.GetHashCode() : 0;
// }
//}
public class Int32EqualityComparer : EqualityComparer<int>
{
public override bool Equals(int x, int y)
{
return Int32.Equals(x, y);
}
public override int GetHashCode(int val)
{
return val.GetHashCode();
}
}
//public class NullableInt32EqualityComparer : EqualityComparer<Int32?>
//{
// public override bool Equals(Int32? x, Int32? y)
// {
// if (x.HasValue)
// {
// if (y.HasValue)
// {
// return Int32.Equals(x.Value, y.Value);
// }
// return false;
// }
// if (y.HasValue)
// {
// return false;
// }
// return true;
// }
// public override int GetHashCode(Int32? val)
// {
// return val.HasValue ? val.Value.GetHashCode() : 0;
// }
//}
public class UInt32EqualityComparer : EqualityComparer<uint>
{
public override bool Equals(uint x, uint y)
{
return UInt32.Equals(x, y);
}
public override int GetHashCode(uint val)
{
return val.GetHashCode();
}
}
//public class NullableUInt32EqualityComparer : EqualityComparer<UInt32?>
//{
// public override bool Equals(UInt32? x, UInt32? y)
// {
// if (x.HasValue)
// {
// if (y.HasValue)
// {
// return UInt32.Equals(x.Value, y.Value);
// }
// return false;
// }
// if (y.HasValue)
// {
// return false;
// }
// return true;
// }
// public override int GetHashCode(UInt32? val)
// {
// return val.HasValue ? val.Value.GetHashCode() : 0;
// }
//}
public class Int64EqualityComparer : EqualityComparer<long>
{
public override bool Equals(long x, long y)
{
return Int64.Equals(x, y);
}
public override int GetHashCode(long val)
{
return val.GetHashCode();
}
}
//public class NullableInt64EqualityComparer : EqualityComparer<Int64?>
//{
// public override bool Equals(Int64? x, Int64? y)
// {
// if (x.HasValue)
// {
// if (y.HasValue)
// {
// return Int64.Equals(x.Value, y.Value);
// }
// return false;
// }
// if (y.HasValue)
// {
// return false;
// }
// return true;
// }
// public override int GetHashCode(Int64? val)
// {
// return val.HasValue ? val.Value.GetHashCode() : 0;
// }
//}
public class UInt64EqualityComparer : EqualityComparer<ulong>
{
public override bool Equals(ulong x, ulong y)
{
return UInt64.Equals(x, y);
}
public override int GetHashCode(ulong val)
{
return val.GetHashCode();
}
}
//public class NullableUInt64EqualityComparer : EqualityComparer<UInt64?>
//{
// public override bool Equals(UInt64? x, UInt64? y)
// {
// if (x.HasValue)
// {
// if (y.HasValue)
// {
// return UInt64.Equals(x.Value, y.Value);
// }
// return false;
// }
// if (y.HasValue)
// {
// return false;
// }
// return true;
// }
// public override int GetHashCode(UInt64? val)
// {
// return val.HasValue ? val.Value.GetHashCode() : 0;
// }
//}
public class GuidEqualityComparer : EqualityComparer<Guid>
{
public override bool Equals(Guid x, Guid y)
{
return Guid.Equals(x, y);
}
public override int GetHashCode(Guid val)
{
return val.GetHashCode();
}
}
//public class NullableGuidEqualityComparer : EqualityComparer<Guid?>
//{
// public override bool Equals(Guid? x, Guid? y)
// {
// if (x.HasValue)
// {
// if (y.HasValue)
// {
// return Guid.Equals(x.Value, y.Value);
// }
// return false;
// }
// if (y.HasValue)
// {
// return false;
// }
// return true;
// }
// public override int GetHashCode(Guid? val)
// {
// return val.HasValue ? val.Value.GetHashCode() : 0;
// }
//}
public class ObjectEqualityComparer : EqualityComparer<object>
{
public override bool Equals(object x, object y)
{
if (x != null)
{
if (y != null)
{
return x.Equals(y);
}
return false;
}
if (y != null)
{
return false;
}
return true;
}
public override int GetHashCode(object val)
{
return val?.GetHashCode() ?? 0;
}
}
#endregion
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using System.ComponentModel;
using System.Globalization;
using System.IO;
using System.Management.Automation.Remoting;
using System.Text;
using System.Diagnostics;
namespace System.Management.Automation.Runspaces
{
/// <summary>
/// </summary>
public sealed class PowerShellProcessInstance : IDisposable
{
#region Private Members
private readonly ProcessStartInfo _startInfo;
private static readonly string s_PSExePath;
private RunspacePool _runspacePool;
private readonly object _syncObject = new object();
private bool _started;
private bool _isDisposed;
private bool _processExited;
#endregion Private Members
#region Constructors
/// <summary>
/// </summary>
static PowerShellProcessInstance()
{
#if UNIX
s_PSExePath = Path.Combine(Utils.DefaultPowerShellAppBase,
"pwsh");
#else
s_PSExePath = Path.Combine(Utils.DefaultPowerShellAppBase,
"pwsh.exe");
#endif
}
/// <summary>
/// </summary>
/// <param name="powerShellVersion"></param>
/// <param name="credential"></param>
/// <param name="initializationScript"></param>
/// <param name="useWow64"></param>
public PowerShellProcessInstance(Version powerShellVersion, PSCredential credential, ScriptBlock initializationScript, bool useWow64)
{
string psWow64Path = s_PSExePath;
if (useWow64)
{
string procArch = Environment.GetEnvironmentVariable("PROCESSOR_ARCHITECTURE");
if ((!string.IsNullOrEmpty(procArch)) && (procArch.Equals("amd64", StringComparison.OrdinalIgnoreCase) ||
procArch.Equals("ia64", StringComparison.OrdinalIgnoreCase)))
{
psWow64Path = s_PSExePath.ToLowerInvariant().Replace("\\system32\\", "\\syswow64\\");
if (!File.Exists(psWow64Path))
{
string message =
PSRemotingErrorInvariants.FormatResourceString(
RemotingErrorIdStrings.IPCWowComponentNotPresent,
psWow64Path);
throw new PSInvalidOperationException(message);
}
}
}
#if CORECLR
string processArguments = " -s -NoLogo -NoProfile";
#else
// Adding Version parameter to powershell
// Version parameter needs to go before all other parameters because the native layer looks for Version or
// PSConsoleFile parameters before parsing other parameters.
// The other parameters get parsed in the managed layer.
Version tempVersion = powerShellVersion ?? PSVersionInfo.PSVersion;
string processArguments = string.Format(CultureInfo.InvariantCulture,
"-Version {0}", new Version(tempVersion.Major, tempVersion.Minor));
processArguments = string.Format(CultureInfo.InvariantCulture,
"{0} -s -NoLogo -NoProfile", processArguments);
#endif
if (initializationScript != null)
{
string scripBlockAsString = initializationScript.ToString();
if (!string.IsNullOrEmpty(scripBlockAsString))
{
string encodedCommand =
Convert.ToBase64String(Encoding.Unicode.GetBytes(scripBlockAsString));
processArguments = string.Format(CultureInfo.InvariantCulture,
"{0} -EncodedCommand {1}", processArguments, encodedCommand);
}
}
// 'WindowStyle' is used only if 'UseShellExecute' is 'true'. Since 'UseShellExecute' is set
// to 'false' in our use, we can ignore the 'WindowStyle' setting in the initialization below.
_startInfo = new ProcessStartInfo
{
FileName = useWow64 ? psWow64Path : s_PSExePath,
Arguments = processArguments,
UseShellExecute = false,
RedirectStandardInput = true,
RedirectStandardOutput = true,
RedirectStandardError = true,
CreateNoWindow = true,
#if !UNIX
LoadUserProfile = true,
#endif
};
if (credential != null)
{
Net.NetworkCredential netCredential = credential.GetNetworkCredential();
_startInfo.UserName = netCredential.UserName;
_startInfo.Domain = string.IsNullOrEmpty(netCredential.Domain) ? "." : netCredential.Domain;
_startInfo.Password = credential.Password;
}
Process = new Process { StartInfo = _startInfo, EnableRaisingEvents = true };
}
/// <summary>
/// </summary>
public PowerShellProcessInstance() : this(null, null, null, false)
{
}
/// <summary>
/// Gets a value indicating whether the associated process has been terminated.
/// true if the operating system process referenced by the Process component has terminated; otherwise, false.
/// </summary>
public bool HasExited
{
get
{
// When process is exited, there is some delay in receiving ProcessExited event and HasExited property on process object.
// Using HasExited property on started process object to determine if powershell process has exited.
//
return _processExited || (_started && Process != null && Process.HasExited);
}
}
#endregion Constructors
#region Dispose
/// <summary>
/// </summary>
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
/// <summary>
/// </summary>
/// <param name="disposing"></param>
private void Dispose(bool disposing)
{
if (_isDisposed) return;
lock (_syncObject)
{
if (_isDisposed) return;
_isDisposed = true;
}
if (disposing)
{
try
{
if (Process != null && !Process.HasExited)
Process.Kill();
}
catch (InvalidOperationException)
{
}
catch (Win32Exception)
{
}
catch (NotSupportedException)
{
}
}
}
#endregion Dispose
#region Public Properties
/// <summary>
/// </summary>
public Process Process { get; }
#endregion Public Properties
#region Internal Members
internal RunspacePool RunspacePool
{
get
{
lock (_syncObject)
{
return _runspacePool;
}
}
set
{
lock (_syncObject)
{
_runspacePool = value;
}
}
}
internal OutOfProcessTextWriter StdInWriter { get; set; }
internal void Start()
{
// To fix the deadlock, we should not call Process.HasExited by holding the sync lock as Process.HasExited can raise ProcessExited event
//
if (HasExited)
{
throw new InvalidOperationException();
}
lock (_syncObject)
{
if (_started)
{
return;
}
_started = true;
Process.Exited += ProcessExited;
}
Process.Start();
}
private void ProcessExited(object sender, EventArgs e)
{
lock (_syncObject)
{
_processExited = true;
}
}
#endregion Internal Members
}
}
| |
//! \file Image.cs
//! \date Tue Jul 01 11:29:52 2014
//! \brief image class.
//
// Copyright (C) 2014 by morkt
//
// 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.IO;
using System.Linq;
using System.Windows.Media;
using System.Windows.Media.Imaging;
namespace GameRes
{
public class ImageMetaData
{
/// <summary>Image width in pixels.</summary>
public uint Width { get; set; }
/// <summary>Image height in pixels.</summary>
public uint Height { get; set; }
/// <summary>Horizontal coordinate of the image top left corner.</summary>
public int OffsetX { get; set; }
/// <summary>Vertical coordinate of the image top left corner.</summary>
public int OffsetY { get; set; }
/// <summary>Image bitdepth.</summary>
public int BPP { get; set; }
/// <summary>Image source file name, if any.</summary>
public string FileName { get; set; }
public int iWidth { get { return (int)Width; } }
public int iHeight { get { return (int)Height; } }
}
public class ImageEntry : Entry
{
public override string Type { get { return "image"; } }
}
/// <summary>
/// Enumeration representing possible palette serialization formats.
/// </summary>
public enum PaletteFormat
{
Rgb = 1,
Bgr = 2,
RgbX = 5,
BgrX = 6,
RgbA = 9,
BgrA = 10,
}
public class ImageData
{
private BitmapSource m_bitmap;
public BitmapSource Bitmap { get { return m_bitmap; } }
public uint Width { get { return (uint)m_bitmap.PixelWidth; } }
public uint Height { get { return (uint)m_bitmap.PixelHeight; } }
public int OffsetX { get; set; }
public int OffsetY { get; set; }
public int BPP { get { return m_bitmap.Format.BitsPerPixel; } }
public static double DefaultDpiX { get; set; }
public static double DefaultDpiY { get; set; }
static ImageData ()
{
SetDefaultDpi (96, 96);
}
public static void SetDefaultDpi (double x, double y)
{
DefaultDpiX = x;
DefaultDpiY = y;
}
public ImageData (BitmapSource data, ImageMetaData meta)
{
m_bitmap = data;
OffsetX = meta.OffsetX;
OffsetY = meta.OffsetY;
}
public ImageData (BitmapSource data, int x = 0, int y = 0)
{
m_bitmap = data;
OffsetX = x;
OffsetY = y;
}
public static ImageData Create (ImageMetaData info, PixelFormat format, BitmapPalette palette,
Array pixel_data, int stride)
{
var bitmap = BitmapSource.Create ((int)info.Width, (int)info.Height, DefaultDpiX, DefaultDpiY,
format, palette, pixel_data, stride);
bitmap.Freeze();
return new ImageData (bitmap, info);
}
public static ImageData Create (ImageMetaData info, PixelFormat format, BitmapPalette palette,
Array pixel_data)
{
return Create (info, format, palette, pixel_data, (int)info.Width*((format.BitsPerPixel+7)/8));
}
public static ImageData CreateFlipped (ImageMetaData info, PixelFormat format, BitmapPalette palette,
Array pixel_data, int stride)
{
var bitmap = BitmapSource.Create ((int)info.Width, (int)info.Height, DefaultDpiX, DefaultDpiY,
format, palette, pixel_data, stride);
var flipped = new TransformedBitmap (bitmap, new ScaleTransform { ScaleY = -1 });
flipped.Freeze();
return new ImageData (flipped, info);
}
}
public abstract class ImageFormat : IResource
{
public override string Type { get { return "image"; } }
public abstract ImageMetaData ReadMetaData (IBinaryStream file);
public abstract ImageData Read (IBinaryStream file, ImageMetaData info);
public abstract void Write (Stream file, ImageData bitmap);
public static ImageData Read (IBinaryStream file)
{
var format = FindFormat (file);
if (null == format)
return null;
file.Position = 0;
return format.Item1.Read (file, format.Item2);
}
public static System.Tuple<ImageFormat, ImageMetaData> FindFormat (IBinaryStream file)
{
foreach (var impl in FormatCatalog.Instance.FindFormats<ImageFormat> (file.Name, file.Signature))
{
try
{
file.Position = 0;
ImageMetaData metadata = impl.ReadMetaData (file);
if (null != metadata)
{
metadata.FileName = file.Name;
return Tuple.Create (impl, metadata);
}
}
catch (OperationCanceledException)
{
throw;
}
catch { }
}
return null;
}
public bool IsBuiltin
{
get { return this.GetType().Assembly == typeof(ImageFormat).Assembly; }
}
public static ImageFormat FindByTag (string tag)
{
return FormatCatalog.Instance.ImageFormats.FirstOrDefault (x => x.Tag == tag);
}
static readonly Lazy<ImageFormat> s_JpegFormat = new Lazy<ImageFormat> (() => FindByTag ("JPEG"));
static readonly Lazy<ImageFormat> s_PngFormat = new Lazy<ImageFormat> (() => FindByTag ("PNG"));
static readonly Lazy<ImageFormat> s_BmpFormat = new Lazy<ImageFormat> (() => FindByTag ("BMP"));
static readonly Lazy<ImageFormat> s_TgaFormat = new Lazy<ImageFormat> (() => FindByTag ("TGA"));
public static ImageFormat Jpeg { get { return s_JpegFormat.Value; } }
public static ImageFormat Png { get { return s_PngFormat.Value; } }
public static ImageFormat Bmp { get { return s_BmpFormat.Value; } }
public static ImageFormat Tga { get { return s_TgaFormat.Value; } }
/// <summary>
/// Desereialize color map from <paramref name="input"/> stream, consisting of specified number of
/// <paramref name="colors"/> stored in specified <paramref name="format"/>.
/// Default number of colors is 256 and format is 4-byte BGRX (where X is an unsignificant byte).
/// </summary>
public static Color[] ReadColorMap (Stream input, int colors = 0x100, PaletteFormat format = PaletteFormat.BgrX)
{
int bpp = PaletteFormat.Rgb == format || PaletteFormat.Bgr == format ? 3 : 4;
var palette_data = new byte[bpp * colors];
if (palette_data.Length != input.Read (palette_data, 0, palette_data.Length))
throw new EndOfStreamException();
int src = 0;
var color_map = new Color[colors];
Func<int, Color> get_color;
if (PaletteFormat.Bgr == format || PaletteFormat.BgrX == format)
get_color = x => Color.FromRgb (palette_data[x+2], palette_data[x+1], palette_data[x]);
else if (PaletteFormat.BgrA == format)
get_color = x => Color.FromArgb (palette_data[x+3], palette_data[x+2], palette_data[x+1], palette_data[x]);
else if (PaletteFormat.RgbA == format)
get_color = x => Color.FromArgb (palette_data[x+3], palette_data[x], palette_data[x+1], palette_data[x+2]);
else
get_color = x => Color.FromRgb (palette_data[x], palette_data[x+1], palette_data[x+2]);
for (int i = 0; i < colors; ++i)
{
color_map[i] = get_color (src);
src += bpp;
}
return color_map;
}
public static BitmapPalette ReadPalette (Stream input, int colors = 0x100, PaletteFormat format = PaletteFormat.BgrX)
{
return new BitmapPalette (ReadColorMap (input, colors, format));
}
public static BitmapPalette ReadPalette (ArcView file, long offset, int colors = 0x100, PaletteFormat format = PaletteFormat.BgrX)
{
using (var input = file.CreateStream (offset, (uint)(4 * colors))) // largest possible size for palette
return ReadPalette (input, colors, format);
}
}
}
| |
using System;
using System.Data;
using System.Data.Common;
using System.Data.SqlClient;
using System.Collections.Generic;
using DDTek.Oracle;
using DbParallel.DataAccess;
using DbParallel.DataAccess.Booster.Oracle;
using DbParallel.DataAccess.Booster.SqlServer;
namespace DataBooster.DbWebApi.DataAccess
{
public static partial class DbPackage
{
#region Initialization
static DbPackage()
{
// DbAccess.DefaultCommandType = CommandType.StoredProcedure;
}
public static DbAccess CreateConnection()
{
return new DbAccess(ConfigHelper.DbProviderFactory, ConfigHelper.ConnectionString);
}
private static string GetProcedure(string sp)
{
return ConfigHelper.DatabasePackage + sp;
}
#endregion
#region Usage Examples
// To turn off following sample code in DEBUG mode, just add NO_SAMPLE into the project properties ...
// Project Properties Dialog -> Build -> General -> Conditional Compilation Symbols.
#if (DEBUG && !NO_SAMPLE)
#region Some samples of using DbAccess class
#region A sample of reader action
public class SampleClassA
{
public string PropertyA { get; set; }
public int PropertyB { get; set; }
public decimal? PropertyC { get; set; }
public SampleClassA() // => ... <T> ... where T : class, new()
{
PropertyA = string.Empty;
PropertyB = 0;
PropertyC = 0m;
}
public SampleClassA(string a, int b, decimal? c)
{
PropertyA = a;
PropertyB = b;
PropertyC = c;
}
}
internal static List<SampleClassA> LoadSampleObjByAction(this DbAccess dbAccess, string area, int grpId)
{
const string sp = "GET_SAMPLE_OBJ";
List<SampleClassA> sampleClsList = new List<SampleClassA>();
dbAccess.ExecuteReader(GetProcedure(sp), parameters =>
{
parameters.Add("inArea", area);
parameters.Add("inGrp_Id", grpId);
},
row =>
{
sampleClsList.Add(new SampleClassA(row.Field<string>("COL_A"), row.Field<int>("COL_B"), row.Field<decimal?>("COL_C")));
});
return sampleClsList;
}
#endregion
#region A sample of specified fields mapping
public class SampleClassB
{
public string PropertyA { get; set; }
public int PropertyB { get; set; }
public decimal? PropertyC { get; set; }
// public SampleClassB() { } // Implicitly or Explicitly
}
internal static IEnumerable<SampleClassB> LoadSampleObjByMap(this DbAccess dbAccess, string area, int grpId)
{
const string sp = "GET_SAMPLE_OBJ";
return dbAccess.ExecuteReader<SampleClassB>(GetProcedure(sp), parameters =>
{
parameters.Add("inArea", area);
parameters.Add("inGrp_Id", grpId);
},
map =>
{
// In order to allow Visual Studio Intellisense to be able to infer the type of map and t correctly
// Please make sure that SampleClassB class has a parameterless constructor or default constructor implicitly
map.Add("COL_A", t => t.PropertyA);
map.Add("COL_B", t => t.PropertyB);
map.Add("COL_C", t => t.PropertyC);
});
}
#endregion
#region A sample of auto fields mapping
public class SampleClassC
{
public string Column_Name1 { get; set; }
public int Column_Name2 { get; set; }
public decimal? Column_Name3 { get; set; }
public bool Column_Name4 { get; set; }
// public SampleClassC() { } // Implicitly or Explicitly
}
internal static IEnumerable<SampleClassC> LoadSampleObjAutoMap(this DbAccess dbAccess, string area, int grpId)
{
const string sp = "GET_SAMPLE_ITEM";
return dbAccess.ExecuteReader<SampleClassC>(GetProcedure(sp), parameters =>
{
parameters.Add("inArea", area);
parameters.Add("inGrp_Id", grpId);
});
}
#endregion
#region A sample of Multi-ResultSets with auto/specified fields mapping
internal static Tuple<List<SampleClassA>, List<SampleClassB>, List<SampleClassC>> ViewReport(this DbAccess dbAccess, DateTime date, int sessionId)
{
const string sp = "VIEW_REPORT";
var resultTuple = Tuple.Create(new List<SampleClassA>(), new List<SampleClassB>(), new List<SampleClassC>());
dbAccess.ExecuteMultiReader(GetProcedure(sp), parameters =>
{
parameters.Add("inDate", date);
parameters.Add("inSession", sessionId);
}, resultSets =>
{
// Specified fields mapping example
resultSets.Add(resultTuple.Item1, // Put 1st ResultSet into resultTuple.Item1
colMap =>
{
colMap.Add("COL_A", t => t.PropertyA);
colMap.Add("COL_B", t => t.PropertyB);
colMap.Add("COL_C", t => t.PropertyC);
});
// Full-automatic (case-insensitive) fields mapping examples
resultSets.Add(resultTuple.Item2); // Put 2nd ResultSet into resultTuple.Item2
resultSets.Add(resultTuple.Item3); // Put 3rd ResultSet into resultTuple.Item3
}
);
return resultTuple;
}
#endregion
#region A sample of output parameter
internal static Tuple<string, int, byte> GetSampleSetting(this DbAccess dbAccess, string sampleDomain)
{
const string sp = "GET_SAMPLE_SETTING";
DbParameter outStartupMode = null;
DbParameter outRefreshInterval = null;
DbParameter outDegreeOfTaskParallelism = null;
dbAccess.ExecuteNonQuery(GetProcedure(sp), parameters =>
{
parameters.Add("inSample_Domain", sampleDomain);
outStartupMode = parameters.AddOutput("outStartup_Mode", 32);
outRefreshInterval = parameters.AddOutput("outRefresh_Interval", DbType.Int32);
outDegreeOfTaskParallelism = parameters.AddOutput("outParallelism_Degree", DbType.Byte);
});
return Tuple.Create(outStartupMode.Parameter<string>(),
outRefreshInterval.Parameter<int>(),
outDegreeOfTaskParallelism.Parameter<byte>());
}
#endregion
#region A sample of non-return
public static void LogSampleError(this DbAccess dbAccess, string strReference, string strMessage)
{
const string sp = "LOG_SAMPLE_ERROR";
dbAccess.ExecuteNonQuery(GetProcedure(sp), parameters =>
{
parameters.Add("inReference", strReference);
parameters.Add("inMessage", strMessage);
});
}
#endregion
#endregion
#region A sample of using SqlLauncher class
public static SqlLauncher CreateSampleSqlLauncher()
{
return new SqlLauncher(ConfigHelper.AuxConnectionString, "schema.DestBigTable",
/* (Optional)
* If the data source and the destination table have the same number of columns,
* and the ordinal position of each source column within the data source matches the ordinal position
* of the corresponding destination column, the ColumnMappings collection is unnecessary.
* However, if the column counts differ, or the ordinal positions are not consistent,
* you must use ColumnMappings to make sure that data is copied into the correct columns.
* (this remark is excerpted from MSDN http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlbulkcopy.columnmappings.aspx,
* please see also http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlbulkcopycolumnmappingcollection.aspx)
*/ columnMappings =>
{
columnMappings.Add(/* 0, */"ProdID");
columnMappings.Add(/* 1, */"ProdName");
columnMappings.Add(/* 2, */"ProdPrice");
}
);
}
public static void AddSampleSqlRow(this SqlLauncher launcher, int col0, string col1, decimal col2)
{
launcher.Post(col0, col1, col2);
}
#endregion
#region A sample of using OracleLauncher class
public static OracleLauncher CreateSampleOraLauncher(int grpId)
{
return new OracleLauncher(ConfigHelper.ConnectionString, GetProcedure("WRITE_BULK_DATA"),
parameters =>
{
parameters.Add("inGroup_ID", grpId); // Ordinary parameter
// All Array Bind Types must be explicitly specified and must match PL/SQL table row types defined in database side
parameters.AddAssociativeArray("inItem_IDs", OracleDbType.Int32);
parameters.AddAssociativeArray("inItem_Values", OracleDbType.Double);
});
}
public static void AddSampleOraRow(this OracleLauncher launcher, int itemId, double itemValue)
{
launcher.Post(itemId, itemValue);
}
// The database side package:
// CREATE OR REPLACE PACKAGE SCHEMA.PACKAGE IS
// TYPE NUMBER_ARRAY IS TABLE OF NUMBER INDEX BY PLS_INTEGER;
// TYPE DOUBLE_ARRAY IS TABLE OF BINARY_DOUBLE INDEX BY PLS_INTEGER;
// -- ...
// PROCEDURE WRITE_BULK_DATA
// (
// inGroup_ID NUMBER,
// inItem_IDs NUMBER_ARRAY,
// inItem_Values DOUBLE_ARRAY
// );
// -- ...
// END PACKAGE;
// /
// CREATE OR REPLACE PACKAGE BODY SCHEMA.PACKAGE IS
// -- ...
// PROCEDURE WRITE_BULK_DATA
// (
// inGroup_ID NUMBER,
// inItem_IDs NUMBER_ARRAY,
// inItem_Values DOUBLE_ARRAY
// ) AS
// BEGIN
// FORALL i IN inItem_IDs.FIRST .. inItem_IDs.LAST
// INSERT /*+ APPEND_VALUES */ INTO SCHEMA.TEST_WRITE_DATA
// (
// GROUP_ID,
// ITEM_ID,
// ITEM_VALUE
// )
// VALUES
// (
// inGroup_ID,
// inItem_IDs(i),
// inItem_Values(i)
// );
// COMMIT;
// END WRITE_BULK_DATA;
// -- ...
// END PACKAGE;
#endregion
#endif
#endregion
}
}
| |
using System;
using System.Globalization;
using System.Collections.Generic;
using Sasoma.Utils;
using Sasoma.Microdata.Interfaces;
using Sasoma.Languages.Core;
using Sasoma.Microdata.Properties;
namespace Sasoma.Microdata.Types
{
/// <summary>
/// Event type: Social event.
/// </summary>
public class SocialEvent_Core : TypeCore, IEvent
{
public SocialEvent_Core()
{
this._TypeId = 244;
this._Id = "SocialEvent";
this._Schema_Org_Url = "http://schema.org/SocialEvent";
string label = "";
GetLabel(out label, "SocialEvent", typeof(SocialEvent_Core));
this._Label = label;
this._Ancestors = new int[]{266,98};
this._SubTypes = new int[0];
this._SuperTypes = new int[]{98};
this._Properties = new int[]{67,108,143,229,19,71,82,130,151,158,214,216,218};
}
/// <summary>
/// A person attending the event.
/// </summary>
private Attendees_Core attendees;
public Attendees_Core Attendees
{
get
{
return attendees;
}
set
{
attendees = value;
SetPropertyInstance(attendees);
}
}
/// <summary>
/// A short description of the item.
/// </summary>
private Description_Core description;
public Description_Core Description
{
get
{
return description;
}
set
{
description = value;
SetPropertyInstance(description);
}
}
/// <summary>
/// The duration of the item (movie, audio recording, event, etc.) in <a href=\http://en.wikipedia.org/wiki/ISO_8601\ target=\new\>ISO 8601 date format</a>.
/// </summary>
private Properties.Duration_Core duration;
public Properties.Duration_Core Duration
{
get
{
return duration;
}
set
{
duration = value;
SetPropertyInstance(duration);
}
}
/// <summary>
/// The end date and time of the event (in <a href=\http://en.wikipedia.org/wiki/ISO_8601\ target=\new\>ISO 8601 date format</a>).
/// </summary>
private EndDate_Core endDate;
public EndDate_Core EndDate
{
get
{
return endDate;
}
set
{
endDate = value;
SetPropertyInstance(endDate);
}
}
/// <summary>
/// URL of an image of the item.
/// </summary>
private Image_Core image;
public Image_Core Image
{
get
{
return image;
}
set
{
image = value;
SetPropertyInstance(image);
}
}
/// <summary>
/// The location of the event or organization.
/// </summary>
private Location_Core location;
public Location_Core Location
{
get
{
return location;
}
set
{
location = value;
SetPropertyInstance(location);
}
}
/// <summary>
/// The name of the item.
/// </summary>
private Name_Core name;
public Name_Core Name
{
get
{
return name;
}
set
{
name = value;
SetPropertyInstance(name);
}
}
/// <summary>
/// An offer to sell this item\u2014for example, an offer to sell a product, the DVD of a movie, or tickets to an event.
/// </summary>
private Offers_Core offers;
public Offers_Core Offers
{
get
{
return offers;
}
set
{
offers = value;
SetPropertyInstance(offers);
}
}
/// <summary>
/// The main performer or performers of the event\u2014for example, a presenter, musician, or actor.
/// </summary>
private Performers_Core performers;
public Performers_Core Performers
{
get
{
return performers;
}
set
{
performers = value;
SetPropertyInstance(performers);
}
}
/// <summary>
/// The start date and time of the event (in <a href=\http://en.wikipedia.org/wiki/ISO_8601\ target=\new\>ISO 8601 date format</a>).
/// </summary>
private StartDate_Core startDate;
public StartDate_Core StartDate
{
get
{
return startDate;
}
set
{
startDate = value;
SetPropertyInstance(startDate);
}
}
/// <summary>
/// Events that are a part of this event. For example, a conference event includes many presentations, each are subEvents of the conference.
/// </summary>
private SubEvents_Core subEvents;
public SubEvents_Core SubEvents
{
get
{
return subEvents;
}
set
{
subEvents = value;
SetPropertyInstance(subEvents);
}
}
/// <summary>
/// An event that this event is a part of. For example, a collection of individual music performances might each have a music festival as their superEvent.
/// </summary>
private SuperEvent_Core superEvent;
public SuperEvent_Core SuperEvent
{
get
{
return superEvent;
}
set
{
superEvent = value;
SetPropertyInstance(superEvent);
}
}
/// <summary>
/// URL of the item.
/// </summary>
private Properties.URL_Core uRL;
public Properties.URL_Core URL
{
get
{
return uRL;
}
set
{
uRL = value;
SetPropertyInstance(uRL);
}
}
}
}
| |
/* ****************************************************************************
*
* 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
* dlr@microsoft.com. 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.Reflection;
using Microsoft.Scripting;
using IronPython.Runtime;
#if FEATURE_CORE_DLR
using MSAst = System.Linq.Expressions;
#else
using MSAst = Microsoft.Scripting.Ast;
#endif
using AstUtils = Microsoft.Scripting.Ast.Utils;
namespace IronPython.Compiler.Ast {
using Ast = MSAst.Expression;
using System.Runtime.CompilerServices;
public abstract class ComprehensionIterator : Node {
internal abstract MSAst.Expression Transform(MSAst.Expression body);
}
public abstract class Comprehension : Expression {
public abstract IList<ComprehensionIterator> Iterators { get; }
public abstract override string NodeName { get; }
protected abstract MSAst.ParameterExpression MakeParameter();
protected abstract MethodInfo Factory();
protected abstract MSAst.Expression Body(MSAst.ParameterExpression res);
public abstract override void Walk(PythonWalker walker);
public override Ast Reduce() {
MSAst.ParameterExpression res = MakeParameter();
// 1. Initialization code - create list and store it in the temp variable
MSAst.Expression initialize =
Ast.Assign(
res,
Ast.Call(Factory())
);
// 2. Create body from LHS: res.Append(item), res.Add(key, value), etc.
MSAst.Expression body = Body(res);
// 3. Transform all iterators in reverse order, building the true bodies
for (int current = Iterators.Count - 1; current >= 0; current--) {
ComprehensionIterator iterator = Iterators[current];
body = iterator.Transform(body);
}
return Ast.Block(
new[] { res },
initialize,
body,
res
);
}
}
public sealed class ListComprehension : Comprehension {
private readonly ComprehensionIterator[] _iterators;
private readonly Expression _item;
public ListComprehension(Expression item, ComprehensionIterator[] iterators) {
_item = item;
_iterators = iterators;
}
public Expression Item {
get { return _item; }
}
public override IList<ComprehensionIterator> Iterators {
get { return _iterators; }
}
protected override MSAst.ParameterExpression MakeParameter() {
return Ast.Parameter(typeof(List), "list_comprehension_list");
}
protected override MethodInfo Factory() {
return AstMethods.MakeList;
}
protected override Ast Body(MSAst.ParameterExpression res) {
return GlobalParent.AddDebugInfo(
Ast.Call(
AstMethods.ListAddForComprehension,
res,
AstUtils.Convert(_item, typeof(object))
),
_item.Span
);
}
public override string NodeName {
get {
return "list comprehension";
}
}
public override void Walk(PythonWalker walker) {
if (walker.Walk(this)) {
if (_item != null) {
_item.Walk(walker);
}
if (_iterators != null) {
foreach (ComprehensionIterator ci in _iterators) {
ci.Walk(walker);
}
}
}
walker.PostWalk(this);
}
}
public sealed class SetComprehension : Comprehension {
private readonly ComprehensionIterator[] _iterators;
private readonly Expression _item;
private readonly ComprehensionScope _scope;
public SetComprehension(Expression item, ComprehensionIterator[] iterators) {
_item = item;
_iterators = iterators;
_scope = new ComprehensionScope(this);
}
public Expression Item {
get { return _item; }
}
public override IList<ComprehensionIterator> Iterators {
get { return _iterators; }
}
protected override MSAst.ParameterExpression MakeParameter() {
return Ast.Parameter(typeof(SetCollection), "set_comprehension_set");
}
protected override MethodInfo Factory() {
return AstMethods.MakeEmptySet;
}
public override Ast Reduce() {
return _scope.AddVariables(base.Reduce());
}
protected override Ast Body(MSAst.ParameterExpression res) {
return GlobalParent.AddDebugInfo(
Ast.Call(
AstMethods.SetAddForComprehension,
res,
AstUtils.Convert(_item, typeof(object))
),
_item.Span
);
}
public override string NodeName {
get {
return "set comprehension";
}
}
public override void Walk(PythonWalker walker) {
if (walker.Walk(this)) {
if (_item != null) {
_item.Walk(walker);
}
if (_iterators != null) {
foreach (ComprehensionIterator ci in _iterators) {
ci.Walk(walker);
}
}
}
walker.PostWalk(this);
}
internal ComprehensionScope Scope {
get {
return _scope;
}
}
}
public sealed class DictionaryComprehension : Comprehension {
private readonly ComprehensionIterator[] _iterators;
private readonly Expression _key, _value;
private readonly ComprehensionScope _scope;
public DictionaryComprehension(Expression key, Expression value, ComprehensionIterator[] iterators) {
_key = key;
_value = value;
_iterators = iterators;
_scope = new ComprehensionScope(this);
}
public Expression Key {
get { return _key; }
}
public Expression Value {
get { return _value; }
}
public override IList<ComprehensionIterator> Iterators {
get { return _iterators; }
}
protected override MSAst.ParameterExpression MakeParameter() {
return Ast.Parameter(typeof(PythonDictionary), "dict_comprehension_dict");
}
protected override MethodInfo Factory() {
return AstMethods.MakeEmptyDict;
}
public override Ast Reduce() {
return _scope.AddVariables(base.Reduce());
}
protected override Ast Body(MSAst.ParameterExpression res) {
return GlobalParent.AddDebugInfo(
Ast.Call(
AstMethods.DictAddForComprehension,
res,
AstUtils.Convert(_key, typeof(object)),
AstUtils.Convert(_value, typeof(object))
),
new SourceSpan(_key.Span.Start, _value.Span.End)
);
}
public override string NodeName {
get {
return "dict comprehension";
}
}
public override void Walk(PythonWalker walker) {
if (walker.Walk(this)) {
if (_key != null) {
_key.Walk(walker);
}
if (_value != null) {
_value.Walk(walker);
}
if (_iterators != null) {
foreach (ComprehensionIterator ci in _iterators) {
ci.Walk(walker);
}
}
}
walker.PostWalk(this);
}
internal ComprehensionScope Scope {
get {
return _scope;
}
}
}
/// <summary>
/// Scope for the comprehension. Because scopes are usually statements and comprehensions are expressions
/// this doesn't actually show up in the AST hierarchy and instead hangs off the comprehension expression.
/// </summary>
class ComprehensionScope : ScopeStatement {
private readonly Expression _comprehension;
internal static readonly MSAst.ParameterExpression _compContext = Ast.Parameter(typeof(CodeContext), "$compContext");
public ComprehensionScope(Expression comprehension) {
_comprehension = comprehension;
}
internal override bool ExposesLocalVariable(PythonVariable variable) {
if (NeedsLocalsDictionary) {
return true;
} else if (variable.Scope == this) {
return false;
}
return _comprehension.Parent.ExposesLocalVariable(variable);
}
internal override PythonVariable BindReference(PythonNameBinder binder, PythonReference reference) {
PythonVariable variable;
if (TryGetVariable(reference.Name, out variable)) {
if (variable.Kind == VariableKind.Global) {
AddReferencedGlobal(reference.Name);
}
return variable;
}
// then bind in our parent scope
return _comprehension.Parent.BindReference(binder, reference);
}
internal override Ast GetVariableExpression(PythonVariable variable) {
if (variable.IsGlobal) {
return GlobalParent.ModuleVariables[variable];
}
Ast expr;
if (_variableMapping.TryGetValue(variable, out expr)) {
return expr;
}
return _comprehension.Parent.GetVariableExpression(variable);
}
internal override Microsoft.Scripting.Ast.LightLambdaExpression GetLambda() {
throw new NotImplementedException();
}
public override void Walk(PythonWalker walker) {
_comprehension.Walk(walker);
}
internal override Ast LocalContext {
get {
if (NeedsLocalContext) {
return _compContext;
}
return _comprehension.Parent.LocalContext;
}
}
internal Ast AddVariables(Ast expression) {
ReadOnlyCollectionBuilder<MSAst.ParameterExpression> locals = new ReadOnlyCollectionBuilder<MSAst.ParameterExpression>();
MSAst.ParameterExpression localContext = null;
if (NeedsLocalContext) {
localContext = _compContext;
locals.Add(_compContext);
}
List<MSAst.Expression> body = new List<MSAst.Expression>();
CreateVariables(locals, body);
if (localContext != null) {
var createLocal = CreateLocalContext(_comprehension.Parent.LocalContext);
body.Add(Ast.Assign(_compContext, createLocal));
body.Add(expression);
} else {
body.Add(expression);
}
return Expression.Block(
locals,
body
);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using Chutzpah.Exceptions;
using Chutzpah.Models;
using Chutzpah.Wrappers;
using Chutzpah.FileProcessors;
namespace Chutzpah.BatchProcessor
{
public class BatchCompilerService : IBatchCompilerService
{
private readonly IProcessHelper processHelper;
private readonly IFileSystemWrapper fileSystem;
private readonly ISourceMapDiscoverer sourceMapDiscoverer;
public BatchCompilerService(IProcessHelper processHelper, IFileSystemWrapper fileSystem, ISourceMapDiscoverer sourceMapDiscoverer)
{
this.processHelper = processHelper;
this.fileSystem = fileSystem;
this.sourceMapDiscoverer = sourceMapDiscoverer;
}
public void Compile(IEnumerable<TestContext> testContexts)
{
// Group the test contexts by test settings to run batch aware settings like compile
// For each test settings file that defines a compile step we will run it and update
// testContexts reference files accordingly.
var groupedTestContexts = testContexts.GroupBy(x => x.TestFileSettings);
foreach (var contextGroup in groupedTestContexts)
{
var testSettings = contextGroup.Key;
// If there is no compile setting then nothing to do here
if (testSettings.Compile == null) continue;
// Build the mapping from source to output files and gather properties about them
var filePropeties = (
from file in contextGroup.SelectMany(x => x.ReferencedFiles).Distinct()
where testSettings.Compile.Extensions.Any(x => file.Path.EndsWith(x, StringComparison.OrdinalIgnoreCase))
let sourceProperties = GetFileProperties(file.Path)
let sourceHasOutput = !testSettings.Compile.ExtensionsWithNoOutput.Any(x => file.Path.EndsWith(x, StringComparison.OrdinalIgnoreCase))
let outputPath = GetOutputPath(file.Path, testSettings.Compile)
let outputProperties = sourceHasOutput ? GetFileProperties(outputPath) : null
select new SourceCompileInfo { SourceProperties = sourceProperties, OutputProperties = outputProperties, SourceHasOutput = sourceHasOutput }).ToList();
var outputPathMap = filePropeties
.Where(x => x.SourceHasOutput)
.ToDictionary(x => x.SourceProperties.Path, x => x.OutputProperties.Path, StringComparer.OrdinalIgnoreCase);
// Check if the batch compile is needed
var shouldCompile = CheckIfCompileIsNeeded(testSettings, filePropeties);
// Run the batch compile if necessary
if (shouldCompile)
{
if (testSettings.Compile.Mode == BatchCompileMode.Executable)
{
RunBatchCompile(testSettings);
}
else if(testSettings.Compile.Mode == BatchCompileMode.External)
{
ChutzpahTracer.TraceError("Chutzpah determined generated .js files are missing but the compile mode is External so Chutzpah can't compile them. Test results may be wrong.");
}
}
else
{
ChutzpahTracer.TraceInformation("Skipping batch compile since all files are supdate to date for {0}", testSettings.SettingsFileName);
}
// Now that compile finished set generated path on all files who match the compiled extensions
var filesToUpdate = contextGroup.SelectMany(x => x.ReferencedFiles)
.Where(x => outputPathMap.ContainsKey(x.Path));
foreach (var file in filesToUpdate)
{
var outputPath = outputPathMap[file.Path];
if (outputPath != null && fileSystem.FileExists(outputPath))
{
file.GeneratedFilePath = outputPath;
ChutzpahTracer.TraceInformation("Found generated path for {0} at {1}", file.Path, outputPath);
}
else
{
ChutzpahTracer.TraceWarning("Couldn't find generated path for {0} at {1}", file.Path, outputPath);
}
if (!string.IsNullOrWhiteSpace(file.GeneratedFilePath))
{
file.SourceMapFilePath = testSettings.Compile.UseSourceMaps ? sourceMapDiscoverer.FindSourceMap(file.GeneratedFilePath) : null;
}
}
}
}
private void RunBatchCompile(ChutzpahTestSettingsFile testSettings)
{
try
{
var result = processHelper.RunBatchCompileProcess(testSettings.Compile);
if (result.ExitCode > 0)
{
throw new ChutzpahCompilationFailedException(result.StandardError, testSettings.SettingsFileName);
}
}
catch (Exception e)
{
ChutzpahTracer.TraceError(e, "Error during batch compile of {0}", testSettings.SettingsFileName);
throw new ChutzpahCompilationFailedException(e.Message, testSettings.SettingsFileName, e);
}
}
/// <summary>
/// Determines if a compile is needed. To figure this out we check the following things:
/// 1. Check if any source file which produces output is missing its output
/// 2. Check if any source file which produces output is newer than its output
/// 3. Check if any source file which does not produce output is newer than the oldest output file
/// </summary>
/// <param name="testSettings"></param>
/// <param name="filePropeties"></param>
/// <returns></returns>
private static bool CheckIfCompileIsNeeded(ChutzpahTestSettingsFile testSettings, List<SourceCompileInfo> filePropeties)
{
if (!filePropeties.Any(x => x.SourceHasOutput))
{
return false;
}
// If SkipIfUnchanged is true then we check if all the output files are newer than the input files
// we will only run the compile if this fails
if (testSettings.Compile.SkipIfUnchanged)
{
var hasMissingOutput = filePropeties
.Where(x => x.SourceHasOutput)
.Any(x => !x.OutputProperties.Exists);
if (!hasMissingOutput)
{
var pairFileHasChanged =
filePropeties.Any(x => x.SourceHasOutput
&& x.SourceProperties.Exists
&& x.OutputProperties.Exists
&& x.SourceProperties.LastModifiedDate > x.OutputProperties.LastModifiedDate);
var fileWithNoOutputHasChanged = false;
var sourcesWithNoOutput = filePropeties.Where(x => x.SourceProperties.Exists && !x.SourceHasOutput).ToList();
if (sourcesWithNoOutput.Any())
{
// Get the time of the newest file change of a file which has no output (like a .d.ts)
var newestSourceWithNoOutputFileTime = sourcesWithNoOutput.Max(x => x.SourceProperties.LastModifiedDate);
var oldestOutputFileTime = filePropeties
.Where(x => x.SourceHasOutput && x.OutputProperties.Exists)
.Min(x => x.OutputProperties.LastModifiedDate);
fileWithNoOutputHasChanged = newestSourceWithNoOutputFileTime >= oldestOutputFileTime;
}
return pairFileHasChanged || fileWithNoOutputHasChanged;
}
}
return true;
}
private string GetOutputPath(string sourcePath, BatchCompileConfiguration compileConfiguration)
{
if (sourcePath.IndexOf(compileConfiguration.SourceDirectory, StringComparison.OrdinalIgnoreCase) >= 0)
{
var relativePath = FileProbe.GetRelativePath(compileConfiguration.SourceDirectory, sourcePath);
var outputPath = Path.Combine(compileConfiguration.OutDirectory, relativePath);
outputPath = Path.ChangeExtension(outputPath, ".js");
return outputPath;
}
else
{
ChutzpahTracer.TraceWarning(
"Can't find location for generated path on {0} since it is not inside of configured source dir {1}",
sourcePath,
compileConfiguration.SourceDirectory);
}
return null;
}
private FileProperties GetFileProperties(string path)
{
var fileProperties = new FileProperties();
if (string.IsNullOrEmpty(path))
{
return fileProperties;
}
fileProperties.Path = path;
fileProperties.Exists = fileSystem.FileExists(path);
fileProperties.LastModifiedDate = fileSystem.GetLastWriteTime(path);
return fileProperties;
}
private class FileProperties
{
public DateTime LastModifiedDate { get; set; }
public string Path { get; set; }
public bool Exists { get; set; }
}
private class SourceCompileInfo
{
public SourceCompileInfo()
{
SourceHasOutput = true;
}
public bool SourceHasOutput { get; set; }
public FileProperties SourceProperties { get; set; }
public FileProperties OutputProperties { get; set; }
}
}
}
| |
//
// Copyright (C) Microsoft. All rights reserved.
//
using Microsoft.PowerShell.Activities;
using System.Management.Automation;
using System.Activities;
using System.Collections.Generic;
using System.ComponentModel;
namespace Microsoft.WSMan.Management.Activities
{
/// <summary>
/// Activity to invoke the Microsoft.WSMan.Management\New-WSManInstance command in a Workflow.
/// </summary>
[System.CodeDom.Compiler.GeneratedCode("Microsoft.PowerShell.Activities.ActivityGenerator.GenerateFromName", "3.0")]
public sealed class NewWSManInstance : PSRemotingActivity
{
/// <summary>
/// Gets the display name of the command invoked by this activity.
/// </summary>
public NewWSManInstance()
{
this.DisplayName = "New-WSManInstance";
}
/// <summary>
/// Gets the fully qualified name of the command invoked by this activity.
/// </summary>
public override string PSCommandName { get { return "Microsoft.WSMan.Management\\New-WSManInstance"; } }
// Arguments
/// <summary>
/// Provides access to the ApplicationName parameter.
/// </summary>
[ParameterSpecificCategory]
[DefaultValue(null)]
public InArgument<System.String> ApplicationName { get; set; }
/// <summary>
/// Provides access to the ComputerName parameter.
/// </summary>
[ParameterSpecificCategory]
[DefaultValue(null)]
public InArgument<System.String> ComputerName { get; set; }
/// <summary>
/// Provides access to the ConnectionURI parameter.
/// </summary>
[ParameterSpecificCategory]
[DefaultValue(null)]
public InArgument<System.Uri> ConnectionURI { get; set; }
/// <summary>
/// Provides access to the FilePath parameter.
/// </summary>
[ParameterSpecificCategory]
[DefaultValue(null)]
public InArgument<System.String> FilePath { get; set; }
/// <summary>
/// Provides access to the OptionSet parameter.
/// </summary>
[ParameterSpecificCategory]
[DefaultValue(null)]
public InArgument<System.Collections.Hashtable> OptionSet { get; set; }
/// <summary>
/// Provides access to the Port parameter.
/// </summary>
[ParameterSpecificCategory]
[DefaultValue(null)]
public InArgument<System.Int32> Port { get; set; }
/// <summary>
/// Provides access to the ResourceURI parameter.
/// </summary>
[ParameterSpecificCategory]
[DefaultValue(null)]
public InArgument<System.Uri> ResourceURI { get; set; }
/// <summary>
/// Provides access to the SelectorSet parameter.
/// </summary>
[ParameterSpecificCategory]
[DefaultValue(null)]
public InArgument<System.Collections.Hashtable> SelectorSet { get; set; }
/// <summary>
/// Provides access to the SessionOption parameter.
/// </summary>
[ParameterSpecificCategory]
[DefaultValue(null)]
public InArgument<Microsoft.WSMan.Management.SessionOption> SessionOption { get; set; }
/// <summary>
/// Provides access to the UseSSL parameter.
/// </summary>
[ParameterSpecificCategory]
[DefaultValue(null)]
public InArgument<System.Management.Automation.SwitchParameter> UseSSL { get; set; }
/// <summary>
/// Provides access to the ValueSet parameter.
/// </summary>
[ParameterSpecificCategory]
[DefaultValue(null)]
public InArgument<System.Collections.Hashtable> ValueSet { get; set; }
/// <summary>
/// Provides access to the Credential parameter.
/// </summary>
[ParameterSpecificCategory]
[DefaultValue(null)]
public InArgument<System.Management.Automation.PSCredential> Credential { get; set; }
/// <summary>
/// Provides access to the Authentication parameter.
/// </summary>
[ParameterSpecificCategory]
[DefaultValue(null)]
public InArgument<Microsoft.WSMan.Management.AuthenticationMechanism> Authentication { get; set; }
/// <summary>
/// Provides access to the CertificateThumbprint parameter.
/// </summary>
[ParameterSpecificCategory]
[DefaultValue(null)]
public InArgument<System.String> CertificateThumbprint { get; set; }
/// <summary>
/// Declares that this activity supports its own remoting.
/// </summary>
protected override bool SupportsCustomRemoting { get { return true; } }
// Module defining this command
// Optional custom code for this activity
/// <summary>
/// Returns a configured instance of System.Management.Automation.PowerShell, pre-populated with the command to run.
/// </summary>
/// <param name="context">The NativeActivityContext for the currently running activity.</param>
/// <returns>A populated instance of Sytem.Management.Automation.PowerShell</returns>
/// <remarks>The infrastructure takes responsibility for closing and disposing the PowerShell instance returned.</remarks>
protected override ActivityImplementationContext GetPowerShell(NativeActivityContext context)
{
System.Management.Automation.PowerShell invoker = global::System.Management.Automation.PowerShell.Create();
System.Management.Automation.PowerShell targetCommand = invoker.AddCommand(PSCommandName);
// Initialize the arguments
if(ApplicationName.Expression != null)
{
targetCommand.AddParameter("ApplicationName", ApplicationName.Get(context));
}
if((ComputerName.Expression != null) && (PSRemotingBehavior.Get(context) != RemotingBehavior.Custom))
{
targetCommand.AddParameter("ComputerName", ComputerName.Get(context));
}
if(ConnectionURI.Expression != null)
{
targetCommand.AddParameter("ConnectionURI", ConnectionURI.Get(context));
}
if(FilePath.Expression != null)
{
targetCommand.AddParameter("FilePath", FilePath.Get(context));
}
if(OptionSet.Expression != null)
{
targetCommand.AddParameter("OptionSet", OptionSet.Get(context));
}
if(Port.Expression != null)
{
targetCommand.AddParameter("Port", Port.Get(context));
}
if(ResourceURI.Expression != null)
{
targetCommand.AddParameter("ResourceURI", ResourceURI.Get(context));
}
if(SelectorSet.Expression != null)
{
targetCommand.AddParameter("SelectorSet", SelectorSet.Get(context));
}
if(SessionOption.Expression != null)
{
targetCommand.AddParameter("SessionOption", SessionOption.Get(context));
}
if(UseSSL.Expression != null)
{
targetCommand.AddParameter("UseSSL", UseSSL.Get(context));
}
if(ValueSet.Expression != null)
{
targetCommand.AddParameter("ValueSet", ValueSet.Get(context));
}
if(Credential.Expression != null)
{
targetCommand.AddParameter("Credential", Credential.Get(context));
}
if(Authentication.Expression != null)
{
targetCommand.AddParameter("Authentication", Authentication.Get(context));
}
if(CertificateThumbprint.Expression != null)
{
targetCommand.AddParameter("CertificateThumbprint", CertificateThumbprint.Get(context));
}
if(GetIsComputerNameSpecified(context) && (PSRemotingBehavior.Get(context) == RemotingBehavior.Custom))
{
targetCommand.AddParameter("ComputerName", PSComputerName.Get(context));
}
return new ActivityImplementationContext() { PowerShellInstance = invoker };
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.