context stringlengths 2.52k 185k | gt stringclasses 1
value |
|---|---|
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Collections.ObjectModel;
using System.Runtime;
using System.ServiceModel.Channels;
using System.Xml;
namespace System.ServiceModel
{
public class EndpointAddress
{
private static Uri s_anonymousUri;
private static Uri s_noneUri;
private static EndpointAddress s_anonymousAddress;
/*
Conceptually, the agnostic EndpointAddress class represents all of UNION(v200408,v10) data thusly:
- Address Uri (both versions - the Address)
- AddressHeaderCollection (both versions - RefProp&RefParam both project into here)
- PSP blob (200408 - this is PortType, ServiceName, Policy, it is not surfaced in OM)
- metadata (both versions, but weird semantics in 200408)
- identity (both versions, this is the one 'extension' that we know about)
- extensions (both versions, the "any*" stuff at the end)
When reading from 200408:
- Address is projected into Uri
- both RefProps and RefParams are projected into AddressHeaderCollection,
they (internally) remember 'which kind' they are
- PortType, ServiceName, Policy are projected into the (internal) PSP blob
- if we see a wsx:metadata element next, we project that element and that element only into the metadata reader
- we read the rest, recognizing and fishing out identity if there, projecting rest to extensions reader
When reading from 10:
- Address is projected into Uri
- RefParams are projected into AddressHeaderCollection; they (internally) remember 'which kind' they are
- nothing is projected into the (internal) PSP blob (it's empty)
- if there's a wsa10:metadata element, everything inside it projects into metadatareader
- we read the rest, recognizing and fishing out identity if there, projecting rest to extensions reader
When writing to 200408:
- Uri is written as Address
- AddressHeaderCollection is written as RefProps & RefParams, based on what they internally remember selves to be
- PSP blob is written out verbatim (will have: PortType?, ServiceName?, Policy?)
- metadata reader is written out verbatim
- identity is written out as extension
- extension reader is written out verbatim
When writing to 10:
- Uri is written as Address
- AddressHeaderCollection is all written as RefParams, regardless of what they internally remember selves to be
- PSP blob is ignored
- if metadata reader is non-empty, we write its value out verbatim inside a wsa10:metadata element
- identity is written out as extension
- extension reader is written out verbatim
EndpointAddressBuilder:
- you can set metadata to any value you like; we don't (cannot) validate because 10 allows anything
- you can set any extensions you like
Known Weirdnesses:
- PSP blob does not surface in OM - it can only roundtrip 200408wire->OM->200408wire
- RefProperty distinction does not surface in OM - it can only roundtrip 200408wire->OM->200408wire
- regardless of what metadata in reader, when you roundtrip OM->200408wire->OM, only wsx:metadata
as first element after PSP will stay in metadata, anything else gets dumped in extensions
- PSP blob is lost when doing OM->10wire->OM
- RefProps turn into RefParams when doing OM->10wire->OM
- Identity is always shuffled to front of extensions when doing anyWire->OM->anyWire
*/
private AddressingVersion _addressingVersion;
private AddressHeaderCollection _headers;
private EndpointIdentity _identity;
private Uri _uri;
private XmlBuffer _buffer; // invariant: each section in the buffer will start with a dummy wrapper element
private int _extensionSection;
private int _metadataSection;
private int _pspSection;
private bool _isAnonymous;
private bool _isNone;
// these are the element name/namespace for the dummy wrapper element that wraps each buffer section
internal const string DummyName = "Dummy";
internal const string DummyNamespace = "http://Dummy";
private EndpointAddress(AddressingVersion version, Uri uri, EndpointIdentity identity, AddressHeaderCollection headers, XmlBuffer buffer, int metadataSection, int extensionSection, int pspSection)
{
Init(version, uri, identity, headers, buffer, metadataSection, extensionSection, pspSection);
}
public EndpointAddress(string uri)
{
if (uri == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("uri");
}
Uri u = new Uri(uri);
Init(u, (EndpointIdentity)null, (AddressHeaderCollection)null, null, -1, -1, -1);
}
public EndpointAddress(Uri uri, params AddressHeader[] addressHeaders)
: this(uri, (EndpointIdentity)null, addressHeaders)
{
}
public EndpointAddress(Uri uri, EndpointIdentity identity, params AddressHeader[] addressHeaders)
{
if (uri == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("uri");
}
Init(uri, identity, addressHeaders);
}
internal EndpointAddress(Uri uri, EndpointIdentity identity, AddressHeaderCollection headers, XmlDictionaryReader metadataReader, XmlDictionaryReader extensionReader, XmlDictionaryReader pspReader)
{
if (uri == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("uri");
}
XmlBuffer buffer = null;
PossiblyPopulateBuffer(metadataReader, ref buffer, out _metadataSection);
EndpointIdentity ident2;
int extSection;
buffer = ReadExtensions(extensionReader, null, buffer, out ident2, out extSection);
if (identity != null && ident2 != null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(SR.MultipleIdentities, "extensionReader"));
}
PossiblyPopulateBuffer(pspReader, ref buffer, out _pspSection);
if (buffer != null)
{
buffer.Close();
}
Init(uri, identity ?? ident2, headers, buffer, _metadataSection, extSection, _pspSection);
}
private void Init(Uri uri, EndpointIdentity identity, AddressHeader[] headers)
{
if (headers == null || headers.Length == 0)
{
Init(uri, identity, (AddressHeaderCollection)null, null, -1, -1, -1);
}
else
{
Init(uri, identity, new AddressHeaderCollection(headers), null, -1, -1, -1);
}
}
private void Init(Uri uri, EndpointIdentity identity, AddressHeaderCollection headers, XmlBuffer buffer, int metadataSection, int extensionSection, int pspSection)
{
Init(null, uri, identity, headers, buffer, metadataSection, extensionSection, pspSection);
}
private void Init(AddressingVersion version, Uri uri, EndpointIdentity identity, AddressHeaderCollection headers, XmlBuffer buffer, int metadataSection, int extensionSection, int pspSection)
{
if (!uri.IsAbsoluteUri)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument("uri", SR.UriMustBeAbsolute);
_addressingVersion = version;
_uri = uri;
_identity = identity;
_headers = headers;
_buffer = buffer;
_metadataSection = metadataSection;
_extensionSection = extensionSection;
_pspSection = pspSection;
if (version != null)
{
_isAnonymous = uri == version.AnonymousUri;
_isNone = uri == version.NoneUri;
}
else
{
_isAnonymous = object.ReferenceEquals(uri, AnonymousUri) || uri == AnonymousUri;
_isNone = object.ReferenceEquals(uri, NoneUri) || uri == NoneUri;
}
if (_isAnonymous)
{
_uri = AnonymousUri;
}
if (_isNone)
{
_uri = NoneUri;
}
}
internal static EndpointAddress AnonymousAddress
{
get
{
if (s_anonymousAddress == null)
s_anonymousAddress = new EndpointAddress(AnonymousUri);
return s_anonymousAddress;
}
}
public static Uri AnonymousUri
{
get
{
if (s_anonymousUri == null)
s_anonymousUri = new Uri(AddressingStrings.AnonymousUri);
return s_anonymousUri;
}
}
public static Uri NoneUri
{
get
{
if (s_noneUri == null)
s_noneUri = new Uri(AddressingStrings.NoneUri);
return s_noneUri;
}
}
internal XmlBuffer Buffer
{
get
{
return _buffer;
}
}
public AddressHeaderCollection Headers
{
get
{
if (_headers == null)
{
_headers = new AddressHeaderCollection();
}
return _headers;
}
}
public EndpointIdentity Identity
{
get
{
return _identity;
}
}
public bool IsAnonymous
{
get
{
return _isAnonymous;
}
}
public bool IsNone
{
get
{
return _isNone;
}
}
public Uri Uri
{
get
{
return _uri;
}
}
public void ApplyTo(Message message)
{
if (message == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("message");
Uri uri = this.Uri;
if (IsAnonymous)
{
if (message.Version.Addressing == AddressingVersion.WSAddressing10)
{
message.Headers.To = null;
}
else
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
new ProtocolException(SR.Format(SR.AddressingVersionNotSupported, message.Version.Addressing)));
}
}
else if (IsNone)
{
message.Headers.To = message.Version.Addressing.NoneUri;
}
else
{
message.Headers.To = uri;
}
message.Properties.Via = message.Headers.To;
if (_headers != null)
{
_headers.AddHeadersTo(message);
}
}
// NOTE: UserInfo, Query, and Fragment are ignored when comparing Uris as addresses
// this is the WCF logic for comparing Uris that represent addresses
// this method must be kept in sync with UriGetHashCode
internal static bool UriEquals(Uri u1, Uri u2, bool ignoreCase, bool includeHostInComparison)
{
return UriEquals(u1, u2, ignoreCase, includeHostInComparison, true);
}
internal static bool UriEquals(Uri u1, Uri u2, bool ignoreCase, bool includeHostInComparison, bool includePortInComparison)
{
// PERF: Equals compares everything but UserInfo and Fragments. It's more strict than
// we are, and faster, so it is done first.
if (u1.Equals(u2))
{
return true;
}
if (u1.Scheme != u2.Scheme) // Uri.Scheme is always lowercase
{
return false;
}
if (includePortInComparison)
{
if (u1.Port != u2.Port)
{
return false;
}
}
if (includeHostInComparison)
{
if (string.Compare(u1.Host, u2.Host, StringComparison.OrdinalIgnoreCase) != 0)
{
return false;
}
}
if (string.Compare(u1.AbsolutePath, u2.AbsolutePath, ignoreCase ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal) == 0)
{
return true;
}
// Normalize for trailing slashes
string u1Path = u1.GetComponents(UriComponents.Path, UriFormat.Unescaped);
string u2Path = u2.GetComponents(UriComponents.Path, UriFormat.Unescaped);
int u1Len = (u1Path.Length > 0 && u1Path[u1Path.Length - 1] == '/') ? u1Path.Length - 1 : u1Path.Length;
int u2Len = (u2Path.Length > 0 && u2Path[u2Path.Length - 1] == '/') ? u2Path.Length - 1 : u2Path.Length;
if (u2Len != u1Len)
{
return false;
}
return string.Compare(u1Path, 0, u2Path, 0, u1Len, ignoreCase ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal) == 0;
}
// this method must be kept in sync with UriEquals
internal static int UriGetHashCode(Uri uri, bool includeHostInComparison)
{
return UriGetHashCode(uri, includeHostInComparison, true);
}
internal static int UriGetHashCode(Uri uri, bool includeHostInComparison, bool includePortInComparison)
{
UriComponents components = UriComponents.Scheme | UriComponents.Path;
if (includePortInComparison)
{
components = components | UriComponents.Port;
}
if (includeHostInComparison)
{
components = components | UriComponents.Host;
}
// Normalize for trailing slashes
string uriString = uri.GetComponents(components, UriFormat.Unescaped);
if (uriString.Length > 0 && uriString[uriString.Length - 1] != '/')
uriString = string.Concat(uriString, "/");
return StringComparer.OrdinalIgnoreCase.GetHashCode(uriString);
}
internal bool EndpointEquals(EndpointAddress endpointAddress)
{
if (endpointAddress == null)
{
return false;
}
if (object.ReferenceEquals(this, endpointAddress))
{
return true;
}
Uri thisTo = this.Uri;
Uri otherTo = endpointAddress.Uri;
if (!UriEquals(thisTo, otherTo, false /* ignoreCase */, true /* includeHostInComparison */))
{
return false;
}
if (this.Identity == null)
{
if (endpointAddress.Identity != null)
{
return false;
}
}
else if (!this.Identity.Equals(endpointAddress.Identity))
{
return false;
}
if (!this.Headers.IsEquivalent(endpointAddress.Headers))
{
return false;
}
return true;
}
public override bool Equals(object obj)
{
if (object.ReferenceEquals(obj, this))
{
return true;
}
if (obj == null)
{
return false;
}
EndpointAddress address = obj as EndpointAddress;
if (address == null)
{
return false;
}
return EndpointEquals(address);
}
public override int GetHashCode()
{
return UriGetHashCode(_uri, true /* includeHostInComparison */);
}
// returns reader without starting dummy wrapper element
internal XmlDictionaryReader GetReaderAtPsp()
{
return GetReaderAtSection(_buffer, _pspSection);
}
// returns reader without starting dummy wrapper element
public XmlDictionaryReader GetReaderAtMetadata()
{
return GetReaderAtSection(_buffer, _metadataSection);
}
// returns reader without starting dummy wrapper element
public XmlDictionaryReader GetReaderAtExtensions()
{
return GetReaderAtSection(_buffer, _extensionSection);
}
private static XmlDictionaryReader GetReaderAtSection(XmlBuffer buffer, int section)
{
if (buffer == null || section < 0)
return null;
XmlDictionaryReader reader = buffer.GetReader(section);
reader.MoveToContent();
Fx.Assert(reader.Name == DummyName, "EndpointAddress: Expected dummy element not found");
reader.Read(); // consume the dummy wrapper element
return reader;
}
private void PossiblyPopulateBuffer(XmlDictionaryReader reader, ref XmlBuffer buffer, out int section)
{
if (reader == null)
{
section = -1;
}
else
{
if (buffer == null)
{
buffer = new XmlBuffer(short.MaxValue);
}
section = buffer.SectionCount;
XmlDictionaryWriter writer = buffer.OpenSection(reader.Quotas);
writer.WriteStartElement(DummyName, DummyNamespace);
Copy(writer, reader);
buffer.CloseSection();
}
}
public static EndpointAddress ReadFrom(XmlDictionaryReader reader)
{
AddressingVersion dummyVersion;
return ReadFrom(reader, out dummyVersion);
}
internal static EndpointAddress ReadFrom(XmlDictionaryReader reader, out AddressingVersion version)
{
if (reader == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("reader");
reader.ReadFullStartElement();
reader.MoveToContent();
if (reader.IsNamespaceUri(AddressingVersion.WSAddressing10.DictionaryNamespace))
{
version = AddressingVersion.WSAddressing10;
}
else if (reader.NodeType != XmlNodeType.Element)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument(
"reader", SR.CannotDetectAddressingVersion);
}
else
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument(
"reader", SR.Format(SR.AddressingVersionNotSupported, reader.NamespaceURI));
}
EndpointAddress ea = ReadFromDriver(version, reader);
reader.ReadEndElement();
return ea;
}
public static EndpointAddress ReadFrom(AddressingVersion addressingVersion, XmlDictionaryReader reader)
{
if (reader == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("reader");
if (addressingVersion == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("addressingVersion");
reader.ReadFullStartElement();
EndpointAddress ea = ReadFromDriver(addressingVersion, reader);
reader.ReadEndElement();
return ea;
}
private static EndpointAddress ReadFromDriver(AddressingVersion addressingVersion, XmlDictionaryReader reader)
{
AddressHeaderCollection headers;
EndpointIdentity identity;
Uri uri;
XmlBuffer buffer;
bool isAnonymous;
int extensionSection;
int metadataSection;
int pspSection = -1;
if (addressingVersion == AddressingVersion.WSAddressing10)
{
isAnonymous = ReadContentsFrom10(reader, out uri, out headers, out identity, out buffer, out metadataSection, out extensionSection);
}
else
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument("addressingVersion",
SR.Format(SR.AddressingVersionNotSupported, addressingVersion));
}
if (isAnonymous && headers == null && identity == null && buffer == null)
{
return AnonymousAddress;
}
else
{
return new EndpointAddress(addressingVersion, uri, identity, headers, buffer, metadataSection, extensionSection, pspSection);
}
}
internal static XmlBuffer ReadExtensions(XmlDictionaryReader reader, AddressingVersion version, XmlBuffer buffer, out EndpointIdentity identity, out int section)
{
if (reader == null)
{
identity = null;
section = -1;
return buffer;
}
// EndpointIdentity and extensions
identity = null;
XmlDictionaryWriter bufferWriter = null;
reader.MoveToContent();
while (reader.IsStartElement())
{
if (reader.IsStartElement(XD.AddressingDictionary.Identity, XD.AddressingDictionary.IdentityExtensionNamespace))
{
if (identity != null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(CreateXmlException(reader, SR.Format(SR.UnexpectedDuplicateElement, XD.AddressingDictionary.Identity.Value, XD.AddressingDictionary.IdentityExtensionNamespace.Value)));
identity = EndpointIdentity.ReadIdentity(reader);
}
else if (version != null && reader.NamespaceURI == version.Namespace)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(CreateXmlException(reader, SR.Format(SR.AddressingExtensionInBadNS, reader.LocalName, reader.NamespaceURI)));
}
else
{
if (bufferWriter == null)
{
if (buffer == null)
buffer = new XmlBuffer(short.MaxValue);
bufferWriter = buffer.OpenSection(reader.Quotas);
bufferWriter.WriteStartElement(DummyName, DummyNamespace);
}
bufferWriter.WriteNode(reader, true);
}
reader.MoveToContent();
}
if (bufferWriter != null)
{
bufferWriter.WriteEndElement();
buffer.CloseSection();
section = buffer.SectionCount - 1;
}
else
{
section = -1;
}
return buffer;
}
private static bool ReadContentsFrom10(XmlDictionaryReader reader, out Uri uri, out AddressHeaderCollection headers, out EndpointIdentity identity, out XmlBuffer buffer, out int metadataSection, out int extensionSection)
{
buffer = null;
extensionSection = -1;
metadataSection = -1;
// Cache address string
if (!reader.IsStartElement(XD.AddressingDictionary.Address, XD.Addressing10Dictionary.Namespace))
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(CreateXmlException(reader, SR.Format(SR.UnexpectedElementExpectingElement, reader.LocalName, reader.NamespaceURI, XD.AddressingDictionary.Address.Value, XD.Addressing10Dictionary.Namespace.Value)));
string address = reader.ReadElementContentAsString();
// Headers
if (reader.IsStartElement(XD.AddressingDictionary.ReferenceParameters, XD.Addressing10Dictionary.Namespace))
{
headers = AddressHeaderCollection.ReadServiceParameters(reader);
}
else
{
headers = null;
}
// Metadata
if (reader.IsStartElement(XD.Addressing10Dictionary.Metadata, XD.Addressing10Dictionary.Namespace))
{
reader.ReadFullStartElement(); // the wsa10:Metadata element is never stored in the buffer
buffer = new XmlBuffer(short.MaxValue);
metadataSection = 0;
XmlDictionaryWriter writer = buffer.OpenSection(reader.Quotas);
writer.WriteStartElement(DummyName, DummyNamespace);
while (reader.NodeType != XmlNodeType.EndElement && !reader.EOF)
{
writer.WriteNode(reader, true);
}
writer.Flush();
buffer.CloseSection();
reader.ReadEndElement();
}
// Extensions
buffer = ReadExtensions(reader, AddressingVersion.WSAddressing10, buffer, out identity, out extensionSection);
if (buffer != null)
{
buffer.Close();
}
// Process Address
if (address == Addressing10Strings.Anonymous)
{
uri = AddressingVersion.WSAddressing10.AnonymousUri;
if (headers == null && identity == null)
{
return true;
}
}
else if (address == Addressing10Strings.NoneAddress)
{
uri = AddressingVersion.WSAddressing10.NoneUri;
return false;
}
else
{
if (!Uri.TryCreate(address, UriKind.Absolute, out uri))
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(SR.Format(SR.InvalidUriValue, address, XD.AddressingDictionary.Address.Value, XD.Addressing10Dictionary.Namespace.Value)));
}
}
return false;
}
private static XmlException CreateXmlException(XmlDictionaryReader reader, string message)
{
IXmlLineInfo lineInfo = reader as IXmlLineInfo;
if (lineInfo != null)
{
return new XmlException(message, null, lineInfo.LineNumber, lineInfo.LinePosition);
}
return new XmlException(message);
}
// this function has a side-effect on the reader (MoveToContent)
private static bool Done(XmlDictionaryReader reader)
{
reader.MoveToContent();
return (reader.NodeType == XmlNodeType.EndElement || reader.EOF);
}
// copy all of reader to writer
static internal void Copy(XmlDictionaryWriter writer, XmlDictionaryReader reader)
{
while (!Done(reader))
{
writer.WriteNode(reader, true);
}
}
public override string ToString()
{
return _uri.ToString();
}
public void WriteContentsTo(AddressingVersion addressingVersion, XmlDictionaryWriter writer)
{
if (writer == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("writer");
}
if (addressingVersion == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("addressingVersion");
}
if (addressingVersion == AddressingVersion.WSAddressing10)
{
WriteContentsTo10(writer);
}
else if (addressingVersion == AddressingVersion.None)
{
WriteContentsToNone(writer);
}
else
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument("addressingVersion",
SR.Format(SR.AddressingVersionNotSupported, addressingVersion));
}
}
private void WriteContentsToNone(XmlDictionaryWriter writer)
{
writer.WriteString(this.Uri.AbsoluteUri);
}
private void WriteContentsTo10(XmlDictionaryWriter writer)
{
// Address
writer.WriteStartElement(XD.AddressingDictionary.Address, XD.Addressing10Dictionary.Namespace);
if (_isAnonymous)
{
writer.WriteString(XD.Addressing10Dictionary.Anonymous);
}
else if (_isNone)
{
writer.WriteString(XD.Addressing10Dictionary.NoneAddress);
}
else
{
writer.WriteString(this.Uri.AbsoluteUri);
}
writer.WriteEndElement();
// Headers
if (_headers != null && _headers.Count > 0)
{
writer.WriteStartElement(XD.AddressingDictionary.ReferenceParameters, XD.Addressing10Dictionary.Namespace);
_headers.WriteContentsTo(writer);
writer.WriteEndElement();
}
// Metadata
if (_metadataSection >= 0)
{
XmlDictionaryReader reader = GetReaderAtSection(_buffer, _metadataSection);
writer.WriteStartElement(XD.Addressing10Dictionary.Metadata, XD.Addressing10Dictionary.Namespace);
Copy(writer, reader);
writer.WriteEndElement();
}
// EndpointIdentity
if (this.Identity != null)
{
this.Identity.WriteTo(writer);
}
// Extensions
if (_extensionSection >= 0)
{
XmlDictionaryReader reader = GetReaderAtSection(_buffer, _extensionSection);
while (reader.IsStartElement())
{
if (reader.NamespaceURI == AddressingVersion.WSAddressing10.Namespace)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(CreateXmlException(reader, SR.Format(SR.AddressingExtensionInBadNS, reader.LocalName, reader.NamespaceURI)));
}
writer.WriteNode(reader, true);
}
}
}
public void WriteContentsTo(AddressingVersion addressingVersion, XmlWriter writer)
{
XmlDictionaryWriter dictionaryWriter = XmlDictionaryWriter.CreateDictionaryWriter(writer);
WriteContentsTo(addressingVersion, dictionaryWriter);
}
public void WriteTo(AddressingVersion addressingVersion, XmlDictionaryWriter writer)
{
WriteTo(addressingVersion, writer, XD.AddressingDictionary.EndpointReference,
addressingVersion.DictionaryNamespace);
}
public void WriteTo(AddressingVersion addressingVersion, XmlDictionaryWriter writer, XmlDictionaryString localName, XmlDictionaryString ns)
{
if (writer == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("writer");
}
if (addressingVersion == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("addressingVersion");
}
if (localName == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("localName");
}
if (ns == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("ns");
}
writer.WriteStartElement(localName, ns);
WriteContentsTo(addressingVersion, writer);
writer.WriteEndElement();
}
public void WriteTo(AddressingVersion addressingVersion, XmlWriter writer)
{
XmlDictionaryString dictionaryNamespace = addressingVersion.DictionaryNamespace;
if (dictionaryNamespace == null)
{
dictionaryNamespace = XD.AddressingDictionary.Empty;
}
WriteTo(addressingVersion, XmlDictionaryWriter.CreateDictionaryWriter(writer),
XD.AddressingDictionary.EndpointReference, dictionaryNamespace);
}
public void WriteTo(AddressingVersion addressingVersion, XmlWriter writer, string localName, string ns)
{
if (writer == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("writer");
}
if (addressingVersion == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("addressingVersion");
}
if (localName == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("localName");
}
if (ns == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("ns");
}
writer.WriteStartElement(localName, ns);
WriteContentsTo(addressingVersion, writer);
writer.WriteEndElement();
}
public static bool operator ==(EndpointAddress address1, EndpointAddress address2)
{
if (object.ReferenceEquals(address2, null))
{
return (object.ReferenceEquals(address1, null));
}
return address2.Equals(address1);
}
public static bool operator !=(EndpointAddress address1, EndpointAddress address2)
{
if (object.ReferenceEquals(address2, null))
{
return !object.ReferenceEquals(address1, null);
}
return !address2.Equals(address1);
}
}
public class EndpointAddressBuilder
{
private Uri _uri;
private EndpointIdentity _identity;
private Collection<AddressHeader> _headers;
private XmlBuffer _extensionBuffer; // this buffer is wrapped just like in EndpointAddress
private XmlBuffer _metadataBuffer; // this buffer is wrapped just like in EndpointAddress
private bool _hasExtension;
private bool _hasMetadata;
private EndpointAddress _epr;
public EndpointAddressBuilder()
{
_headers = new Collection<AddressHeader>();
}
public EndpointAddressBuilder(EndpointAddress address)
{
if (address == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("address");
}
_epr = address;
_uri = address.Uri;
_identity = address.Identity;
_headers = new Collection<AddressHeader>();
#pragma warning suppress 56506
for (int i = 0; i < address.Headers.Count; i++)
{
_headers.Add(address.Headers[i]);
}
}
public Uri Uri
{
get { return _uri; }
set { _uri = value; }
}
public EndpointIdentity Identity
{
get { return _identity; }
set { _identity = value; }
}
public Collection<AddressHeader> Headers
{
get { return _headers; }
}
public XmlDictionaryReader GetReaderAtMetadata()
{
if (!_hasMetadata)
{
return _epr == null ? null : _epr.GetReaderAtMetadata();
}
if (_metadataBuffer == null)
{
return null;
}
XmlDictionaryReader reader = _metadataBuffer.GetReader(0);
reader.MoveToContent();
Fx.Assert(reader.Name == EndpointAddress.DummyName, "EndpointAddressBuilder: Expected dummy element not found");
reader.Read(); // consume the wrapper element
return reader;
}
public void SetMetadataReader(XmlDictionaryReader reader)
{
_hasMetadata = true;
_metadataBuffer = null;
if (reader != null)
{
_metadataBuffer = new XmlBuffer(short.MaxValue);
XmlDictionaryWriter writer = _metadataBuffer.OpenSection(reader.Quotas);
writer.WriteStartElement(EndpointAddress.DummyName, EndpointAddress.DummyNamespace);
EndpointAddress.Copy(writer, reader);
_metadataBuffer.CloseSection();
_metadataBuffer.Close();
}
}
public XmlDictionaryReader GetReaderAtExtensions()
{
if (!_hasExtension)
{
return _epr == null ? null : _epr.GetReaderAtExtensions();
}
if (_extensionBuffer == null)
{
return null;
}
XmlDictionaryReader reader = _extensionBuffer.GetReader(0);
reader.MoveToContent();
Fx.Assert(reader.Name == EndpointAddress.DummyName, "EndpointAddressBuilder: Expected dummy element not found");
reader.Read(); // consume the wrapper element
return reader;
}
public void SetExtensionReader(XmlDictionaryReader reader)
{
_hasExtension = true;
EndpointIdentity identity;
int tmp;
_extensionBuffer = EndpointAddress.ReadExtensions(reader, null, null, out identity, out tmp);
if (_extensionBuffer != null)
{
_extensionBuffer.Close();
}
if (identity != null)
{
_identity = identity;
}
}
public EndpointAddress ToEndpointAddress()
{
return new EndpointAddress(
_uri,
_identity,
new AddressHeaderCollection(_headers),
this.GetReaderAtMetadata(),
this.GetReaderAtExtensions(),
_epr == null ? null : _epr.GetReaderAtPsp());
}
}
}
| |
/*
* CID0018.cs - ro culture handler.
*
* Copyright (c) 2003 Southern Storm Software, Pty Ltd
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
// Generated from "ro.txt".
namespace I18N.West
{
using System;
using System.Globalization;
using I18N.Common;
public class CID0018 : RootCulture
{
public CID0018() : base(0x0018) {}
public CID0018(int culture) : base(culture) {}
public override String Name
{
get
{
return "ro";
}
}
public override String ThreeLetterISOLanguageName
{
get
{
return "ron";
}
}
public override String ThreeLetterWindowsLanguageName
{
get
{
return "ROM";
}
}
public override String TwoLetterISOLanguageName
{
get
{
return "ro";
}
}
public override DateTimeFormatInfo DateTimeFormat
{
get
{
DateTimeFormatInfo dfi = base.DateTimeFormat;
dfi.AbbreviatedDayNames = new String[] {"D", "L", "Ma", "Mi", "J", "V", "S"};
dfi.DayNames = new String[] {"duminic\u0103", "luni", "mar\u0163i", "miercuri", "joi", "vineri", "s\u00EEmb\u0103t\u0103"};
dfi.AbbreviatedMonthNames = new String[] {"Ian", "Feb", "Mar", "Apr", "Mai", "Iun", "Iul", "Aug", "Sep", "Oct", "Nov", "Dec", ""};
dfi.MonthNames = new String[] {"ianuarie", "februarie", "martie", "aprilie", "mai", "iunie", "iulie", "august", "septembrie", "octombrie", "noiembrie", "decembrie", ""};
dfi.DateSeparator = ".";
dfi.TimeSeparator = ":";
dfi.LongDatePattern = "d MMMM yyyy";
dfi.LongTimePattern = "HH:mm:ss z";
dfi.ShortDatePattern = "dd.MM.yyyy";
dfi.ShortTimePattern = "HH:mm";
dfi.FullDateTimePattern = "d MMMM yyyy HH:mm:ss z";
dfi.I18NSetDateTimePatterns(new String[] {
"d:dd.MM.yyyy",
"D:d MMMM yyyy",
"f:d MMMM yyyy HH:mm:ss z",
"f:d MMMM yyyy HH:mm:ss z",
"f:d MMMM yyyy HH:mm:ss",
"f:d MMMM yyyy HH:mm",
"F:d MMMM yyyy HH:mm:ss",
"g:dd.MM.yyyy HH:mm:ss z",
"g:dd.MM.yyyy HH:mm:ss z",
"g:dd.MM.yyyy HH:mm:ss",
"g:dd.MM.yyyy HH:mm",
"G:dd.MM.yyyy HH:mm:ss",
"m:MMMM dd",
"M:MMMM dd",
"r:ddd, dd MMM yyyy HH':'mm':'ss 'GMT'",
"R:ddd, dd MMM yyyy HH':'mm':'ss 'GMT'",
"s:yyyy'-'MM'-'dd'T'HH':'mm':'ss",
"t:HH:mm:ss z",
"t:HH:mm:ss z",
"t:HH:mm:ss",
"t:HH:mm",
"T:HH:mm:ss",
"u:yyyy'-'MM'-'dd HH':'mm':'ss'Z'",
"U:dddd, dd MMMM yyyy HH:mm:ss",
"y:yyyy MMMM",
"Y:yyyy MMMM",
});
return dfi;
}
set
{
base.DateTimeFormat = value; // not used
}
}
public override NumberFormatInfo NumberFormat
{
get
{
NumberFormatInfo nfi = base.NumberFormat;
nfi.CurrencyDecimalSeparator = ",";
nfi.CurrencyGroupSeparator = ".";
nfi.NumberGroupSeparator = ".";
nfi.PercentGroupSeparator = ".";
nfi.NegativeSign = "-";
nfi.NumberDecimalSeparator = ",";
nfi.PercentDecimalSeparator = ",";
nfi.PercentSymbol = "%";
nfi.PerMilleSymbol = "\u2030";
return nfi;
}
set
{
base.NumberFormat = value; // not used
}
}
public override String ResolveLanguage(String name)
{
switch(name)
{
case "ro": return "rom\u00E2n\u0103";
}
return base.ResolveLanguage(name);
}
public override String ResolveCountry(String name)
{
switch(name)
{
case "RO": return "Rom\u00E2nia";
}
return base.ResolveCountry(name);
}
private class PrivateTextInfo : _I18NTextInfo
{
public PrivateTextInfo(int culture) : base(culture) {}
public override int ANSICodePage
{
get
{
return 1250;
}
}
public override int EBCDICCodePage
{
get
{
return 20880;
}
}
public override int MacCodePage
{
get
{
return 10029;
}
}
public override int OEMCodePage
{
get
{
return 852;
}
}
public override String ListSeparator
{
get
{
return ";";
}
}
}; // class PrivateTextInfo
public override TextInfo TextInfo
{
get
{
return new PrivateTextInfo(LCID);
}
}
}; // class CID0018
public class CNro : CID0018
{
public CNro() : base() {}
}; // class CNro
}; // namespace I18N.West
| |
/*
* Copyright (c) 2006-2014, openmetaverse.org
* 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.
* - Neither the name of the openmetaverse.org nor the names
* of its contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.Text;
namespace OpenMetaverse
{
/// <summary>
/// A Name Value pair with additional settings, used in the protocol
/// primarily to transmit avatar names and active group in object packets
/// </summary>
public struct NameValue
{
#region Enums
/// <summary>Type of the value</summary>
public enum ValueType
{
/// <summary>Unknown</summary>
Unknown = -1,
/// <summary>String value</summary>
String,
/// <summary></summary>
F32,
/// <summary></summary>
S32,
/// <summary></summary>
VEC3,
/// <summary></summary>
U32,
/// <summary>Deprecated</summary>
[Obsolete]
CAMERA,
/// <summary>String value, but designated as an asset</summary>
Asset,
/// <summary></summary>
U64
}
/// <summary>
///
/// </summary>
public enum ClassType
{
/// <summary></summary>
Unknown = -1,
/// <summary></summary>
ReadOnly,
/// <summary></summary>
ReadWrite,
/// <summary></summary>
Callback
}
/// <summary>
///
/// </summary>
public enum SendtoType
{
/// <summary></summary>
Unknown = -1,
/// <summary></summary>
Sim,
/// <summary></summary>
DataSim,
/// <summary></summary>
SimViewer,
/// <summary></summary>
DataSimViewer
}
#endregion Enums
/// <summary></summary>
public string Name;
/// <summary></summary>
public ValueType Type;
/// <summary></summary>
public ClassType Class;
/// <summary></summary>
public SendtoType Sendto;
/// <summary></summary>
public object Value;
private static readonly string[] TypeStrings = new string[]
{
"STRING",
"F32",
"S32",
"VEC3",
"U32",
"ASSET",
"U64"
};
private static readonly string[] ClassStrings = new string[]
{
"R", // Read-only
"RW", // Read-write
"CB" // Callback
};
private static readonly string[] SendtoStrings = new string[]
{
"S", // Sim
"DS", // Data Sim
"SV", // Sim Viewer
"DSV" // Data Sim Viewer
};
private static readonly char[] Separators = new char[]
{
' ',
'\n',
'\t',
'\r'
};
/// <summary>
/// Constructor that takes all the fields as parameters
/// </summary>
/// <param name="name"></param>
/// <param name="valueType"></param>
/// <param name="classType"></param>
/// <param name="sendtoType"></param>
/// <param name="value"></param>
public NameValue(string name, ValueType valueType, ClassType classType, SendtoType sendtoType, object value)
{
Name = name;
Type = valueType;
Class = classType;
Sendto = sendtoType;
Value = value;
}
/// <summary>
/// Constructor that takes a single line from a NameValue field
/// </summary>
/// <param name="data"></param>
public NameValue(string data)
{
int i;
// Name
i = data.IndexOfAny(Separators);
if (i < 1)
{
Name = String.Empty;
Type = ValueType.Unknown;
Class = ClassType.Unknown;
Sendto = SendtoType.Unknown;
Value = null;
return;
}
Name = data.Substring(0, i);
data = data.Substring(i + 1);
// Type
i = data.IndexOfAny(Separators);
if (i > 0)
{
Type = GetValueType(data.Substring(0, i));
data = data.Substring(i + 1);
// Class
i = data.IndexOfAny(Separators);
if (i > 0)
{
Class = GetClassType(data.Substring(0, i));
data = data.Substring(i + 1);
// Sendto
i = data.IndexOfAny(Separators);
if (i > 0)
{
Sendto = GetSendtoType(data.Substring(0, 1));
data = data.Substring(i + 1);
}
}
}
// Value
Type = ValueType.String;
Class = ClassType.ReadOnly;
Sendto = SendtoType.Sim;
Value = null;
SetValue(data);
}
public static string NameValuesToString(NameValue[] values)
{
if (values == null || values.Length == 0)
return String.Empty;
StringBuilder output = new StringBuilder();
for (int i = 0; i < values.Length; i++)
{
NameValue value = values[i];
if (value.Value != null)
{
string newLine = (i < values.Length - 1) ? "\n" : String.Empty;
output.AppendFormat("{0} {1} {2} {3} {4}{5}", value.Name, TypeStrings[(int)value.Type],
ClassStrings[(int)value.Class], SendtoStrings[(int)value.Sendto], value.Value.ToString(), newLine);
}
}
return output.ToString();
}
private void SetValue(string value)
{
switch (Type)
{
case ValueType.Asset:
case ValueType.String:
Value = value;
break;
case ValueType.F32:
{
float temp;
Utils.TryParseSingle(value, out temp);
Value = temp;
break;
}
case ValueType.S32:
{
int temp;
Int32.TryParse(value, out temp);
Value = temp;
break;
}
case ValueType.U32:
{
uint temp;
UInt32.TryParse(value, out temp);
Value = temp;
break;
}
case ValueType.U64:
{
ulong temp;
UInt64.TryParse(value, out temp);
Value = temp;
break;
}
case ValueType.VEC3:
{
Vector3 temp;
Vector3.TryParse(value, out temp);
Value = temp;
break;
}
default:
Value = null;
break;
}
}
private static ValueType GetValueType(string value)
{
ValueType type = ValueType.Unknown;
for (int i = 0; i < TypeStrings.Length; i++)
{
if (value == TypeStrings[i])
{
type = (ValueType)i;
break;
}
}
if (type == ValueType.Unknown)
type = ValueType.String;
return type;
}
private static ClassType GetClassType(string value)
{
ClassType type = ClassType.Unknown;
for (int i = 0; i < ClassStrings.Length; i++)
{
if (value == ClassStrings[i])
{
type = (ClassType)i;
break;
}
}
if (type == ClassType.Unknown)
type = ClassType.ReadOnly;
return type;
}
private static SendtoType GetSendtoType(string value)
{
SendtoType type = SendtoType.Unknown;
for (int i = 0; i < SendtoStrings.Length; i++)
{
if (value == SendtoStrings[i])
{
type = (SendtoType)i;
break;
}
}
if (type == SendtoType.Unknown)
type = SendtoType.Sim;
return type;
}
}
}
| |
/*******************************************************************************
INTEL CORPORATION PROPRIETARY INFORMATION
This software is supplied under the terms of a license agreement or nondisclosure
agreement with Intel Corporation and may not be copied or disclosed except in
accordance with the terms of that agreement
Copyright(c) 2012-2014 Intel Corporation. All Rights Reserved.
*******************************************************************************/
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
namespace RSUnityToolkit
{
/// <summary>
/// Facial Expression rule - Process Animation trigger
/// </summary>
[AddComponentMenu("")]
[AnimationTrigger.AnimationTriggerAtt]
public class FacialExpressionAnimationRule : BaseRule
{
#region Constants
private const float OPTIMAL_RELATIVE_FACE_HEIGHT = 55.5f;
private const float OPTIMAL_EYEBROW_UP_MAX_DISTANCE = 40f;
private const float EYEBROW_UP_INITIAL_DISTANCE = 23f;
private const float OPTIMAL_EYE_CLOSE_MAX_DISTANCE = 4.5f;
private const float EYE_CLOSE_INITIAL_DISTANCE = 10f;
private const float OPTIMAL_MOUTH_OPEN_MAX_DISTANCE = 41f;
private const float MOUTH_OPEN_INITIAL_DISTANCE = 8f;
private const float NORMALIZE_MAX_FACIAL_EXPRESSION_VALUE = 100f;
#endregion
#region Public Fields
public string[] AvailableExpressions;
#endregion
#region Private Fields
#endregion
#region C'tor
public FacialExpressionAnimationRule(): base()
{
FriendlyName = "Facial Expression Animation";
int numOfExpressions = System.Enum.GetValues(typeof(PXCMFaceData.ExpressionsData.FaceExpression)).Length;
AvailableExpressions = new string[numOfExpressions];
int i = 0;;
foreach(PXCMFaceData.ExpressionsData.FaceExpression t in System.Enum.GetValues(typeof(PXCMFaceData.ExpressionsData.FaceExpression)))
{
AvailableExpressions[i] = t.ToString();
i++;
}
}
#endregion
#region Public Methods
protected override bool OnRuleEnabled()
{
SenseToolkitManager.Instance.SetSenseOption(SenseOption.SenseOptionID.Face);
return true;
}
protected override void OnRuleDisabled()
{
SenseToolkitManager.Instance.UnsetSenseOption(SenseOption.SenseOptionID.Face);
}
override public string GetIconPath()
{
return @"RulesIcons/face-detected";
}
override public string GetRuleDescription()
{
return "Fires whenever a face expression is detected";
}
public override bool Process(Trigger trigger)
{
trigger.ErrorDetected = false;
if (!SenseToolkitManager.Instance.IsSenseOptionSet(SenseOption.SenseOptionID.Face))
{
trigger.ErrorDetected = true;
return false;
}
AnimationTrigger animationTrigger = trigger as AnimationTrigger;
if (animationTrigger == null)
{
trigger.ErrorDetected = true;
return false;
}
bool success = false;
if (SenseToolkitManager.Instance.Initialized && SenseToolkitManager.Instance.FaceModuleOutput != null)
{
success = UpdateFace(animationTrigger);
}
else
{
success = false;
}
return success;
}
#endregion
#region Private Methods
private bool UpdateFace(AnimationTrigger animationTrigger)
{
animationTrigger.IsAnimationDataValid = false;
// Get the closest face
PXCMFaceData.Face pxcmFace = SenseToolkitManager.Instance.FaceModuleOutput.QueryFaceByIndex(0);
if (SenseToolkitManager.Instance.FaceModuleOutput.QueryNumberOfDetectedFaces() <= 0)
{
// PXCMFaceData.QueryFaceByIndex(0) failed.
return false;
}
PXCMFaceData.LandmarksData pxcmLandmarksData = pxcmFace.QueryLandmarks();
if (pxcmLandmarksData == null)
{
// PXCMFaceData.Face.QueryLandmarks() failed.
return false;
}
Dictionary<PXCMFaceData.LandmarkType, PXCMFaceData.LandmarkPoint> landmarkPoints = new Dictionary<PXCMFaceData.LandmarkType, PXCMFaceData.LandmarkPoint>();
PXCMFaceData.LandmarkType[] landmarkTypes = new PXCMFaceData.LandmarkType[]
{
PXCMFaceData.LandmarkType.LANDMARK_NOSE_TIP,
PXCMFaceData.LandmarkType.LANDMARK_NOSE_TOP,
PXCMFaceData.LandmarkType.LANDMARK_EYEBROW_LEFT_CENTER,
PXCMFaceData.LandmarkType.LANDMARK_EYE_LEFT_CENTER,
PXCMFaceData.LandmarkType.LANDMARK_EYEBROW_RIGHT_CENTER,
PXCMFaceData.LandmarkType.LANDMARK_EYE_RIGHT_CENTER,
PXCMFaceData.LandmarkType.LANDMARK_UPPER_LIP_CENTER,
PXCMFaceData.LandmarkType.LANDMARK_LOWER_LIP_CENTER,
PXCMFaceData.LandmarkType.LANDMARK_EYELID_LEFT_TOP,
PXCMFaceData.LandmarkType.LANDMARK_EYELID_LEFT_BOTTOM,
PXCMFaceData.LandmarkType.LANDMARK_EYELID_RIGHT_TOP,
PXCMFaceData.LandmarkType.LANDMARK_EYELID_RIGHT_BOTTOM
};
foreach (PXCMFaceData.LandmarkType landmarkType in landmarkTypes)
{
PXCMFaceData.LandmarkPoint landmarkPoint = GetLandmarkPoint(pxcmLandmarksData, landmarkType);
if (landmarkPoint == null)
{
// PXCMFaceData.LandmarksData.QueryPointIndex() failed.
return false;
}
landmarkPoints.Add(landmarkType, landmarkPoint);
}
PXCMFaceData.ExpressionsData pxcmExpressionsData = pxcmFace.QueryExpressions();
if (pxcmExpressionsData == null)
{
// PXCMFaceData.Face.QueryExpressions() failed.
return false;
}
animationTrigger.IsAnimationDataValid = true;
PXCMCapture.Device.MirrorMode mirrorMode = PXCMCapture.Device.MirrorMode.MIRROR_MODE_DISABLED;
PXCMCaptureManager pxcmCaptureManager = SenseToolkitManager.Instance.SenseManager.QueryCaptureManager();
if (pxcmCaptureManager != null)
{
PXCMCapture.Device pxcmCaptureDevice = pxcmCaptureManager.QueryDevice();
if (pxcmCaptureDevice != null)
{
mirrorMode = pxcmCaptureDevice.QueryMirrorMode();
}
}
animationTrigger.Animations.Clear();
float faceHeight = landmarkPoints[PXCMFaceData.LandmarkType.LANDMARK_NOSE_TIP].image.y - landmarkPoints[PXCMFaceData.LandmarkType.LANDMARK_NOSE_TOP].image.y;
float leftEyebrowUp = GetNormalizedLandmarksDistance(landmarkPoints[PXCMFaceData.LandmarkType.LANDMARK_EYE_LEFT_CENTER].image.y, landmarkPoints[PXCMFaceData.LandmarkType.LANDMARK_EYEBROW_LEFT_CENTER].image.y, OPTIMAL_RELATIVE_FACE_HEIGHT, faceHeight, EYEBROW_UP_INITIAL_DISTANCE, OPTIMAL_EYEBROW_UP_MAX_DISTANCE, NORMALIZE_MAX_FACIAL_EXPRESSION_VALUE, true);
float rightEyebrowUp = GetNormalizedLandmarksDistance(landmarkPoints[PXCMFaceData.LandmarkType.LANDMARK_EYE_RIGHT_CENTER].image.y, landmarkPoints[PXCMFaceData.LandmarkType.LANDMARK_EYEBROW_RIGHT_CENTER].image.y, OPTIMAL_RELATIVE_FACE_HEIGHT, faceHeight, EYEBROW_UP_INITIAL_DISTANCE, OPTIMAL_EYEBROW_UP_MAX_DISTANCE, NORMALIZE_MAX_FACIAL_EXPRESSION_VALUE, true);
float leftEyeClose = GetNormalizedLandmarksDistance(landmarkPoints[PXCMFaceData.LandmarkType.LANDMARK_EYELID_LEFT_BOTTOM].image.y, landmarkPoints[PXCMFaceData.LandmarkType.LANDMARK_EYELID_LEFT_TOP].image.y, OPTIMAL_RELATIVE_FACE_HEIGHT, faceHeight, EYE_CLOSE_INITIAL_DISTANCE, OPTIMAL_EYE_CLOSE_MAX_DISTANCE, NORMALIZE_MAX_FACIAL_EXPRESSION_VALUE, true);
float rightEyeClose = GetNormalizedLandmarksDistance(landmarkPoints[PXCMFaceData.LandmarkType.LANDMARK_EYELID_RIGHT_BOTTOM].image.y, landmarkPoints[PXCMFaceData.LandmarkType.LANDMARK_EYELID_RIGHT_TOP].image.y, OPTIMAL_RELATIVE_FACE_HEIGHT, faceHeight, EYE_CLOSE_INITIAL_DISTANCE, OPTIMAL_EYE_CLOSE_MAX_DISTANCE, NORMALIZE_MAX_FACIAL_EXPRESSION_VALUE, true);
if (mirrorMode == PXCMCapture.Device.MirrorMode.MIRROR_MODE_HORIZONTAL)
{
animationTrigger.Animations.Add(PXCMFaceData.ExpressionsData.FaceExpression.EXPRESSION_BROW_RAISER_LEFT.ToString(), rightEyebrowUp);
animationTrigger.Animations.Add(PXCMFaceData.ExpressionsData.FaceExpression.EXPRESSION_BROW_RAISER_RIGHT.ToString(), leftEyebrowUp);
animationTrigger.Animations.Add(PXCMFaceData.ExpressionsData.FaceExpression.EXPRESSION_EYES_CLOSED_LEFT.ToString(), rightEyeClose);
animationTrigger.Animations.Add(PXCMFaceData.ExpressionsData.FaceExpression.EXPRESSION_EYES_CLOSED_RIGHT.ToString(), leftEyeClose);
}
else
{
animationTrigger.Animations.Add(PXCMFaceData.ExpressionsData.FaceExpression.EXPRESSION_BROW_RAISER_LEFT.ToString(), leftEyebrowUp);
animationTrigger.Animations.Add(PXCMFaceData.ExpressionsData.FaceExpression.EXPRESSION_BROW_RAISER_RIGHT.ToString(), rightEyebrowUp);
animationTrigger.Animations.Add(PXCMFaceData.ExpressionsData.FaceExpression.EXPRESSION_EYES_CLOSED_LEFT.ToString(), leftEyeClose);
animationTrigger.Animations.Add(PXCMFaceData.ExpressionsData.FaceExpression.EXPRESSION_EYES_CLOSED_RIGHT.ToString(), rightEyeClose);
}
// Instead of LANDMARK_LOWER_LIP_CENTER, we need landmark 51 (lower lip upper center)
// Instead of LANDMARK_UPPER_LIP_CENTER, we need landmark 47 (upper lip lower center)
animationTrigger.Animations.Add(PXCMFaceData.ExpressionsData.FaceExpression.EXPRESSION_MOUTH_OPEN.ToString(), GetNormalizedLandmarksDistance(landmarkPoints[PXCMFaceData.LandmarkType.LANDMARK_LOWER_LIP_CENTER].image.y, landmarkPoints[PXCMFaceData.LandmarkType.LANDMARK_UPPER_LIP_CENTER].image.y, OPTIMAL_RELATIVE_FACE_HEIGHT, faceHeight, MOUTH_OPEN_INITIAL_DISTANCE, OPTIMAL_MOUTH_OPEN_MAX_DISTANCE, NORMALIZE_MAX_FACIAL_EXPRESSION_VALUE, true));
PXCMFaceData.ExpressionsData.FaceExpressionResult pxcmFaceExpressionResult = new PXCMFaceData.ExpressionsData.FaceExpressionResult();
if (pxcmExpressionsData.QueryExpression(PXCMFaceData.ExpressionsData.FaceExpression.EXPRESSION_SMILE, out pxcmFaceExpressionResult))
{
animationTrigger.Animations.Add(PXCMFaceData.ExpressionsData.FaceExpression.EXPRESSION_SMILE.ToString(), (float)pxcmFaceExpressionResult.intensity);
}
else
{
// Error querying expression: EXPRESSION_SMILE.
return false;
}
return true;
}
private PXCMFaceData.LandmarkPoint GetLandmarkPoint(PXCMFaceData.LandmarksData pxcmLandmarksData, PXCMFaceData.LandmarkType landmarkType)
{
PXCMFaceData.LandmarkPoint landmarkPoint = null;
pxcmLandmarksData.QueryPoint(pxcmLandmarksData.QueryPointIndex(landmarkType), out landmarkPoint);
return landmarkPoint;
}
private float GetNormalizedLandmarksDistance(float x1, float x2, float optimalFaceDistance, float faceDistance, float initialDistance, float optimalMaxDistance, float maxNormalizedValue, bool clampMinMax)
{
float normalizedValue = ((((x1 - x2) * optimalFaceDistance / faceDistance) - initialDistance) / (optimalMaxDistance - initialDistance) * maxNormalizedValue);
if (clampMinMax)
{
normalizedValue = Mathf.Clamp(normalizedValue, 0, maxNormalizedValue);
}
return normalizedValue;
}
#endregion
}
}
| |
//----------------------------------------------------------------------------
// Anti-Grain Geometry - Version 2.4
// Copyright (C) 2002-2005 Maxim Shemanarev (http://www.antigrain.com)
//
// C# port by: Lars Brubaker
// larsbrubaker@gmail.com
// Copyright (C) 2007
//
// Permission to copy, use, modify, sell and distribute this software
// is granted provided this copyright notice appears in all copies.
// This software is provided "as is" without express or implied
// warranty, and with no claim as to its suitability for any purpose.
//
//----------------------------------------------------------------------------
//
// The author gratefully acknowledges the support of David Turner,
// Robert Wilhelm, and Werner Lemberg - the authors of the FreeType
// library - in producing this work. See http://www.freetype.org for details.
//
//----------------------------------------------------------------------------
// Contact: mcseem@antigrain.com
// mcseemagg@yahoo.com
// http://www.antigrain.com
//----------------------------------------------------------------------------
//
// Adaptation for 32-bit screen coordinates has been sponsored by
// Liberty Technology Systems, Inc., visit http://lib-sys.com
//
// Liberty Technology Systems, Inc. is the provider of
// PostScript and PDF technology for software developers.
//
//----------------------------------------------------------------------------
using MatterHackers.Agg.VertexSource;
using MatterHackers.VectorMath;
using filling_rule_e = MatterHackers.Agg.agg_basics.filling_rule_e;
using poly_subpixel_scale_e = MatterHackers.Agg.agg_basics.poly_subpixel_scale_e;
namespace MatterHackers.Agg
{
//==================================================rasterizer_scanline_aa
// Polygon rasterizer that is used to render filled polygons with
// high-quality Anti-Aliasing. Internally, by default, the class uses
// integer coordinates in format 24.8, i.e. 24 bits for integer part
// and 8 bits for fractional - see poly_subpixel_shift. This class can be
// used in the following way:
//
// 1. filling_rule(filling_rule_e ft) - optional.
//
// 2. gamma() - optional.
//
// 3. reset()
//
// 4. move_to(x, y) / line_to(x, y) - make the polygon. One can create
// more than one contour, but each contour must consist of at least 3
// vertices, i.e. move_to(x1, y1); line_to(x2, y2); line_to(x3, y3);
// is the absolute minimum of vertices that define a triangle.
// The algorithm does not check either the number of vertices nor
// coincidence of their coordinates, but in the worst case it just
// won't draw anything.
// The order of the vertices (clockwise or counterclockwise)
// is important when using the non-zero filling rule (fill_non_zero).
// In this case the vertex order of all the contours must be the same
// if you want your intersecting polygons to be without "holes".
// You actually can use different vertices order. If the contours do not
// intersect each other the order is not important anyway. If they do,
// contours with the same vertex order will be rendered without "holes"
// while the intersecting contours with different orders will have "holes".
//
// filling_rule() and gamma() can be called anytime before "sweeping".
//------------------------------------------------------------------------
public interface IRasterizer
{
int min_x();
int min_y();
int max_x();
int max_y();
void gamma(IGammaFunction gamma_function);
bool sweep_scanline(IScanlineCache sl);
void reset();
void add_path(IVertexSource vs);
bool rewind_scanlines();
}
public sealed class ScanlineRasterizer : IRasterizer
{
private rasterizer_cells_aa m_outline;
private VectorClipper m_VectorClipper;
private int[] m_gamma = new int[(int)aa_scale_e.aa_scale];
private agg_basics.filling_rule_e m_filling_rule;
private bool m_auto_close;
private int m_start_x;
private int m_start_y;
private status m_status;
private int m_scan_y;
public enum status
{
status_initial,
status_move_to,
status_line_to,
status_closed
};
public enum aa_scale_e
{
aa_shift = 8,
aa_scale = 1 << aa_shift,
aa_mask = aa_scale - 1,
aa_scale2 = aa_scale * 2,
aa_mask2 = aa_scale2 - 1
};
public ScanlineRasterizer()
: this(new VectorClipper())
{
}
//--------------------------------------------------------------------
public ScanlineRasterizer(VectorClipper rasterizer_sl_clip)
{
m_outline = new rasterizer_cells_aa();
m_VectorClipper = rasterizer_sl_clip;
m_filling_rule = filling_rule_e.fill_non_zero;
m_auto_close = true;
m_start_x = 0;
m_start_y = 0;
m_status = status.status_initial;
for (int i = 0; i < (int)aa_scale_e.aa_scale; i++)
{
m_gamma[i] = i;
}
}
/*
//--------------------------------------------------------------------
public rasterizer_scanline_aa(IClipper rasterizer_sl_clip, IGammaFunction gamma_function)
{
m_outline = new rasterizer_cells_aa();
m_clipper = rasterizer_sl_clip;
m_filling_rule = filling_rule_e.fill_non_zero;
m_auto_close = true;
m_start_x = 0;
m_start_y = 0;
m_status = status.status_initial;
gamma(gamma_function);
}*/
//--------------------------------------------------------------------
public void reset()
{
m_outline.reset();
m_status = status.status_initial;
}
public void reset_clipping()
{
reset();
m_VectorClipper.reset_clipping();
}
public RectangleDouble GetVectorClipBox()
{
return new RectangleDouble(
m_VectorClipper.downscale(m_VectorClipper.clipBox.Left),
m_VectorClipper.downscale(m_VectorClipper.clipBox.Bottom),
m_VectorClipper.downscale(m_VectorClipper.clipBox.Right),
m_VectorClipper.downscale(m_VectorClipper.clipBox.Top));
}
public void SetVectorClipBox(RectangleDouble clippingRect)
{
SetVectorClipBox(clippingRect.Left, clippingRect.Bottom, clippingRect.Right, clippingRect.Top);
}
public void SetVectorClipBox(double x1, double y1, double x2, double y2)
{
reset();
m_VectorClipper.clip_box(m_VectorClipper.upscale(x1), m_VectorClipper.upscale(y1),
m_VectorClipper.upscale(x2), m_VectorClipper.upscale(y2));
}
public void filling_rule(agg_basics.filling_rule_e filling_rule)
{
m_filling_rule = filling_rule;
}
public void auto_close(bool flag)
{
m_auto_close = flag;
}
//--------------------------------------------------------------------
public void gamma(IGammaFunction gamma_function)
{
for (int i = 0; i < (int)aa_scale_e.aa_scale; i++)
{
m_gamma[i] = (int)agg_basics.uround(gamma_function.GetGamma((double)(i) / (int)aa_scale_e.aa_mask) * (int)aa_scale_e.aa_mask);
}
}
/*
//--------------------------------------------------------------------
public int apply_gamma(int cover)
{
return (int)m_gamma[cover];
}
*/
//--------------------------------------------------------------------
private void move_to(int x, int y)
{
if (m_outline.sorted()) reset();
if (m_auto_close) close_polygon();
m_VectorClipper.move_to(m_start_x = m_VectorClipper.downscale(x),
m_start_y = m_VectorClipper.downscale(y));
m_status = status.status_move_to;
}
//------------------------------------------------------------------------
private void line_to(int x, int y)
{
m_VectorClipper.line_to(m_outline,
m_VectorClipper.downscale(x),
m_VectorClipper.downscale(y));
m_status = status.status_line_to;
}
//------------------------------------------------------------------------
public void move_to_d(double x, double y)
{
if (m_outline.sorted()) reset();
if (m_auto_close) close_polygon();
m_VectorClipper.move_to(m_start_x = m_VectorClipper.upscale(x),
m_start_y = m_VectorClipper.upscale(y));
m_status = status.status_move_to;
}
//------------------------------------------------------------------------
public void line_to_d(double x, double y)
{
m_VectorClipper.line_to(m_outline,
m_VectorClipper.upscale(x),
m_VectorClipper.upscale(y));
m_status = status.status_line_to;
}
public void close_polygon()
{
if (m_status == status.status_line_to)
{
m_VectorClipper.line_to(m_outline, m_start_x, m_start_y);
m_status = status.status_closed;
}
}
private void AddVertex(VertexData vertexData)
{
if (ShapePath.is_move_to(vertexData.command))
{
move_to_d(vertexData.position.X, vertexData.position.Y);
}
else
{
if (ShapePath.is_vertex(vertexData.command))
{
line_to_d(vertexData.position.X, vertexData.position.Y);
}
else
{
if (ShapePath.is_close(vertexData.command))
{
close_polygon();
}
}
}
}
//------------------------------------------------------------------------
private void edge(int x1, int y1, int x2, int y2)
{
if (m_outline.sorted()) reset();
m_VectorClipper.move_to(m_VectorClipper.downscale(x1), m_VectorClipper.downscale(y1));
m_VectorClipper.line_to(m_outline,
m_VectorClipper.downscale(x2),
m_VectorClipper.downscale(y2));
m_status = status.status_move_to;
}
//------------------------------------------------------------------------
private void edge_d(double x1, double y1, double x2, double y2)
{
if (m_outline.sorted()) reset();
m_VectorClipper.move_to(m_VectorClipper.upscale(x1), m_VectorClipper.upscale(y1));
m_VectorClipper.line_to(m_outline,
m_VectorClipper.upscale(x2),
m_VectorClipper.upscale(y2));
m_status = status.status_move_to;
}
//-------------------------------------------------------------------
public void add_path(IVertexSource vs)
{
double x = 0;
double y = 0;
ShapePath.FlagsAndCommand PathAndFlags;
vs.rewind(0);
if (m_outline.sorted())
{
reset();
}
while (!ShapePath.is_stop(PathAndFlags = vs.vertex(out x, out y)))
{
AddVertex(new VertexData(PathAndFlags, new Vector2(x, y)));
}
}
//--------------------------------------------------------------------
public int min_x()
{
return m_outline.min_x();
}
public int min_y()
{
return m_outline.min_y();
}
public int max_x()
{
return m_outline.max_x();
}
public int max_y()
{
return m_outline.max_y();
}
//--------------------------------------------------------------------
private void sort()
{
if (m_auto_close) close_polygon();
m_outline.sort_cells();
}
//------------------------------------------------------------------------
public bool rewind_scanlines()
{
if (m_auto_close) close_polygon();
m_outline.sort_cells();
if (m_outline.total_cells() == 0)
{
return false;
}
m_scan_y = m_outline.min_y();
return true;
}
//------------------------------------------------------------------------
private bool navigate_scanline(int y)
{
if (m_auto_close) close_polygon();
m_outline.sort_cells();
if (m_outline.total_cells() == 0 ||
y < m_outline.min_y() ||
y > m_outline.max_y())
{
return false;
}
m_scan_y = y;
return true;
}
//--------------------------------------------------------------------
public int calculate_alpha(int area)
{
int cover = area >> ((int)poly_subpixel_scale_e.poly_subpixel_shift * 2 + 1 - (int)aa_scale_e.aa_shift);
if (cover < 0)
{
cover = -cover;
}
if (m_filling_rule == filling_rule_e.fill_even_odd)
{
cover &= (int)aa_scale_e.aa_mask2;
if (cover > (int)aa_scale_e.aa_scale)
{
cover = (int)aa_scale_e.aa_scale2 - cover;
}
}
if (cover > (int)aa_scale_e.aa_mask)
{
cover = (int)aa_scale_e.aa_mask;
}
return (int)m_gamma[cover];
}
//--------------------------------------------------------------------
public bool sweep_scanline(IScanlineCache scanlineCache)
{
for (; ; )
{
if (m_scan_y > m_outline.max_y())
{
return false;
}
scanlineCache.ResetSpans();
int num_cells = (int)m_outline.scanline_num_cells(m_scan_y);
cell_aa[] cells;
int Offset;
m_outline.scanline_cells(m_scan_y, out cells, out Offset);
int cover = 0;
while (num_cells != 0)
{
cell_aa cur_cell = cells[Offset];
int x = cur_cell.x;
int area = cur_cell.area;
int alpha;
cover += cur_cell.cover;
//accumulate all cells with the same X
while (--num_cells != 0)
{
Offset++;
cur_cell = cells[Offset];
if (cur_cell.x != x)
{
break;
}
area += cur_cell.area;
cover += cur_cell.cover;
}
if (area != 0)
{
alpha = calculate_alpha((cover << ((int)poly_subpixel_scale_e.poly_subpixel_shift + 1)) - area);
if (alpha != 0)
{
scanlineCache.add_cell(x, alpha);
}
x++;
}
if ((num_cells != 0) && (cur_cell.x > x))
{
alpha = calculate_alpha(cover << ((int)poly_subpixel_scale_e.poly_subpixel_shift + 1));
if (alpha != 0)
{
scanlineCache.add_span(x, (cur_cell.x - x), alpha);
}
}
}
if (scanlineCache.num_spans() != 0) break;
++m_scan_y;
}
scanlineCache.finalize(m_scan_y);
++m_scan_y;
return true;
}
//--------------------------------------------------------------------
private bool hit_test(int tx, int ty)
{
if (!navigate_scanline(ty)) return false;
//scanline_hit_test sl(tx);
//sweep_scanline(sl);
//return sl.hit();
return true;
}
};
}
| |
// The MIT License (MIT)
// Copyright (c) 2013 lailongwei<lailongwei@126.com>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of
// this software and associated documentation files (the "Software"), to deal in
// the Software without restriction, including without limitation the rights to
// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
// the Software, and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
using System;
using System.Reflection;
using System.Collections.Generic;
using System.Threading;
using System.Text;
namespace llbc
{
#region ServiceRegHolderBase
/// <summary>
/// All service register holder class base class encapsulation.
/// </summary>
internal class ServiceRegHolderBase
{
}
#endregion
#region ServiceRegHolderMethod
/// <summary>
/// The service register holder method encapsulation.
/// <para>use for describe all service about register stubs.</para>
/// </summary>
internal class ServiceRegHolderMethod : ServiceRegHolderBase
{
public ServiceRegHolderMethod(MethodInfo mi)
{
methodInfo = mi;
}
/// <summary>
/// Get already hold register informations validate or not.
/// <para>If invalidate, will raise LLBCException</para>
/// </summary>
public void ValidateCheck()
{
if (isHandlerType)
{
int asHandlerCount = 0;
if (asHandler)
asHandlerCount += 1;
if (asPreHandler)
asHandlerCount += 1;
if (asUnifyPreHandler)
asHandlerCount += 1;
if (asHandlerCount > 1)
throw new LLBCException(
"Cannot be specified 'Handler/PreHandler/UnifyPreHandler' attributes at the same method '{0}'", methodInfo);
if (isExcHandlerType || isDftExcHandlerType)
throw new LLBCException(
"Cannot be specified 'Handler/PreHandler/UnifyPreHandler/PacketExcHandler' attributes at the same method '{0}'", methodInfo);
}
}
/// <summary>
/// Set all already hold register informations to given service.
/// </summary>
/// <param name="svc">service object</param>
/// <param name="obj">method's declare type object</param>
public void RegisterToService(Service svc, ref object obj)
{
_RegisterHandler(svc, PacketHandlePhase.Handle, ref obj);
_RegisterHandler(svc, PacketHandlePhase.PreHandle, ref obj);
_RegisterHandler(svc, PacketHandlePhase.UnifyPreHandle, ref obj);
_RegisterExcHandler(svc, PacketHandlePhase.Handle, false, ref obj);
_RegisterExcHandler(svc, PacketHandlePhase.PreHandle, false, ref obj);
_RegisterExcHandler(svc, PacketHandlePhase.UnifyPreHandle, false, ref obj);
_RegisterExcHandler(svc, PacketHandlePhase.Handle, true, ref obj);
_RegisterExcHandler(svc, PacketHandlePhase.PreHandle, true, ref obj);
_RegisterFrameExcHandler(svc, ref obj);
}
#region Internal implementation
private void _RegisterHandler(Service svc, PacketHandlePhase phase, ref object obj)
{
if (phase == PacketHandlePhase.Handle && asHandler)
{
_CreateObject(ref obj);
svc.Subscribe(handlerOpcode,
methodInfo.CreateDelegate(typeof(PacketHandler), obj) as PacketHandler);
}
else if (phase == PacketHandlePhase.PreHandle && asPreHandler)
{
_CreateObject(ref obj);
svc.PreSubscribe(preHandlerOpcode,
methodInfo.CreateDelegate(typeof(PacketPreHandler), obj) as PacketPreHandler);
}
else if (phase == PacketHandlePhase.UnifyPreHandle && asUnifyPreHandler)
{
_CreateObject(ref obj);
svc.UnifyPreSubscribe(
methodInfo.CreateDelegate(typeof(PacketUnifyPreHandler), obj) as PacketUnifyPreHandler);
}
}
private void _RegisterExcHandler(Service svc, PacketHandlePhase phase, bool asDefault, ref object obj)
{
if (phase == PacketHandlePhase.Handle)
{
if (!asDefault && asExcHandler)
{
_CreateObject(ref obj);
for (int i = 0; i < excHandlerOpcodes.Count; ++i)
{
svc.SetPacketExcHandler(PacketHandlePhase.Handle,
methodInfo.CreateDelegate(typeof(PacketExcHandler), obj) as PacketExcHandler, excHandlerOpcodes[i]);
}
}
else if (asDefault && asDftExcHandler)
{
_CreateObject(ref obj);
svc.SetDftPacketExcHandler(PacketHandlePhase.Handle,
methodInfo.CreateDelegate(typeof(PacketExcHandler), obj) as PacketExcHandler);
}
}
else if (phase == PacketHandlePhase.PreHandle)
{
if (!asDefault && asExcPreHandler)
{
_CreateObject(ref obj);
for (int i = 0; i < excPreHandlerOpcodes.Count; ++i)
{
svc.SetPacketExcHandler(PacketHandlePhase.PreHandle,
methodInfo.CreateDelegate(typeof(PacketExcHandler), obj) as PacketExcHandler, excPreHandlerOpcodes[i]);
}
}
else if (asDefault && asDftExcPreHandler)
{
_CreateObject(ref obj);
svc.SetDftPacketExcHandler(PacketHandlePhase.PreHandle,
methodInfo.CreateDelegate(typeof(PacketExcHandler), obj) as PacketExcHandler);
}
}
else if (phase == PacketHandlePhase.UnifyPreHandle && asExcUnifyPreHandler)
{
_CreateObject(ref obj);
svc.SetPacketExcHandler(PacketHandlePhase.UnifyPreHandle,
methodInfo.CreateDelegate(typeof(PacketExcHandler), obj) as PacketExcHandler, 0);
}
}
private void _RegisterFrameExcHandler(Service svc, ref object obj)
{
if (asFrameExcHandler)
{
_CreateObject(ref obj);
svc.SetFrameExceptionHandler(
methodInfo.CreateDelegate(typeof(FrameExceptionHandler), obj) as FrameExceptionHandler);
}
}
private void _CreateObject(ref object obj)
{
if (obj == null)
obj = Activator.CreateInstance(methodInfo.DeclaringType);
}
#endregion
public MethodInfo methodInfo;
public bool isHandlerType
{
get
{
return asHandler || asPreHandler || asUnifyPreHandler;
}
}
public bool asHandler;
public int handlerOpcode;
public bool asPreHandler;
public int preHandlerOpcode;
public bool asUnifyPreHandler;
public bool isExcHandlerType
{
get
{
return asExcHandler || asExcPreHandler || asExcUnifyPreHandler;
}
}
public bool asExcHandler;
public List<int> excHandlerOpcodes;
public bool asExcPreHandler;
public List<int> excPreHandlerOpcodes;
public bool asExcUnifyPreHandler;
public bool isDftExcHandlerType
{
get
{
return asDftExcHandler || asDftExcPreHandler;
}
}
public bool asDftExcHandler;
public bool asDftExcPreHandler;
public bool asFrameExcHandler;
}
#endregion
#region ServiceRegHolderClass
/// <summary>
/// Service register holder class encapsulation.
/// </summary>
internal class ServiceRegHolderClass : ServiceRegHolderBase
{
/// <summary>
/// Construct a service register holder class information.
/// </summary>
/// <param name="cls"></param>
public ServiceRegHolderClass(Type cls)
{
this.cls = cls;
}
/// <summary>
/// Check this register holder class is registable to specific service or not.
/// </summary>
/// <param name="svc"></param>
/// <returns></returns>
public bool IsRegistableTo(Service svc)
{
return bindTos.Contains(svc.svcName);
}
/// <summary>
/// Check all already hold register informations validate or not.
/// <para>If not validate, will raise LLBCException</para>
/// </summary>
public void ValidateCheck()
{
foreach (var holderMethod in methods.Values)
holderMethod.ValidateCheck();
}
/// <summary>
/// Register all already hold register informations to given service.
/// </summary>
/// <param name="svc">service object</param>
public void RegisterToService(Service svc)
{
object obj = null;
if (!IsRegistableTo(svc))
return;
_RegisterComp(svc, ref obj);
_RegisterCoder(svc, ref obj);
_RegisterGlobalCoder(svc, ref obj);
foreach (var holderMethod in methods.Values)
holderMethod.RegisterToService(svc, ref obj);
}
#region Internal implementation
private void _RegisterCoder(Service svc, ref object obj)
{
if (!asCoder)
return;
svc.RegisterCoder(coderOpcode, cls);
}
private void _RegisterComp(Service svc, ref object obj)
{
if (!asComp)
return;
_CreateObject(ref obj);
svc.RegisterComponent(obj as IComponent);
}
private void _RegisterGlobalCoder(Service svc, ref object obj)
{
if (!asGlobalCoder)
return;
_CreateObject(ref obj);
svc.RegisterGlobalCoder(obj as IGlobalCoder);
}
private void _CreateObject(ref object obj)
{
if (obj == null)
obj = Activator.CreateInstance(cls);
}
#endregion
public Type cls;
public bool asComp;
public bool asCoder;
public int coderOpcode;
public bool asGlobalCoder;
public List<string> bindTos = new List<string>();
public Dictionary<MethodInfo, ServiceRegHolderMethod> methods = new Dictionary<MethodInfo, ServiceRegHolderMethod>();
}
#endregion
/// <summary>
/// Register information holder collector class encapsulation.
/// </summary>
internal class RegHolderCollector
{
/// <summary>
/// Collect specified assembly's llbc library register information.
/// </summary>
/// <param name="assembly">given assembly</param>
/// <param name="async"></param>
public static void Collect(Assembly assembly, bool async = true)
{
lock (_lock)
{
if (_collectedAssemblies.Contains(assembly.FullName) ||
_collectingAssemblies.Contains(assembly.FullName))
throw new LLBCException("Could not repeat collect assembly '{0}' information", assembly.FullName);
_collectingAssemblies.Add(assembly.FullName);
if (!async)
{
_DoCollect(assembly);
return;
}
Thread thread = new Thread(
new ParameterizedThreadStart(_CollectThreadEntry));
thread.Start(assembly);
}
}
/// <summary>
/// Check given assembly is not collect or in collecting/collected.
/// </summary>
/// <param name="assemblyName"></param>
/// <returns></returns>
public static bool IsNotCollect(string assemblyName)
{
lock (_lock)
{
return !_collectingAssemblies.Contains(assemblyName) &&
!_collectedAssemblies.Contains(assemblyName);
}
}
/// <summary>
/// Check given assembly is in collecting state or not.
/// </summary>
/// <param name="assemblyName"></param>
/// <returns></returns>
public static bool IsCollecting(string assemblyName)
{
lock (_lock)
{
return _collectingAssemblies.Contains(assemblyName);
}
}
/// <summary>
/// Check given assembly is collected state or not.
/// </summary>
/// <param name="assemblyName"></param>
/// <returns></returns>
public static bool IsCollected(string assemblyName)
{
lock (_lock)
{
return _collectedAssemblies.Contains(assemblyName);
}
}
/// <summary>
/// Register all already hold register informations to service.
/// </summary>
/// <param name="svc"></param>
/// <param name="assembly"></param>
public static void RegisterToService(Service svc, Assembly assembly = null)
{
if (assembly == null)
assembly = LibIniter.loaderAssembly;
string assemblyName = assembly.FullName;
if (IsNotCollect(assemblyName))
{
Collect(assembly, false);
}
else
{
while (!IsCollected(assemblyName))
Thread.Sleep(5);
}
_RegisterToService(assemblyName, svc);
}
/// <summary>
/// Get specific coder opcode.
/// </summary>
/// <param name="coder">coder</param>
/// <returns>the coder opcode</returns>
public static int GetCoderOpcode(Type coder)
{
CoderAttribute attr =
coder.GetCustomAttribute(typeof(CoderAttribute), false) as CoderAttribute;
if (attr == null || attr.autoGen)
{
if (attr == null && coder.GetInterface(typeof(ICoder).Name) == null)
throw new LLBCException("class '{0}' could not as a coder", coder);
return StringUtil.UniqueId(coder.Name);
}
else
{
return attr.opcode;
}
}
#region Internal implementation
#region Collect about methods
private static void _CollectThreadEntry(object _)
{
Assembly assembly = _ as Assembly;
_DoCollect(assembly);
}
private static void _DoCollect(Assembly assembly)
{
ServiceRegHolderClass holderCls;
Type[] types = assembly.GetTypes();
for (int i = 0; i < types.Length; ++i)
{
Type ty = types[i];
if (!ty.IsClass)
continue;
else if ((holderCls = _CollectClass(ty)) == null)
continue;
holderCls.ValidateCheck();
lock (_lock)
{
if (!_holders.ContainsKey(assembly.FullName))
_holders.Add(assembly.FullName, new List<ServiceRegHolderClass>());
_holders[assembly.FullName].Add(holderCls);
}
}
lock (_lock)
{
_collectingAssemblies.Remove(assembly.FullName);
_collectedAssemblies.Add(assembly.FullName);
}
}
private static ServiceRegHolderClass _CollectClass(Type cls)
{
ServiceRegHolderClass holderCls = null;
_DetectClass_Comp(cls, ref holderCls); // Component detect.
_DetectClass_Coder(cls, ref holderCls); // ICoder detect.
_DetectClass_GlobalCoder(cls, ref holderCls); // Global coder detect.
// Collect all methods, only IComponent subclass can become service handlers.
if (holderCls == null || !holderCls.asComp)
return holderCls;
MethodInfo[] clsMethods = null;
_CollectMethods(cls, holderCls, ref clsMethods);
return holderCls;
}
public static void _DetectClass_Comp(Type cls, ref ServiceRegHolderClass holderCls)
{
if (cls.BaseType != typeof(IComponent))
return;
_CreateHolderClass(cls, ref holderCls);
holderCls.asComp = true;
}
private static void _DetectClass_Coder(Type cls, ref ServiceRegHolderClass holderCls)
{
if (cls.GetInterface(typeof(ICoder).Name) == null &&
cls.GetCustomAttribute(typeof(CoderAttribute), false) == null)
return;
_CreateHolderClass(cls, ref holderCls);
holderCls.asCoder = true;
holderCls.coderOpcode = GetCoderOpcode(cls);
}
private static void _DetectClass_GlobalCoder(Type cls, ref ServiceRegHolderClass holderCls)
{
if (cls.GetInterface("IGlobalCoder") == null)
return;
_CreateHolderClass(cls, ref holderCls);
holderCls.asGlobalCoder = true;
}
private static void _CreateHolderClass(Type cls, ref ServiceRegHolderClass holderCls)
{
if (holderCls != null)
return;
holderCls = new ServiceRegHolderClass(cls);
holderCls.bindTos = _GetBindTos(cls);
}
private static void _GetClassMethods(Type cls, ref MethodInfo[] clsMethods)
{
if (clsMethods == null)
clsMethods = cls.GetMethods(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.IgnoreCase);
}
private static void _CollectMethods(Type cls, ServiceRegHolderClass holderCls, ref MethodInfo[] clsMethods)
{
_GetClassMethods(cls, ref clsMethods);
for (int i = 0; i < clsMethods.Length; ++i)
{
MethodInfo clsMethod = clsMethods[i];
_DetectMethod_Handler(cls, clsMethod, PacketHandlePhase.Handle, holderCls);
_DetectMethod_Handler(cls, clsMethod, PacketHandlePhase.PreHandle, holderCls);
_DetectMethod_Handler(cls, clsMethod, PacketHandlePhase.UnifyPreHandle, holderCls);
_DetectMethod_PacketExcHandler(cls, clsMethod, holderCls);
_DetectMethod_FrameExcHandler(cls, clsMethod, holderCls);
}
}
private static void _DetectMethod_Handler(Type cls, MethodInfo mi, PacketHandlePhase phase, ServiceRegHolderClass holderCls)
{
Type attrTy = (phase == PacketHandlePhase.Handle ? typeof(HandlerAttribute) : (
phase == PacketHandlePhase.PreHandle ? typeof(PreHandlerAttribute) : typeof(UnifyPreHandlerAttribute)));
Attribute attr = mi.GetCustomAttribute(attrTy, false);
if (attr == null)
return;
if (phase == PacketHandlePhase.Handle)
{
ServiceRegHolderMethod holderMethod = _GetHolderMethod(holderCls, mi);
holderMethod.asHandler = true;
holderMethod.handlerOpcode = (attr as HandlerAttribute).opcode;
}
else if (phase == PacketHandlePhase.PreHandle)
{
ServiceRegHolderMethod holderMethod = _GetHolderMethod(holderCls, mi);
holderMethod.asPreHandler = true;
holderMethod.preHandlerOpcode = (attr as PreHandlerAttribute).opcode;
}
else
{
ServiceRegHolderMethod holderMethod = _GetHolderMethod(holderCls, mi);
holderMethod.asUnifyPreHandler = true;
}
}
private static void _DetectMethod_PacketExcHandler(Type cls, MethodInfo mi, ServiceRegHolderClass holderCls)
{
object[] attrs = mi.GetCustomAttributes(typeof(PacketExcHandlerAttribute), false);
for (int i = 0; i < attrs.Length; ++i)
{
PacketExcHandlerAttribute attr = attrs[i] as PacketExcHandlerAttribute;
ServiceRegHolderMethod holderMethod = _GetHolderMethod(holderCls, mi);
if (attr.phase == PacketHandlePhase.Handle)
{
if (attr.asDefault)
{
holderMethod.asDftExcHandler = true;
}
else
{
holderMethod.asExcHandler = true;
_MergeOpcodes(ref holderMethod.excHandlerOpcodes, attr.opcodes);
}
}
else if (attr.phase == PacketHandlePhase.PreHandle)
{
if (attr.asDefault)
{
holderMethod.asDftExcPreHandler = true;
}
else
{
holderMethod.asExcPreHandler = true;
_MergeOpcodes(ref holderMethod.excPreHandlerOpcodes, attr.opcodes);
}
}
else
{
holderMethod.asExcUnifyPreHandler = true;
}
}
}
private static void _DetectMethod_FrameExcHandler(Type cls, MethodInfo mi, ServiceRegHolderClass holderCls)
{
FrameExcHandlerAttribute attr = mi.GetCustomAttribute(
typeof(FrameExcHandlerAttribute), false) as FrameExcHandlerAttribute;
if (attr == null)
return;
ServiceRegHolderMethod holderMethod = _GetHolderMethod(holderCls, mi);
holderMethod.asFrameExcHandler = true;
}
private static ServiceRegHolderMethod _GetHolderMethod(ServiceRegHolderClass holderCls, MethodInfo mi)
{
ServiceRegHolderMethod holderMethod;
if (holderCls.methods.TryGetValue(mi, out holderMethod))
return holderMethod;
holderMethod = new ServiceRegHolderMethod(mi);
holderCls.methods.Add(mi, holderMethod);
return holderMethod;
}
private static List<string> _GetBindTos<T>(T ty) where T : ICustomAttributeProvider
{
object[] attrs = ty.GetCustomAttributes(typeof(BindToAttribute), false);
List<string> bindTos = new List<string>(attrs.Length);
for (int i = 0; i < attrs.Length; ++i)
{
List<string> oneBindTos = (attrs[i] as BindToAttribute).svcNames;
if (oneBindTos == null)
continue;
for (int j = 0; j < oneBindTos.Count; ++j)
{
if (bindTos.Contains(oneBindTos[j]))
continue;
bindTos.Add(oneBindTos[j]);
}
}
return bindTos;
}
private static void _MergeOpcodes(ref List<int> to, List<int> from)
{
if (to == null)
to = new List<int>();
for (int i = 0; i < from.Count; ++i)
{
if (to.Contains(from[i]))
continue;
to.Add(from[i]);
}
}
#endregion
#region Register about methods
private static void _RegisterToService(string assemblyName, Service svc)
{
lock (_lock)
{
List<ServiceRegHolderClass> holderClasses = null;
if (!_holders.TryGetValue(assemblyName, out holderClasses))
return;
for (int i = 0; i < holderClasses.Count; ++i)
holderClasses[i].RegisterToService(svc);
}
}
#endregion
#endregion
private static object _lock = new object();
private static HashSet<string> _collectedAssemblies = new HashSet<string>();
private static HashSet<string> _collectingAssemblies = new HashSet<string>();
private static Dictionary<string, List<ServiceRegHolderClass>> _holders = new Dictionary<string,List<ServiceRegHolderClass>>();
}
}
| |
namespace BM.AbpSample.Migrations
{
using System;
using System.Collections.Generic;
using System.Data.Entity.Infrastructure.Annotations;
using System.Data.Entity.Migrations;
public partial class AbpZero_Initial : DbMigration
{
public override void Up()
{
CreateTable(
"dbo.AbpAuditLogs",
c => new
{
Id = c.Long(nullable: false, identity: true),
TenantId = c.Int(),
UserId = c.Long(),
ServiceName = c.String(maxLength: 256),
MethodName = c.String(maxLength: 256),
Parameters = c.String(maxLength: 1024),
ExecutionTime = c.DateTime(nullable: false),
ExecutionDuration = c.Int(nullable: false),
ClientIpAddress = c.String(maxLength: 64),
ClientName = c.String(maxLength: 128),
BrowserInfo = c.String(maxLength: 256),
Exception = c.String(maxLength: 2000),
ImpersonatorUserId = c.Long(),
ImpersonatorTenantId = c.Int(),
CustomData = c.String(maxLength: 2000),
},
annotations: new Dictionary<string, object>
{
{ "DynamicFilter_AuditLog_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" },
})
.PrimaryKey(t => t.Id);
CreateTable(
"dbo.AbpBackgroundJobs",
c => new
{
Id = c.Long(nullable: false, identity: true),
JobType = c.String(nullable: false, maxLength: 512),
JobArgs = c.String(nullable: false),
TryCount = c.Short(nullable: false),
NextTryTime = c.DateTime(nullable: false),
LastTryTime = c.DateTime(),
IsAbandoned = c.Boolean(nullable: false),
Priority = c.Byte(nullable: false),
CreationTime = c.DateTime(nullable: false),
CreatorUserId = c.Long(),
})
.PrimaryKey(t => t.Id)
.Index(t => new { t.IsAbandoned, t.NextTryTime });
CreateTable(
"dbo.AbpFeatures",
c => new
{
Id = c.Long(nullable: false, identity: true),
Name = c.String(nullable: false, maxLength: 128),
Value = c.String(nullable: false, maxLength: 2000),
CreationTime = c.DateTime(nullable: false),
CreatorUserId = c.Long(),
EditionId = c.Int(),
TenantId = c.Int(),
Discriminator = c.String(nullable: false, maxLength: 128),
},
annotations: new Dictionary<string, object>
{
{ "DynamicFilter_TenantFeatureSetting_MustHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" },
})
.PrimaryKey(t => t.Id)
.ForeignKey("dbo.AbpEditions", t => t.EditionId, cascadeDelete: true)
.Index(t => t.EditionId);
CreateTable(
"dbo.AbpEditions",
c => new
{
Id = c.Int(nullable: false, identity: true),
Name = c.String(nullable: false, maxLength: 32),
DisplayName = c.String(nullable: false, maxLength: 64),
IsDeleted = c.Boolean(nullable: false),
DeleterUserId = c.Long(),
DeletionTime = c.DateTime(),
LastModificationTime = c.DateTime(),
LastModifierUserId = c.Long(),
CreationTime = c.DateTime(nullable: false),
CreatorUserId = c.Long(),
},
annotations: new Dictionary<string, object>
{
{ "DynamicFilter_Edition_SoftDelete", "EntityFramework.DynamicFilters.DynamicFilterDefinition" },
})
.PrimaryKey(t => t.Id);
CreateTable(
"dbo.AbpLanguages",
c => new
{
Id = c.Int(nullable: false, identity: true),
TenantId = c.Int(),
Name = c.String(nullable: false, maxLength: 10),
DisplayName = c.String(nullable: false, maxLength: 64),
Icon = c.String(maxLength: 128),
IsDeleted = c.Boolean(nullable: false),
DeleterUserId = c.Long(),
DeletionTime = c.DateTime(),
LastModificationTime = c.DateTime(),
LastModifierUserId = c.Long(),
CreationTime = c.DateTime(nullable: false),
CreatorUserId = c.Long(),
},
annotations: new Dictionary<string, object>
{
{ "DynamicFilter_ApplicationLanguage_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" },
{ "DynamicFilter_ApplicationLanguage_SoftDelete", "EntityFramework.DynamicFilters.DynamicFilterDefinition" },
})
.PrimaryKey(t => t.Id);
CreateTable(
"dbo.AbpLanguageTexts",
c => new
{
Id = c.Long(nullable: false, identity: true),
TenantId = c.Int(),
LanguageName = c.String(nullable: false, maxLength: 10),
Source = c.String(nullable: false, maxLength: 128),
Key = c.String(nullable: false, maxLength: 256),
Value = c.String(nullable: false),
LastModificationTime = c.DateTime(),
LastModifierUserId = c.Long(),
CreationTime = c.DateTime(nullable: false),
CreatorUserId = c.Long(),
},
annotations: new Dictionary<string, object>
{
{ "DynamicFilter_ApplicationLanguageText_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" },
})
.PrimaryKey(t => t.Id);
CreateTable(
"dbo.AbpNotifications",
c => new
{
Id = c.Guid(nullable: false),
NotificationName = c.String(nullable: false, maxLength: 96),
Data = c.String(),
DataTypeName = c.String(maxLength: 512),
EntityTypeName = c.String(maxLength: 250),
EntityTypeAssemblyQualifiedName = c.String(maxLength: 512),
EntityId = c.String(maxLength: 96),
Severity = c.Byte(nullable: false),
UserIds = c.String(),
ExcludedUserIds = c.String(),
TenantIds = c.String(),
CreationTime = c.DateTime(nullable: false),
CreatorUserId = c.Long(),
})
.PrimaryKey(t => t.Id);
CreateTable(
"dbo.AbpNotificationSubscriptions",
c => new
{
Id = c.Guid(nullable: false),
TenantId = c.Int(),
UserId = c.Long(nullable: false),
NotificationName = c.String(maxLength: 96),
EntityTypeName = c.String(maxLength: 250),
EntityTypeAssemblyQualifiedName = c.String(maxLength: 512),
EntityId = c.String(maxLength: 96),
CreationTime = c.DateTime(nullable: false),
CreatorUserId = c.Long(),
},
annotations: new Dictionary<string, object>
{
{ "DynamicFilter_NotificationSubscriptionInfo_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" },
})
.PrimaryKey(t => t.Id)
.Index(t => new { t.NotificationName, t.EntityTypeName, t.EntityId, t.UserId });
CreateTable(
"dbo.AbpOrganizationUnits",
c => new
{
Id = c.Long(nullable: false, identity: true),
TenantId = c.Int(),
ParentId = c.Long(),
Code = c.String(nullable: false, maxLength: 95),
DisplayName = c.String(nullable: false, maxLength: 128),
IsDeleted = c.Boolean(nullable: false),
DeleterUserId = c.Long(),
DeletionTime = c.DateTime(),
LastModificationTime = c.DateTime(),
LastModifierUserId = c.Long(),
CreationTime = c.DateTime(nullable: false),
CreatorUserId = c.Long(),
},
annotations: new Dictionary<string, object>
{
{ "DynamicFilter_OrganizationUnit_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" },
{ "DynamicFilter_OrganizationUnit_SoftDelete", "EntityFramework.DynamicFilters.DynamicFilterDefinition" },
})
.PrimaryKey(t => t.Id)
.ForeignKey("dbo.AbpOrganizationUnits", t => t.ParentId)
.Index(t => t.ParentId);
CreateTable(
"dbo.AbpPermissions",
c => new
{
Id = c.Long(nullable: false, identity: true),
TenantId = c.Int(),
Name = c.String(nullable: false, maxLength: 128),
IsGranted = c.Boolean(nullable: false),
CreationTime = c.DateTime(nullable: false),
CreatorUserId = c.Long(),
RoleId = c.Int(),
UserId = c.Long(),
Discriminator = c.String(nullable: false, maxLength: 128),
},
annotations: new Dictionary<string, object>
{
{ "DynamicFilter_PermissionSetting_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" },
{ "DynamicFilter_RolePermissionSetting_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" },
{ "DynamicFilter_UserPermissionSetting_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" },
})
.PrimaryKey(t => t.Id)
.ForeignKey("dbo.AbpUsers", t => t.UserId, cascadeDelete: true)
.ForeignKey("dbo.AbpRoles", t => t.RoleId, cascadeDelete: true)
.Index(t => t.RoleId)
.Index(t => t.UserId);
CreateTable(
"dbo.AbpRoles",
c => new
{
Id = c.Int(nullable: false, identity: true),
DisplayName = c.String(nullable: false, maxLength: 64),
IsStatic = c.Boolean(nullable: false),
IsDefault = c.Boolean(nullable: false),
TenantId = c.Int(),
Name = c.String(nullable: false, maxLength: 32),
IsDeleted = c.Boolean(nullable: false),
DeleterUserId = c.Long(),
DeletionTime = c.DateTime(),
LastModificationTime = c.DateTime(),
LastModifierUserId = c.Long(),
CreationTime = c.DateTime(nullable: false),
CreatorUserId = c.Long(),
},
annotations: new Dictionary<string, object>
{
{ "DynamicFilter_Role_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" },
{ "DynamicFilter_Role_SoftDelete", "EntityFramework.DynamicFilters.DynamicFilterDefinition" },
})
.PrimaryKey(t => t.Id)
.ForeignKey("dbo.AbpUsers", t => t.CreatorUserId)
.ForeignKey("dbo.AbpUsers", t => t.DeleterUserId)
.ForeignKey("dbo.AbpUsers", t => t.LastModifierUserId)
.Index(t => t.DeleterUserId)
.Index(t => t.LastModifierUserId)
.Index(t => t.CreatorUserId);
CreateTable(
"dbo.AbpUsers",
c => new
{
Id = c.Long(nullable: false, identity: true),
AuthenticationSource = c.String(maxLength: 64),
Name = c.String(nullable: false, maxLength: 32),
Surname = c.String(nullable: false, maxLength: 32),
Password = c.String(nullable: false, maxLength: 128),
IsEmailConfirmed = c.Boolean(nullable: false),
EmailConfirmationCode = c.String(maxLength: 328),
PasswordResetCode = c.String(maxLength: 328),
LockoutEndDateUtc = c.DateTime(),
AccessFailedCount = c.Int(nullable: false),
IsLockoutEnabled = c.Boolean(nullable: false),
PhoneNumber = c.String(),
IsPhoneNumberConfirmed = c.Boolean(nullable: false),
SecurityStamp = c.String(),
IsTwoFactorEnabled = c.Boolean(nullable: false),
IsActive = c.Boolean(nullable: false),
UserName = c.String(nullable: false, maxLength: 32),
TenantId = c.Int(),
EmailAddress = c.String(nullable: false, maxLength: 256),
LastLoginTime = c.DateTime(),
IsDeleted = c.Boolean(nullable: false),
DeleterUserId = c.Long(),
DeletionTime = c.DateTime(),
LastModificationTime = c.DateTime(),
LastModifierUserId = c.Long(),
CreationTime = c.DateTime(nullable: false),
CreatorUserId = c.Long(),
},
annotations: new Dictionary<string, object>
{
{ "DynamicFilter_User_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" },
{ "DynamicFilter_User_SoftDelete", "EntityFramework.DynamicFilters.DynamicFilterDefinition" },
})
.PrimaryKey(t => t.Id)
.ForeignKey("dbo.AbpUsers", t => t.CreatorUserId)
.ForeignKey("dbo.AbpUsers", t => t.DeleterUserId)
.ForeignKey("dbo.AbpUsers", t => t.LastModifierUserId)
.Index(t => t.DeleterUserId)
.Index(t => t.LastModifierUserId)
.Index(t => t.CreatorUserId);
CreateTable(
"dbo.AbpUserClaims",
c => new
{
Id = c.Long(nullable: false, identity: true),
TenantId = c.Int(),
UserId = c.Long(nullable: false),
ClaimType = c.String(),
ClaimValue = c.String(),
CreationTime = c.DateTime(nullable: false),
CreatorUserId = c.Long(),
},
annotations: new Dictionary<string, object>
{
{ "DynamicFilter_UserClaim_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" },
})
.PrimaryKey(t => t.Id)
.ForeignKey("dbo.AbpUsers", t => t.UserId, cascadeDelete: true)
.Index(t => t.UserId);
CreateTable(
"dbo.AbpUserLogins",
c => new
{
Id = c.Long(nullable: false, identity: true),
TenantId = c.Int(),
UserId = c.Long(nullable: false),
LoginProvider = c.String(nullable: false, maxLength: 128),
ProviderKey = c.String(nullable: false, maxLength: 256),
},
annotations: new Dictionary<string, object>
{
{ "DynamicFilter_UserLogin_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" },
})
.PrimaryKey(t => t.Id)
.ForeignKey("dbo.AbpUsers", t => t.UserId, cascadeDelete: true)
.Index(t => t.UserId);
CreateTable(
"dbo.AbpUserRoles",
c => new
{
Id = c.Long(nullable: false, identity: true),
TenantId = c.Int(),
UserId = c.Long(nullable: false),
RoleId = c.Int(nullable: false),
CreationTime = c.DateTime(nullable: false),
CreatorUserId = c.Long(),
},
annotations: new Dictionary<string, object>
{
{ "DynamicFilter_UserRole_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" },
})
.PrimaryKey(t => t.Id)
.ForeignKey("dbo.AbpUsers", t => t.UserId, cascadeDelete: true)
.Index(t => t.UserId);
CreateTable(
"dbo.AbpSettings",
c => new
{
Id = c.Long(nullable: false, identity: true),
TenantId = c.Int(),
UserId = c.Long(),
Name = c.String(nullable: false, maxLength: 256),
Value = c.String(maxLength: 2000),
LastModificationTime = c.DateTime(),
LastModifierUserId = c.Long(),
CreationTime = c.DateTime(nullable: false),
CreatorUserId = c.Long(),
},
annotations: new Dictionary<string, object>
{
{ "DynamicFilter_Setting_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" },
})
.PrimaryKey(t => t.Id)
.ForeignKey("dbo.AbpUsers", t => t.UserId)
.Index(t => t.UserId);
CreateTable(
"dbo.AbpTenantNotifications",
c => new
{
Id = c.Guid(nullable: false),
TenantId = c.Int(),
NotificationName = c.String(nullable: false, maxLength: 96),
Data = c.String(),
DataTypeName = c.String(maxLength: 512),
EntityTypeName = c.String(maxLength: 250),
EntityTypeAssemblyQualifiedName = c.String(maxLength: 512),
EntityId = c.String(maxLength: 96),
Severity = c.Byte(nullable: false),
CreationTime = c.DateTime(nullable: false),
CreatorUserId = c.Long(),
},
annotations: new Dictionary<string, object>
{
{ "DynamicFilter_TenantNotificationInfo_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" },
})
.PrimaryKey(t => t.Id);
CreateTable(
"dbo.AbpTenants",
c => new
{
Id = c.Int(nullable: false, identity: true),
EditionId = c.Int(),
Name = c.String(nullable: false, maxLength: 128),
IsActive = c.Boolean(nullable: false),
TenancyName = c.String(nullable: false, maxLength: 64),
ConnectionString = c.String(maxLength: 1024),
IsDeleted = c.Boolean(nullable: false),
DeleterUserId = c.Long(),
DeletionTime = c.DateTime(),
LastModificationTime = c.DateTime(),
LastModifierUserId = c.Long(),
CreationTime = c.DateTime(nullable: false),
CreatorUserId = c.Long(),
},
annotations: new Dictionary<string, object>
{
{ "DynamicFilter_Tenant_SoftDelete", "EntityFramework.DynamicFilters.DynamicFilterDefinition" },
})
.PrimaryKey(t => t.Id)
.ForeignKey("dbo.AbpUsers", t => t.CreatorUserId)
.ForeignKey("dbo.AbpUsers", t => t.DeleterUserId)
.ForeignKey("dbo.AbpEditions", t => t.EditionId)
.ForeignKey("dbo.AbpUsers", t => t.LastModifierUserId)
.Index(t => t.EditionId)
.Index(t => t.DeleterUserId)
.Index(t => t.LastModifierUserId)
.Index(t => t.CreatorUserId);
CreateTable(
"dbo.AbpUserAccounts",
c => new
{
Id = c.Long(nullable: false, identity: true),
TenantId = c.Int(),
UserId = c.Long(nullable: false),
UserLinkId = c.Long(),
UserName = c.String(),
EmailAddress = c.String(),
LastLoginTime = c.DateTime(),
IsDeleted = c.Boolean(nullable: false),
DeleterUserId = c.Long(),
DeletionTime = c.DateTime(),
LastModificationTime = c.DateTime(),
LastModifierUserId = c.Long(),
CreationTime = c.DateTime(nullable: false),
CreatorUserId = c.Long(),
},
annotations: new Dictionary<string, object>
{
{ "DynamicFilter_UserAccount_SoftDelete", "EntityFramework.DynamicFilters.DynamicFilterDefinition" },
})
.PrimaryKey(t => t.Id);
CreateTable(
"dbo.AbpUserLoginAttempts",
c => new
{
Id = c.Long(nullable: false, identity: true),
TenantId = c.Int(),
TenancyName = c.String(maxLength: 64),
UserId = c.Long(),
UserNameOrEmailAddress = c.String(maxLength: 255),
ClientIpAddress = c.String(maxLength: 64),
ClientName = c.String(maxLength: 128),
BrowserInfo = c.String(maxLength: 256),
Result = c.Byte(nullable: false),
CreationTime = c.DateTime(nullable: false),
},
annotations: new Dictionary<string, object>
{
{ "DynamicFilter_UserLoginAttempt_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" },
})
.PrimaryKey(t => t.Id)
.Index(t => new { t.UserId, t.TenantId })
.Index(t => new { t.TenancyName, t.UserNameOrEmailAddress, t.Result });
CreateTable(
"dbo.AbpUserNotifications",
c => new
{
Id = c.Guid(nullable: false),
TenantId = c.Int(),
UserId = c.Long(nullable: false),
TenantNotificationId = c.Guid(nullable: false),
State = c.Int(nullable: false),
CreationTime = c.DateTime(nullable: false),
},
annotations: new Dictionary<string, object>
{
{ "DynamicFilter_UserNotificationInfo_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" },
})
.PrimaryKey(t => t.Id)
.Index(t => new { t.UserId, t.State, t.CreationTime });
CreateTable(
"dbo.AbpUserOrganizationUnits",
c => new
{
Id = c.Long(nullable: false, identity: true),
TenantId = c.Int(),
UserId = c.Long(nullable: false),
OrganizationUnitId = c.Long(nullable: false),
CreationTime = c.DateTime(nullable: false),
CreatorUserId = c.Long(),
},
annotations: new Dictionary<string, object>
{
{ "DynamicFilter_UserOrganizationUnit_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" },
})
.PrimaryKey(t => t.Id);
CreateIndex("AbpAuditLogs", new[] { "TenantId", "ExecutionTime" });
CreateIndex("AbpAuditLogs", new[] { "UserId", "ExecutionTime" });
CreateIndex("AbpEditions", new[] { "Name" });
CreateIndex("AbpFeatures", new[] { "Discriminator", "TenantId", "Name" });
CreateIndex("AbpFeatures", new[] { "Discriminator", "EditionId", "Name" });
CreateIndex("AbpFeatures", new[] { "TenantId", "Name" });
CreateIndex("AbpLanguages", new[] { "TenantId", "Name" });
CreateIndex("AbpLanguageTexts", new[] { "TenantId", "LanguageName", "Source", "Key" });
CreateIndex("AbpOrganizationUnits", new[] { "TenantId", "ParentId" });
CreateIndex("AbpOrganizationUnits", new[] { "TenantId", "Code" });
DropIndex("AbpPermissions", new[] { "UserId" });
DropIndex("AbpPermissions", new[] { "RoleId" });
CreateIndex("AbpPermissions", new[] { "UserId", "Name" });
CreateIndex("AbpPermissions", new[] { "RoleId", "Name" });
CreateIndex("AbpRoles", new[] { "TenantId", "Name" });
CreateIndex("AbpRoles", new[] { "IsDeleted", "TenantId", "Name" });
DropIndex("AbpSettings", new[] { "UserId" });
CreateIndex("AbpSettings", new[] { "TenantId", "Name" });
CreateIndex("AbpSettings", new[] { "UserId", "Name" });
CreateIndex("AbpTenants", new[] { "TenancyName" });
CreateIndex("AbpTenants", new[] { "IsDeleted", "TenancyName" });
DropIndex("AbpUserLogins", new[] { "UserId" });
CreateIndex("AbpUserLogins", new[] { "UserId", "LoginProvider" });
CreateIndex("AbpUserOrganizationUnits", new[] { "TenantId", "UserId" });
CreateIndex("AbpUserOrganizationUnits", new[] { "TenantId", "OrganizationUnitId" });
CreateIndex("AbpUserOrganizationUnits", new[] { "UserId" });
CreateIndex("AbpUserOrganizationUnits", new[] { "OrganizationUnitId" });
DropIndex("AbpUserRoles", new[] { "UserId" });
CreateIndex("AbpUserRoles", new[] { "UserId", "RoleId" });
CreateIndex("AbpUserRoles", new[] { "RoleId" });
CreateIndex("AbpUsers", new[] { "TenantId", "UserName" });
CreateIndex("AbpUsers", new[] { "TenantId", "EmailAddress" });
CreateIndex("AbpUsers", new[] { "IsDeleted", "TenantId", "UserName" });
CreateIndex("AbpUsers", new[] { "IsDeleted", "TenantId", "EmailAddress" });
}
public override void Down()
{
DropIndex("AbpAuditLogs", new[] { "TenantId", "ExecutionTime" });
DropIndex("AbpAuditLogs", new[] { "UserId", "ExecutionTime" });
DropIndex("AbpEditions", new[] { "Name" });
DropIndex("AbpFeatures", new[] { "Discriminator", "TenantId", "Name" });
DropIndex("AbpFeatures", new[] { "Discriminator", "EditionId", "Name" });
DropIndex("AbpFeatures", new[] { "TenantId", "Name" });
DropIndex("AbpLanguages", new[] { "TenantId", "Name" });
DropIndex("AbpLanguageTexts", new[] { "TenantId", "LanguageName", "Source", "Key" });
DropIndex("AbpOrganizationUnits", new[] { "TenantId", "ParentId" });
DropIndex("AbpOrganizationUnits", new[] { "TenantId", "Code" });
CreateIndex("AbpPermissions", new[] { "UserId" });
CreateIndex("AbpPermissions", new[] { "RoleId" });
DropIndex("AbpPermissions", new[] { "UserId", "Name" });
DropIndex("AbpPermissions", new[] { "RoleId", "Name" });
DropIndex("AbpRoles", new[] { "TenantId", "Name" });
DropIndex("AbpRoles", new[] { "IsDeleted", "TenantId", "Name" });
CreateIndex("AbpSettings", new[] { "UserId" });
DropIndex("AbpSettings", new[] { "TenantId", "Name" });
DropIndex("AbpSettings", new[] { "UserId", "Name" });
DropIndex("AbpTenants", new[] { "TenancyName" });
DropIndex("AbpTenants", new[] { "IsDeleted", "TenancyName" });
CreateIndex("AbpUserLogins", new[] { "UserId" });
DropIndex("AbpUserLogins", new[] { "UserId", "LoginProvider" });
DropIndex("AbpUserOrganizationUnits", new[] { "TenantId", "UserId" });
DropIndex("AbpUserOrganizationUnits", new[] { "TenantId", "OrganizationUnitId" });
DropIndex("AbpUserOrganizationUnits", new[] { "UserId" });
DropIndex("AbpUserOrganizationUnits", new[] { "OrganizationUnitId" });
CreateIndex("AbpUserRoles", new[] { "UserId" });
DropIndex("AbpUserRoles", new[] { "UserId", "RoleId" });
DropIndex("AbpUserRoles", new[] { "RoleId" });
DropIndex("AbpUsers", new[] { "TenantId", "UserName" });
DropIndex("AbpUsers", new[] { "TenantId", "EmailAddress" });
DropIndex("AbpUsers", new[] { "IsDeleted", "TenantId", "UserName" });
DropIndex("AbpUsers", new[] { "IsDeleted", "TenantId", "EmailAddress" });
DropForeignKey("dbo.AbpTenants", "LastModifierUserId", "dbo.AbpUsers");
DropForeignKey("dbo.AbpTenants", "EditionId", "dbo.AbpEditions");
DropForeignKey("dbo.AbpTenants", "DeleterUserId", "dbo.AbpUsers");
DropForeignKey("dbo.AbpTenants", "CreatorUserId", "dbo.AbpUsers");
DropForeignKey("dbo.AbpPermissions", "RoleId", "dbo.AbpRoles");
DropForeignKey("dbo.AbpRoles", "LastModifierUserId", "dbo.AbpUsers");
DropForeignKey("dbo.AbpRoles", "DeleterUserId", "dbo.AbpUsers");
DropForeignKey("dbo.AbpRoles", "CreatorUserId", "dbo.AbpUsers");
DropForeignKey("dbo.AbpSettings", "UserId", "dbo.AbpUsers");
DropForeignKey("dbo.AbpUserRoles", "UserId", "dbo.AbpUsers");
DropForeignKey("dbo.AbpPermissions", "UserId", "dbo.AbpUsers");
DropForeignKey("dbo.AbpUserLogins", "UserId", "dbo.AbpUsers");
DropForeignKey("dbo.AbpUsers", "LastModifierUserId", "dbo.AbpUsers");
DropForeignKey("dbo.AbpUsers", "DeleterUserId", "dbo.AbpUsers");
DropForeignKey("dbo.AbpUsers", "CreatorUserId", "dbo.AbpUsers");
DropForeignKey("dbo.AbpUserClaims", "UserId", "dbo.AbpUsers");
DropForeignKey("dbo.AbpOrganizationUnits", "ParentId", "dbo.AbpOrganizationUnits");
DropForeignKey("dbo.AbpFeatures", "EditionId", "dbo.AbpEditions");
DropIndex("dbo.AbpUserNotifications", new[] { "UserId", "State", "CreationTime" });
DropIndex("dbo.AbpUserLoginAttempts", new[] { "TenancyName", "UserNameOrEmailAddress", "Result" });
DropIndex("dbo.AbpUserLoginAttempts", new[] { "UserId", "TenantId" });
DropIndex("dbo.AbpTenants", new[] { "CreatorUserId" });
DropIndex("dbo.AbpTenants", new[] { "LastModifierUserId" });
DropIndex("dbo.AbpTenants", new[] { "DeleterUserId" });
DropIndex("dbo.AbpTenants", new[] { "EditionId" });
DropIndex("dbo.AbpSettings", new[] { "UserId" });
DropIndex("dbo.AbpUserRoles", new[] { "UserId" });
DropIndex("dbo.AbpUserLogins", new[] { "UserId" });
DropIndex("dbo.AbpUserClaims", new[] { "UserId" });
DropIndex("dbo.AbpUsers", new[] { "CreatorUserId" });
DropIndex("dbo.AbpUsers", new[] { "LastModifierUserId" });
DropIndex("dbo.AbpUsers", new[] { "DeleterUserId" });
DropIndex("dbo.AbpRoles", new[] { "CreatorUserId" });
DropIndex("dbo.AbpRoles", new[] { "LastModifierUserId" });
DropIndex("dbo.AbpRoles", new[] { "DeleterUserId" });
DropIndex("dbo.AbpPermissions", new[] { "UserId" });
DropIndex("dbo.AbpPermissions", new[] { "RoleId" });
DropIndex("dbo.AbpOrganizationUnits", new[] { "ParentId" });
DropIndex("dbo.AbpNotificationSubscriptions", new[] { "NotificationName", "EntityTypeName", "EntityId", "UserId" });
DropIndex("dbo.AbpFeatures", new[] { "EditionId" });
DropIndex("dbo.AbpBackgroundJobs", new[] { "IsAbandoned", "NextTryTime" });
DropTable("dbo.AbpUserOrganizationUnits",
removedAnnotations: new Dictionary<string, object>
{
{ "DynamicFilter_UserOrganizationUnit_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" },
});
DropTable("dbo.AbpUserNotifications",
removedAnnotations: new Dictionary<string, object>
{
{ "DynamicFilter_UserNotificationInfo_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" },
});
DropTable("dbo.AbpUserLoginAttempts",
removedAnnotations: new Dictionary<string, object>
{
{ "DynamicFilter_UserLoginAttempt_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" },
});
DropTable("dbo.AbpUserAccounts",
removedAnnotations: new Dictionary<string, object>
{
{ "DynamicFilter_UserAccount_SoftDelete", "EntityFramework.DynamicFilters.DynamicFilterDefinition" },
});
DropTable("dbo.AbpTenants",
removedAnnotations: new Dictionary<string, object>
{
{ "DynamicFilter_Tenant_SoftDelete", "EntityFramework.DynamicFilters.DynamicFilterDefinition" },
});
DropTable("dbo.AbpTenantNotifications",
removedAnnotations: new Dictionary<string, object>
{
{ "DynamicFilter_TenantNotificationInfo_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" },
});
DropTable("dbo.AbpSettings",
removedAnnotations: new Dictionary<string, object>
{
{ "DynamicFilter_Setting_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" },
});
DropTable("dbo.AbpUserRoles",
removedAnnotations: new Dictionary<string, object>
{
{ "DynamicFilter_UserRole_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" },
});
DropTable("dbo.AbpUserLogins",
removedAnnotations: new Dictionary<string, object>
{
{ "DynamicFilter_UserLogin_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" },
});
DropTable("dbo.AbpUserClaims",
removedAnnotations: new Dictionary<string, object>
{
{ "DynamicFilter_UserClaim_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" },
});
DropTable("dbo.AbpUsers",
removedAnnotations: new Dictionary<string, object>
{
{ "DynamicFilter_User_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" },
{ "DynamicFilter_User_SoftDelete", "EntityFramework.DynamicFilters.DynamicFilterDefinition" },
});
DropTable("dbo.AbpRoles",
removedAnnotations: new Dictionary<string, object>
{
{ "DynamicFilter_Role_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" },
{ "DynamicFilter_Role_SoftDelete", "EntityFramework.DynamicFilters.DynamicFilterDefinition" },
});
DropTable("dbo.AbpPermissions",
removedAnnotations: new Dictionary<string, object>
{
{ "DynamicFilter_PermissionSetting_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" },
{ "DynamicFilter_RolePermissionSetting_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" },
{ "DynamicFilter_UserPermissionSetting_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" },
});
DropTable("dbo.AbpOrganizationUnits",
removedAnnotations: new Dictionary<string, object>
{
{ "DynamicFilter_OrganizationUnit_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" },
{ "DynamicFilter_OrganizationUnit_SoftDelete", "EntityFramework.DynamicFilters.DynamicFilterDefinition" },
});
DropTable("dbo.AbpNotificationSubscriptions",
removedAnnotations: new Dictionary<string, object>
{
{ "DynamicFilter_NotificationSubscriptionInfo_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" },
});
DropTable("dbo.AbpNotifications");
DropTable("dbo.AbpLanguageTexts",
removedAnnotations: new Dictionary<string, object>
{
{ "DynamicFilter_ApplicationLanguageText_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" },
});
DropTable("dbo.AbpLanguages",
removedAnnotations: new Dictionary<string, object>
{
{ "DynamicFilter_ApplicationLanguage_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" },
{ "DynamicFilter_ApplicationLanguage_SoftDelete", "EntityFramework.DynamicFilters.DynamicFilterDefinition" },
});
DropTable("dbo.AbpEditions",
removedAnnotations: new Dictionary<string, object>
{
{ "DynamicFilter_Edition_SoftDelete", "EntityFramework.DynamicFilters.DynamicFilterDefinition" },
});
DropTable("dbo.AbpFeatures",
removedAnnotations: new Dictionary<string, object>
{
{ "DynamicFilter_TenantFeatureSetting_MustHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" },
});
DropTable("dbo.AbpBackgroundJobs");
DropTable("dbo.AbpAuditLogs",
removedAnnotations: new Dictionary<string, object>
{
{ "DynamicFilter_AuditLog_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" },
});
}
}
}
| |
// 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 gaxgrpc = Google.Api.Gax.Grpc;
using grpccore = Grpc.Core;
using moq = Moq;
using st = System.Threading;
using stt = System.Threading.Tasks;
using NUnit.Framework;
using Google.Ads.GoogleAds.V9.Services;
namespace Google.Ads.GoogleAds.Tests.V9.Services
{
/// <summary>Generated unit tests.</summary>
public sealed class GeneratedCustomerClientServiceClientTest
{
[Category("Autogenerated")][Test]
public void GetCustomerClientRequestObject()
{
moq::Mock<CustomerClientService.CustomerClientServiceClient> mockGrpcClient = new moq::Mock<CustomerClientService.CustomerClientServiceClient>(moq::MockBehavior.Strict);
GetCustomerClientRequest request = new GetCustomerClientRequest
{
ResourceNameAsCustomerClientName = gagvr::CustomerClientName.FromCustomerClientCustomer("[CUSTOMER_ID]", "[CLIENT_CUSTOMER_ID]"),
};
gagvr::CustomerClient expectedResponse = new gagvr::CustomerClient
{
ResourceNameAsCustomerClientName = gagvr::CustomerClientName.FromCustomerClientCustomer("[CUSTOMER_ID]", "[CLIENT_CUSTOMER_ID]"),
ClientCustomerAsCustomerName = gagvr::CustomerName.FromCustomer("[CUSTOMER_ID]"),
Hidden = true,
Level = -1767934904342353463L,
TimeZone = "time_zone73f23b20",
TestAccount = true,
Manager = false,
DescriptiveName = "descriptive_nameee37a0bc",
CurrencyCode = "currency_code7f81e352",
Id = -6774108720365892680L,
AppliedLabelsAsLabelNames =
{
gagvr::LabelName.FromCustomerLabel("[CUSTOMER_ID]", "[LABEL_ID]"),
},
};
mockGrpcClient.Setup(x => x.GetCustomerClient(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
CustomerClientServiceClient client = new CustomerClientServiceClientImpl(mockGrpcClient.Object, null);
gagvr::CustomerClient response = client.GetCustomerClient(request);
Assert.AreEqual(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[Category("Autogenerated")][Test]
public async stt::Task GetCustomerClientRequestObjectAsync()
{
moq::Mock<CustomerClientService.CustomerClientServiceClient> mockGrpcClient = new moq::Mock<CustomerClientService.CustomerClientServiceClient>(moq::MockBehavior.Strict);
GetCustomerClientRequest request = new GetCustomerClientRequest
{
ResourceNameAsCustomerClientName = gagvr::CustomerClientName.FromCustomerClientCustomer("[CUSTOMER_ID]", "[CLIENT_CUSTOMER_ID]"),
};
gagvr::CustomerClient expectedResponse = new gagvr::CustomerClient
{
ResourceNameAsCustomerClientName = gagvr::CustomerClientName.FromCustomerClientCustomer("[CUSTOMER_ID]", "[CLIENT_CUSTOMER_ID]"),
ClientCustomerAsCustomerName = gagvr::CustomerName.FromCustomer("[CUSTOMER_ID]"),
Hidden = true,
Level = -1767934904342353463L,
TimeZone = "time_zone73f23b20",
TestAccount = true,
Manager = false,
DescriptiveName = "descriptive_nameee37a0bc",
CurrencyCode = "currency_code7f81e352",
Id = -6774108720365892680L,
AppliedLabelsAsLabelNames =
{
gagvr::LabelName.FromCustomerLabel("[CUSTOMER_ID]", "[LABEL_ID]"),
},
};
mockGrpcClient.Setup(x => x.GetCustomerClientAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<gagvr::CustomerClient>(stt::Task.FromResult(expectedResponse), null, null, null, null));
CustomerClientServiceClient client = new CustomerClientServiceClientImpl(mockGrpcClient.Object, null);
gagvr::CustomerClient responseCallSettings = await client.GetCustomerClientAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
Assert.AreEqual(expectedResponse, responseCallSettings);
gagvr::CustomerClient responseCancellationToken = await client.GetCustomerClientAsync(request, st::CancellationToken.None);
Assert.AreEqual(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[Category("Autogenerated")][Test]
public void GetCustomerClient()
{
moq::Mock<CustomerClientService.CustomerClientServiceClient> mockGrpcClient = new moq::Mock<CustomerClientService.CustomerClientServiceClient>(moq::MockBehavior.Strict);
GetCustomerClientRequest request = new GetCustomerClientRequest
{
ResourceNameAsCustomerClientName = gagvr::CustomerClientName.FromCustomerClientCustomer("[CUSTOMER_ID]", "[CLIENT_CUSTOMER_ID]"),
};
gagvr::CustomerClient expectedResponse = new gagvr::CustomerClient
{
ResourceNameAsCustomerClientName = gagvr::CustomerClientName.FromCustomerClientCustomer("[CUSTOMER_ID]", "[CLIENT_CUSTOMER_ID]"),
ClientCustomerAsCustomerName = gagvr::CustomerName.FromCustomer("[CUSTOMER_ID]"),
Hidden = true,
Level = -1767934904342353463L,
TimeZone = "time_zone73f23b20",
TestAccount = true,
Manager = false,
DescriptiveName = "descriptive_nameee37a0bc",
CurrencyCode = "currency_code7f81e352",
Id = -6774108720365892680L,
AppliedLabelsAsLabelNames =
{
gagvr::LabelName.FromCustomerLabel("[CUSTOMER_ID]", "[LABEL_ID]"),
},
};
mockGrpcClient.Setup(x => x.GetCustomerClient(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
CustomerClientServiceClient client = new CustomerClientServiceClientImpl(mockGrpcClient.Object, null);
gagvr::CustomerClient response = client.GetCustomerClient(request.ResourceName);
Assert.AreEqual(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[Category("Autogenerated")][Test]
public async stt::Task GetCustomerClientAsync()
{
moq::Mock<CustomerClientService.CustomerClientServiceClient> mockGrpcClient = new moq::Mock<CustomerClientService.CustomerClientServiceClient>(moq::MockBehavior.Strict);
GetCustomerClientRequest request = new GetCustomerClientRequest
{
ResourceNameAsCustomerClientName = gagvr::CustomerClientName.FromCustomerClientCustomer("[CUSTOMER_ID]", "[CLIENT_CUSTOMER_ID]"),
};
gagvr::CustomerClient expectedResponse = new gagvr::CustomerClient
{
ResourceNameAsCustomerClientName = gagvr::CustomerClientName.FromCustomerClientCustomer("[CUSTOMER_ID]", "[CLIENT_CUSTOMER_ID]"),
ClientCustomerAsCustomerName = gagvr::CustomerName.FromCustomer("[CUSTOMER_ID]"),
Hidden = true,
Level = -1767934904342353463L,
TimeZone = "time_zone73f23b20",
TestAccount = true,
Manager = false,
DescriptiveName = "descriptive_nameee37a0bc",
CurrencyCode = "currency_code7f81e352",
Id = -6774108720365892680L,
AppliedLabelsAsLabelNames =
{
gagvr::LabelName.FromCustomerLabel("[CUSTOMER_ID]", "[LABEL_ID]"),
},
};
mockGrpcClient.Setup(x => x.GetCustomerClientAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<gagvr::CustomerClient>(stt::Task.FromResult(expectedResponse), null, null, null, null));
CustomerClientServiceClient client = new CustomerClientServiceClientImpl(mockGrpcClient.Object, null);
gagvr::CustomerClient responseCallSettings = await client.GetCustomerClientAsync(request.ResourceName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
Assert.AreEqual(expectedResponse, responseCallSettings);
gagvr::CustomerClient responseCancellationToken = await client.GetCustomerClientAsync(request.ResourceName, st::CancellationToken.None);
Assert.AreEqual(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[Category("Autogenerated")][Test]
public void GetCustomerClientResourceNames()
{
moq::Mock<CustomerClientService.CustomerClientServiceClient> mockGrpcClient = new moq::Mock<CustomerClientService.CustomerClientServiceClient>(moq::MockBehavior.Strict);
GetCustomerClientRequest request = new GetCustomerClientRequest
{
ResourceNameAsCustomerClientName = gagvr::CustomerClientName.FromCustomerClientCustomer("[CUSTOMER_ID]", "[CLIENT_CUSTOMER_ID]"),
};
gagvr::CustomerClient expectedResponse = new gagvr::CustomerClient
{
ResourceNameAsCustomerClientName = gagvr::CustomerClientName.FromCustomerClientCustomer("[CUSTOMER_ID]", "[CLIENT_CUSTOMER_ID]"),
ClientCustomerAsCustomerName = gagvr::CustomerName.FromCustomer("[CUSTOMER_ID]"),
Hidden = true,
Level = -1767934904342353463L,
TimeZone = "time_zone73f23b20",
TestAccount = true,
Manager = false,
DescriptiveName = "descriptive_nameee37a0bc",
CurrencyCode = "currency_code7f81e352",
Id = -6774108720365892680L,
AppliedLabelsAsLabelNames =
{
gagvr::LabelName.FromCustomerLabel("[CUSTOMER_ID]", "[LABEL_ID]"),
},
};
mockGrpcClient.Setup(x => x.GetCustomerClient(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
CustomerClientServiceClient client = new CustomerClientServiceClientImpl(mockGrpcClient.Object, null);
gagvr::CustomerClient response = client.GetCustomerClient(request.ResourceNameAsCustomerClientName);
Assert.AreEqual(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[Category("Autogenerated")][Test]
public async stt::Task GetCustomerClientResourceNamesAsync()
{
moq::Mock<CustomerClientService.CustomerClientServiceClient> mockGrpcClient = new moq::Mock<CustomerClientService.CustomerClientServiceClient>(moq::MockBehavior.Strict);
GetCustomerClientRequest request = new GetCustomerClientRequest
{
ResourceNameAsCustomerClientName = gagvr::CustomerClientName.FromCustomerClientCustomer("[CUSTOMER_ID]", "[CLIENT_CUSTOMER_ID]"),
};
gagvr::CustomerClient expectedResponse = new gagvr::CustomerClient
{
ResourceNameAsCustomerClientName = gagvr::CustomerClientName.FromCustomerClientCustomer("[CUSTOMER_ID]", "[CLIENT_CUSTOMER_ID]"),
ClientCustomerAsCustomerName = gagvr::CustomerName.FromCustomer("[CUSTOMER_ID]"),
Hidden = true,
Level = -1767934904342353463L,
TimeZone = "time_zone73f23b20",
TestAccount = true,
Manager = false,
DescriptiveName = "descriptive_nameee37a0bc",
CurrencyCode = "currency_code7f81e352",
Id = -6774108720365892680L,
AppliedLabelsAsLabelNames =
{
gagvr::LabelName.FromCustomerLabel("[CUSTOMER_ID]", "[LABEL_ID]"),
},
};
mockGrpcClient.Setup(x => x.GetCustomerClientAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<gagvr::CustomerClient>(stt::Task.FromResult(expectedResponse), null, null, null, null));
CustomerClientServiceClient client = new CustomerClientServiceClientImpl(mockGrpcClient.Object, null);
gagvr::CustomerClient responseCallSettings = await client.GetCustomerClientAsync(request.ResourceNameAsCustomerClientName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
Assert.AreEqual(expectedResponse, responseCallSettings);
gagvr::CustomerClient responseCancellationToken = await client.GetCustomerClientAsync(request.ResourceNameAsCustomerClientName, st::CancellationToken.None);
Assert.AreEqual(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
}
}
| |
namespace Rhino.Etl.Core.Operations
{
using System;
using System.Collections.Generic;
using Enumerables;
/// <summary>
/// Perform a join between two sources. The left part of the join is optional and if not specified it will use the current pipeline as input.
/// </summary>
public abstract class JoinOperation : AbstractOperation
{
private readonly PartialProcessOperation left = new PartialProcessOperation();
private readonly PartialProcessOperation right = new PartialProcessOperation();
private JoinType jointype;
private string[] leftColumns;
private string[] rightColumns;
private Dictionary<Row, object> rightRowsWereMatched = new Dictionary<Row, object>();
private Dictionary<ObjectArrayKeys, List<Row>> rightRowsByJoinKey = new Dictionary<ObjectArrayKeys, List<Row>>();
private bool leftRegistered = false;
/// <summary>
/// Sets the right part of the join
/// </summary>
/// <value>The right.</value>
public JoinOperation Right(IOperation value)
{
right.Register(value);
return this;
}
/// <summary>
/// Sets the left part of the join
/// </summary>
/// <value>The left.</value>
public JoinOperation Left(IOperation value)
{
left.Register(value);
leftRegistered = true;
return this;
}
/// <summary>
/// Executes this operation
/// </summary>
/// <param name="rows">Rows in pipeline. These are only used if a left part of the join was not specified.</param>
/// <returns></returns>
public override IEnumerable<Row> Execute(IEnumerable<Row> rows)
{
PrepareForJoin();
IEnumerable<Row> rightEnumerable = GetRightEnumerable();
IEnumerable<Row> execute = left.Execute(leftRegistered ? null : rows);
foreach (Row leftRow in new EventRaisingEnumerator(left, execute))
{
ObjectArrayKeys key = leftRow.CreateKey(leftColumns);
List<Row> rightRows;
if (this.rightRowsByJoinKey.TryGetValue(key, out rightRows))
{
foreach (Row rightRow in rightRows)
{
rightRowsWereMatched[rightRow] = null;
yield return MergeRows(leftRow, rightRow);
}
}
else if ((jointype & JoinType.Left) != 0)
{
Row emptyRow = new Row();
yield return MergeRows(leftRow, emptyRow);
}
else
{
LeftOrphanRow(leftRow);
}
}
foreach (Row rightRow in rightEnumerable)
{
if (rightRowsWereMatched.ContainsKey(rightRow))
continue;
Row emptyRow = new Row();
if ((jointype & JoinType.Right) != 0)
yield return MergeRows(emptyRow, rightRow);
else
RightOrphanRow(rightRow);
}
}
private void PrepareForJoin()
{
Initialize();
Guard.Against(left == null, "Left branch of a join cannot be null");
Guard.Against(right == null, "Right branch of a join cannot be null");
SetupJoinConditions();
Guard.Against(leftColumns == null, "You must setup the left columns");
Guard.Against(rightColumns == null, "You must setup the right columns");
}
private IEnumerable<Row> GetRightEnumerable()
{
IEnumerable<Row> rightEnumerable = new CachingEnumerable<Row>(
new EventRaisingEnumerator(right, right.Execute(null))
);
foreach (Row row in rightEnumerable)
{
ObjectArrayKeys key = row.CreateKey(rightColumns);
List<Row> rowsForKey;
if (this.rightRowsByJoinKey.TryGetValue(key, out rowsForKey) == false)
{
this.rightRowsByJoinKey[key] = rowsForKey = new List<Row>();
}
rowsForKey.Add(row);
}
return rightEnumerable;
}
/// <summary>
/// Called when a row on the right side was filtered by
/// the join condition, allow a derived class to perform
/// logic associated to that, such as logging
/// </summary>
protected virtual void RightOrphanRow(Row row)
{
}
/// <summary>
/// Called when a row on the left side was filtered by
/// the join condition, allow a derived class to perform
/// logic associated to that, such as logging
/// </summary>
/// <param name="row">The row.</param>
protected virtual void LeftOrphanRow(Row row)
{
}
/// <summary>
/// Merges the two rows into a single row
/// </summary>
/// <param name="leftRow">The left row.</param>
/// <param name="rightRow">The right row.</param>
/// <returns></returns>
protected abstract Row MergeRows(Row leftRow, Row rightRow);
/// <summary>
/// Initializes this instance.
/// </summary>
protected virtual void Initialize()
{
}
/// <summary>
/// Setups the join conditions.
/// </summary>
protected abstract void SetupJoinConditions();
/// <summary>
/// Create an inner join
/// </summary>
/// <value>The inner.</value>
protected JoinBuilder InnerJoin
{
get { return new JoinBuilder(this, JoinType.Inner); }
}
/// <summary>
/// Create a left outer join
/// </summary>
/// <value>The inner.</value>
protected JoinBuilder LeftJoin
{
get { return new JoinBuilder(this, JoinType.Left); }
}
/// <summary>
/// Create a right outer join
/// </summary>
/// <value>The inner.</value>
protected JoinBuilder RightJoin
{
get { return new JoinBuilder(this, JoinType.Right); }
}
/// <summary>
/// Create a full outer join
/// </summary>
/// <value>The inner.</value>
protected JoinBuilder FullOuterJoin
{
get { return new JoinBuilder(this, JoinType.Full); }
}
/// <summary>
/// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
/// </summary>
public override void Dispose()
{
left.Dispose();
right.Dispose();
}
/// <summary>
/// Initializes this instance
/// </summary>
/// <param name="pipelineExecuter">The current pipeline executer.</param>
public override void PrepareForExecution(IPipelineExecuter pipelineExecuter)
{
left.PrepareForExecution(pipelineExecuter);
right.PrepareForExecution(pipelineExecuter);
}
/// <summary>
/// Gets all errors that occured when running this operation
/// </summary>
/// <returns></returns>
public override IEnumerable<Exception> GetAllErrors()
{
foreach (Exception error in left.GetAllErrors())
{
yield return error;
}
foreach (Exception error in right.GetAllErrors())
{
yield return error;
}
}
/// <summary>
/// Fluent interface to create joins
/// </summary>
public class JoinBuilder
{
private readonly JoinOperation parent;
/// <summary>
/// Initializes a new instance of the <see cref="JoinBuilder"/> class.
/// </summary>
/// <param name="parent">The parent.</param>
/// <param name="joinType">Type of the join.</param>
public JoinBuilder(JoinOperation parent, JoinType joinType)
{
this.parent = parent;
parent.jointype = joinType;
}
/// <summary>
/// Setup the left side of the join
/// </summary>
/// <param name="columns">The columns.</param>
/// <returns></returns>
public JoinBuilder Left(params string[] columns)
{
parent.leftColumns = columns;
return this;
}
/// <summary>
/// Setup the right side of the join
/// </summary>
/// <param name="columns">The columns.</param>
/// <returns></returns>
public JoinBuilder Right(params string[] columns)
{
parent.rightColumns = columns;
return this;
}
}
/// <summary>
/// Occurs when a row is processed.
/// </summary>
public override event Action<IOperation, Row> OnRowProcessed
{
add
{
foreach (IOperation operation in new[] { left, right })
operation.OnRowProcessed += value;
base.OnRowProcessed += value;
}
remove
{
foreach (IOperation operation in new[] { left, right })
operation.OnRowProcessed -= value;
base.OnRowProcessed -= value;
}
}
/// <summary>
/// Occurs when all the rows has finished processing.
/// </summary>
public override event Action<IOperation> OnFinishedProcessing
{
add
{
foreach (IOperation operation in new[] { left, right })
operation.OnFinishedProcessing += value;
base.OnFinishedProcessing += value;
}
remove
{
foreach (IOperation operation in new[] { left, right })
operation.OnFinishedProcessing -= value;
base.OnFinishedProcessing -= 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.Diagnostics.Contracts;
namespace System.Globalization
{
////////////////////////////////////////////////////////////////////////////
//
// Notes about JapaneseLunisolarCalendar
//
////////////////////////////////////////////////////////////////////////////
/*
** Calendar support range:
** Calendar Minimum Maximum
** ========== ========== ==========
** Gregorian 1960/01/28 2050/01/22
** JapaneseLunisolar 1960/01/01 2049/12/29
*/
public class JapaneseLunisolarCalendar : EastAsianLunisolarCalendar
{
//
// The era value for the current era.
//
public const int JapaneseEra = 1;
internal GregorianCalendarHelper helper;
internal const int MIN_LUNISOLAR_YEAR = 1960;
internal const int MAX_LUNISOLAR_YEAR = 2049;
internal const int MIN_GREGORIAN_YEAR = 1960;
internal const int MIN_GREGORIAN_MONTH = 1;
internal const int MIN_GREGORIAN_DAY = 28;
internal const int MAX_GREGORIAN_YEAR = 2050;
internal const int MAX_GREGORIAN_MONTH = 1;
internal const int MAX_GREGORIAN_DAY = 22;
internal static DateTime minDate = new DateTime(MIN_GREGORIAN_YEAR, MIN_GREGORIAN_MONTH, MIN_GREGORIAN_DAY);
internal static DateTime maxDate = new DateTime((new DateTime(MAX_GREGORIAN_YEAR, MAX_GREGORIAN_MONTH, MAX_GREGORIAN_DAY, 23, 59, 59, 999)).Ticks + 9999);
public override DateTime MinSupportedDateTime
{
get
{
return (minDate);
}
}
public override DateTime MaxSupportedDateTime
{
get
{
return (maxDate);
}
}
protected override int DaysInYearBeforeMinSupportedYear
{
get
{
// 1959 from ChineseLunisolarCalendar
return 354;
}
}
static readonly int[,] yinfo =
{
/*Y LM Lmon Lday DaysPerMonth D1 D2 D3 D4 D5 D6 D7 D8 D9 D10 D11 D12 D13 #Days
1960 */
{ 6 , 1 , 28 , 44368 },/* 30 29 30 29 30 30 29 30 29 30 29 30 29 384
1961 */{ 0 , 2 , 15 , 43856 },/* 30 29 30 29 30 29 30 30 29 30 29 30 0 355
1962 */{ 0 , 2 , 5 , 19808 },/* 29 30 29 29 30 30 29 30 29 30 30 29 0 354
1963 */{ 4 , 1 , 25 , 42352 },/* 30 29 30 29 29 30 29 30 29 30 30 30 29 384
1964 */{ 0 , 2 , 13 , 42352 },/* 30 29 30 29 29 30 29 30 29 30 30 30 0 355
1965 */{ 0 , 2 , 2 , 21104 },/* 29 30 29 30 29 29 30 29 29 30 30 30 0 354
1966 */{ 3 , 1 , 22 , 26928 },/* 29 30 30 29 30 29 29 30 29 29 30 30 29 383
1967 */{ 0 , 2 , 9 , 55632 },/* 30 30 29 30 30 29 29 30 29 30 29 30 0 355
1968 */{ 7 , 1 , 30 , 27304 },/* 29 30 30 29 30 29 30 29 30 29 30 29 30 384
1969 */{ 0 , 2 , 17 , 22176 },/* 29 30 29 30 29 30 30 29 30 29 30 29 0 354
1970 */{ 0 , 2 , 6 , 39632 },/* 30 29 29 30 30 29 30 29 30 30 29 30 0 355
1971 */{ 5 , 1 , 27 , 19176 },/* 29 30 29 29 30 29 30 29 30 30 30 29 30 384
1972 */{ 0 , 2 , 15 , 19168 },/* 29 30 29 29 30 29 30 29 30 30 30 29 0 354
1973 */{ 0 , 2 , 3 , 42208 },/* 30 29 30 29 29 30 29 29 30 30 30 29 0 354
1974 */{ 4 , 1 , 23 , 53864 },/* 30 30 29 30 29 29 30 29 29 30 30 29 30 384
1975 */{ 0 , 2 , 11 , 53840 },/* 30 30 29 30 29 29 30 29 29 30 29 30 0 354
1976 */{ 8 , 1 , 31 , 54600 },/* 30 30 29 30 29 30 29 30 29 30 29 29 30 384
1977 */{ 0 , 2 , 18 , 46400 },/* 30 29 30 30 29 30 29 30 29 30 29 29 0 354
1978 */{ 0 , 2 , 7 , 54944 },/* 30 30 29 30 29 30 30 29 30 29 30 29 0 355
1979 */{ 6 , 1 , 28 , 38608 },/* 30 29 29 30 29 30 30 29 30 30 29 30 29 384
1980 */{ 0 , 2 , 16 , 38320 },/* 30 29 29 30 29 30 29 30 30 29 30 30 0 355
1981 */{ 0 , 2 , 5 , 18864 },/* 29 30 29 29 30 29 29 30 30 29 30 30 0 354
1982 */{ 4 , 1 , 25 , 42200 },/* 30 29 30 29 29 30 29 29 30 30 29 30 30 384
1983 */{ 0 , 2 , 13 , 42160 },/* 30 29 30 29 29 30 29 29 30 29 30 30 0 354
1984 */{ 10 , 2 , 2 , 45656 },/* 30 29 30 30 29 29 30 29 29 30 29 30 30 384
1985 */{ 0 , 2 , 20 , 27216 },/* 29 30 30 29 30 29 30 29 29 30 29 30 0 354
1986 */{ 0 , 2 , 9 , 27968 },/* 29 30 30 29 30 30 29 30 29 30 29 29 0 354
1987 */{ 6 , 1 , 29 , 46504 },/* 30 29 30 30 29 30 29 30 30 29 30 29 30 385
1988 */{ 0 , 2 , 18 , 11104 },/* 29 29 30 29 30 29 30 30 29 30 30 29 0 354
1989 */{ 0 , 2 , 6 , 38320 },/* 30 29 29 30 29 30 29 30 30 29 30 30 0 355
1990 */{ 5 , 1 , 27 , 18872 },/* 29 30 29 29 30 29 29 30 30 29 30 30 30 384
1991 */{ 0 , 2 , 15 , 18800 },/* 29 30 29 29 30 29 29 30 29 30 30 30 0 354
1992 */{ 0 , 2 , 4 , 25776 },/* 29 30 30 29 29 30 29 29 30 29 30 30 0 354
1993 */{ 3 , 1 , 23 , 27216 },/* 29 30 30 29 30 29 30 29 29 30 29 30 29 383
1994 */{ 0 , 2 , 10 , 59984 },/* 30 30 30 29 30 29 30 29 29 30 29 30 0 355
1995 */{ 8 , 1 , 31 , 27976 },/* 29 30 30 29 30 30 29 30 29 30 29 29 30 384
1996 */{ 0 , 2 , 19 , 23248 },/* 29 30 29 30 30 29 30 29 30 30 29 30 0 355
1997 */{ 0 , 2 , 8 , 11104 },/* 29 29 30 29 30 29 30 30 29 30 30 29 0 354
1998 */{ 5 , 1 , 28 , 37744 },/* 30 29 29 30 29 29 30 30 29 30 30 30 29 384
1999 */{ 0 , 2 , 16 , 37600 },/* 30 29 29 30 29 29 30 29 30 30 30 29 0 354
2000 */{ 0 , 2 , 5 , 51552 },/* 30 30 29 29 30 29 29 30 29 30 30 29 0 354
2001 */{ 4 , 1 , 24 , 58536 },/* 30 30 30 29 29 30 29 29 30 29 30 29 30 384
2002 */{ 0 , 2 , 12 , 54432 },/* 30 30 29 30 29 30 29 29 30 29 30 29 0 354
2003 */{ 0 , 2 , 1 , 55888 },/* 30 30 29 30 30 29 30 29 29 30 29 30 0 355
2004 */{ 2 , 1 , 22 , 23208 },/* 29 30 29 30 30 29 30 29 30 29 30 29 30 384
2005 */{ 0 , 2 , 9 , 22208 },/* 29 30 29 30 29 30 30 29 30 30 29 29 0 354
2006 */{ 7 , 1 , 29 , 43736 },/* 30 29 30 29 30 29 30 29 30 30 29 30 30 385
2007 */{ 0 , 2 , 18 , 9680 },/* 29 29 30 29 29 30 29 30 30 30 29 30 0 354
2008 */{ 0 , 2 , 7 , 37584 },/* 30 29 29 30 29 29 30 29 30 30 29 30 0 354
2009 */{ 5 , 1 , 26 , 51544 },/* 30 30 29 29 30 29 29 30 29 30 29 30 30 384
2010 */{ 0 , 2 , 14 , 43344 },/* 30 29 30 29 30 29 29 30 29 30 29 30 0 354
2011 */{ 0 , 2 , 3 , 46240 },/* 30 29 30 30 29 30 29 29 30 29 30 29 0 354
2012 */{ 3 , 1 , 23 , 47696 },/* 30 29 30 30 30 29 30 29 29 30 29 30 29 384
2013 */{ 0 , 2 , 10 , 46416 },/* 30 29 30 30 29 30 29 30 29 30 29 30 0 355
2014 */{ 9 , 1 , 31 , 21928 },/* 29 30 29 30 29 30 29 30 30 29 30 29 30 384
2015 */{ 0 , 2 , 19 , 19360 },/* 29 30 29 29 30 29 30 30 30 29 30 29 0 354
2016 */{ 0 , 2 , 8 , 42416 },/* 30 29 30 29 29 30 29 30 30 29 30 30 0 355
2017 */{ 5 , 1 , 28 , 21176 },/* 29 30 29 30 29 29 30 29 30 29 30 30 30 384
2018 */{ 0 , 2 , 16 , 21168 },/* 29 30 29 30 29 29 30 29 30 29 30 30 0 354
2019 */{ 0 , 2 , 5 , 43344 },/* 30 29 30 29 30 29 29 30 29 30 29 30 0 354
2020 */{ 4 , 1 , 25 , 46248 },/* 30 29 30 30 29 30 29 29 30 29 30 29 30 384
2021 */{ 0 , 2 , 12 , 27296 },/* 29 30 30 29 30 29 30 29 30 29 30 29 0 354
2022 */{ 0 , 2 , 1 , 44368 },/* 30 29 30 29 30 30 29 30 29 30 29 30 0 355
2023 */{ 2 , 1 , 22 , 21928 },/* 29 30 29 30 29 30 29 30 30 29 30 29 30 384
2024 */{ 0 , 2 , 10 , 19296 },/* 29 30 29 29 30 29 30 30 29 30 30 29 0 354
2025 */{ 6 , 1 , 29 , 42352 },/* 30 29 30 29 29 30 29 30 29 30 30 30 29 384
2026 */{ 0 , 2 , 17 , 42352 },/* 30 29 30 29 29 30 29 30 29 30 30 30 0 355
2027 */{ 0 , 2 , 7 , 21104 },/* 29 30 29 30 29 29 30 29 29 30 30 30 0 354
2028 */{ 5 , 1 , 27 , 26928 },/* 29 30 30 29 30 29 29 30 29 29 30 30 29 383
2029 */{ 0 , 2 , 13 , 55600 },/* 30 30 29 30 30 29 29 30 29 29 30 30 0 355
2030 */{ 0 , 2 , 3 , 23200 },/* 29 30 29 30 30 29 30 29 30 29 30 29 0 354
2031 */{ 3 , 1 , 23 , 43856 },/* 30 29 30 29 30 29 30 30 29 30 29 30 29 384
2032 */{ 0 , 2 , 11 , 38608 },/* 30 29 29 30 29 30 30 29 30 30 29 30 0 355
2033 */{ 11 , 1 , 31 , 19176 },/* 29 30 29 29 30 29 30 29 30 30 30 29 30 384
2034 */{ 0 , 2 , 19 , 19168 },/* 29 30 29 29 30 29 30 29 30 30 30 29 0 354
2035 */{ 0 , 2 , 8 , 42192 },/* 30 29 30 29 29 30 29 29 30 30 29 30 0 354
2036 */{ 6 , 1 , 28 , 53864 },/* 30 30 29 30 29 29 30 29 29 30 30 29 30 384
2037 */{ 0 , 2 , 15 , 53840 },/* 30 30 29 30 29 29 30 29 29 30 29 30 0 354
2038 */{ 0 , 2 , 4 , 54560 },/* 30 30 29 30 29 30 29 30 29 29 30 29 0 354
2039 */{ 5 , 1 , 24 , 55968 },/* 30 30 29 30 30 29 30 29 30 29 30 29 29 384
2040 */{ 0 , 2 , 12 , 46752 },/* 30 29 30 30 29 30 30 29 30 29 30 29 0 355
2041 */{ 0 , 2 , 1 , 38608 },/* 30 29 29 30 29 30 30 29 30 30 29 30 0 355
2042 */{ 2 , 1 , 22 , 19160 },/* 29 30 29 29 30 29 30 29 30 30 29 30 30 384
2043 */{ 0 , 2 , 10 , 18864 },/* 29 30 29 29 30 29 29 30 30 29 30 30 0 354
2044 */{ 7 , 1 , 30 , 42168 },/* 30 29 30 29 29 30 29 29 30 29 30 30 30 384
2045 */{ 0 , 2 , 17 , 42160 },/* 30 29 30 29 29 30 29 29 30 29 30 30 0 354
2046 */{ 0 , 2 , 6 , 45648 },/* 30 29 30 30 29 29 30 29 29 30 29 30 0 354
2047 */{ 5 , 1 , 26 , 46376 },/* 30 29 30 30 29 30 29 30 29 29 30 29 30 384
2048 */{ 0 , 2 , 14 , 27968 },/* 29 30 30 29 30 30 29 30 29 30 29 29 0 354
2049 */{ 0 , 2 , 2 , 44448 },/* 30 29 30 29 30 30 29 30 30 29 30 29 0 355
*/ };
internal override int MinCalendarYear
{
get
{
return (MIN_LUNISOLAR_YEAR);
}
}
internal override int MaxCalendarYear
{
get
{
return (MAX_LUNISOLAR_YEAR);
}
}
internal override DateTime MinDate
{
get
{
return (minDate);
}
}
internal override DateTime MaxDate
{
get
{
return (maxDate);
}
}
internal override EraInfo[] CalEraInfo
{
get
{
return (JapaneseCalendar.GetEraInfo());
}
}
internal override int GetYearInfo(int LunarYear, int Index)
{
if ((LunarYear < MIN_LUNISOLAR_YEAR) || (LunarYear > MAX_LUNISOLAR_YEAR))
{
throw new ArgumentOutOfRangeException(
"year",
String.Format(
CultureInfo.CurrentCulture,
SR.ArgumentOutOfRange_Range,
MIN_LUNISOLAR_YEAR,
MAX_LUNISOLAR_YEAR));
}
Contract.EndContractBlock();
return yinfo[LunarYear - MIN_LUNISOLAR_YEAR, Index];
}
internal override int GetYear(int year, DateTime time)
{
return helper.GetYear(year, time);
}
internal override int GetGregorianYear(int year, int era)
{
return helper.GetGregorianYear(year, era);
}
// Trim off the eras that are before our date range
private static EraInfo[] TrimEras(EraInfo[] baseEras)
{
EraInfo[] newEras = new EraInfo[baseEras.Length];
int newIndex = 0;
// Eras have most recent first, so start with that
for (int i = 0; i < baseEras.Length; i++)
{
// If this one's minimum year is bigger than our maximum year
// then we can't use it.
if (baseEras[i].yearOffset + baseEras[i].minEraYear >= MAX_LUNISOLAR_YEAR)
{
// skip this one.
continue;
}
// If this one's maximum era is less than our minimum era
// then we've gotten too low in the era #s, so we're done
if (baseEras[i].yearOffset + baseEras[i].maxEraYear < MIN_LUNISOLAR_YEAR)
{
break;
}
// Wasn't too large or too small, can use this one
newEras[newIndex] = baseEras[i];
newIndex++;
}
// If we didn't copy any then something was wrong, just return base
if (newIndex == 0) return baseEras;
// Resize the output array
Array.Resize(ref newEras, newIndex);
return newEras;
}
// Construct an instance of JapaneseLunisolar calendar.
public JapaneseLunisolarCalendar()
{
helper = new GregorianCalendarHelper(this, TrimEras(JapaneseCalendar.GetEraInfo()));
}
public override int GetEra(DateTime time)
{
return (helper.GetEra(time));
}
internal override CalendarId BaseCalendarID
{
get
{
return (CalendarId.JAPAN);
}
}
internal override CalendarId ID
{
get
{
return (CalendarId.JAPANESELUNISOLAR);
}
}
public override int[] Eras
{
get
{
return (helper.Eras);
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading;
using Sitecore.Diagnostics.Base;
using JetBrains.Annotations;
namespace SIM.FileSystem
{
using Sitecore.Diagnostics.Logging;
using SIM.Extensions;
public class DirectoryProvider
{
#region Fields
private FileSystem FileSystem { get; }
#endregion
#region Constructors
public DirectoryProvider(FileSystem fileSystem)
{
FileSystem = fileSystem;
}
#endregion
#region Public methods
public virtual void AssertExists([NotNull] string path, [CanBeNull] string message = null)
{
Assert.ArgumentNotNullOrEmpty(path, nameof(path));
Assert.IsTrue(Directory.Exists(path), message.EmptyToNull() ?? $"The {Environment.ExpandEnvironmentVariables(path)} folder does not exist, but is expected to be");
}
public virtual string Combine(DirectoryInfo one, string two)
{
return Path.Combine(one.FullName, two);
}
public virtual void Copy(string path, string newPath, bool recursive)
{
// Get the subdirectories for the specified directory.
DirectoryInfo dir = new DirectoryInfo(path);
DirectoryInfo[] dirs = dir.GetDirectories();
if (!dir.Exists)
{
throw new DirectoryNotFoundException("Source directory does not exist or could not be found: " + path);
}
// If the destination directory doesn't exist, create it.
if (!Exists(newPath))
{
CreateDirectory(newPath);
}
// Get the files in the directory and copy them to the new location.
foreach (var file in FileSystem.Directory.GetFiles(path))
{
var temppath = Path.Combine(newPath, Path.GetFileName(file));
FileSystem.File.Copy(file, temppath);
}
// If copying subdirectories, copy them and their contents to new location.
if (recursive)
{
foreach (DirectoryInfo subdir in dirs)
{
var temppath = Path.Combine(newPath, subdir.Name);
Copy(subdir.FullName, temppath, recursive);
}
}
}
public virtual DirectoryInfo CreateDirectory(string path)
{
return Directory.CreateDirectory(path);
}
public virtual void Delete([NotNull] string path)
{
// TODO: Refactor this to edit attributes only on problem files and folders
Assert.ArgumentNotNull(path, nameof(path));
Log.Info($"Deleting file or folder: {path}");
if (!string.IsNullOrEmpty(path))
{
if (Directory.Exists(path))
{
var directoryInfo = new DirectoryInfo(path)
{
Attributes = FileAttributes.Normal
};
try
{
directoryInfo.Delete(true);
// Hook to make async delete operation synchronus
for (int i = 0; Directory.Exists(path) && i < 10; ++i)
{
Thread.Sleep(100);
}
}
catch (Exception ex)
{
Log.Warn(ex, $"Failed to delete {path} folder, altering attributes and trying again");
Thread.Sleep(100);
foreach (var fileSystemInfo in directoryInfo.GetFileSystemInfos("*", SearchOption.AllDirectories))
{
fileSystemInfo.Attributes = FileAttributes.Normal;
}
directoryInfo.Delete(true);
}
}
}
}
public virtual void DeleteContents(string path)
{
foreach (var file in GetFiles(path))
{
FileSystem.File.Delete(file);
}
foreach (var directory in GetDirectories(path))
{
Delete(directory);
}
}
public virtual void DeleteIfExists([CanBeNull] string path, string ignore = null)
{
if (!string.IsNullOrEmpty(path) && Directory.Exists(path))
{
if (ignore == null)
{
Delete(path);
}
else
{
Assert.IsTrue(!ignore.Contains('\\') && !ignore.Contains('/'), "Multi-level ignore is not supported for deleting");
foreach (var directory in Directory.GetDirectories(path))
{
var directoryName = new DirectoryInfo(directory).Name;
if (!directoryName.EqualsIgnoreCase(ignore))
{
Delete(directory);
}
}
foreach (var file in Directory.GetFiles(path))
{
Delete(file);
}
}
}
}
public void DeleteTempFolders()
{
using (new ProfileSection("Delete temp folders", this))
{
var tempFoldersCacheFilePath = Path.Combine(ApplicationManager.TempFolder, "tempFolders.txt");
if (!System.IO.File.Exists(tempFoldersCacheFilePath))
{
ProfileSection.Result("Skipped");
return;
}
var paths = System.IO.File.ReadAllLines(tempFoldersCacheFilePath);
foreach (var path in paths)
{
DeleteIfExists(path);
}
System.IO.File.Delete(tempFoldersCacheFilePath);
ProfileSection.Result("Done");
}
}
[NotNull]
public virtual string Ensure([NotNull] string folder)
{
Assert.ArgumentNotNullOrEmpty(folder, nameof(folder));
if (!Directory.Exists(folder))
{
Log.Info($"Creating folder {folder}");
Directory.CreateDirectory(folder);
}
return folder;
}
public virtual bool Exists(string path)
{
return Directory.Exists(path);
}
[NotNull]
public virtual string FindCommonParent([NotNull] string path1, [NotNull] string path2)
{
Assert.ArgumentNotNull(path1, nameof(path1));
Assert.ArgumentNotNull(path2, nameof(path2));
var path = string.Empty;
using (new ProfileSection("Find common parent", this))
{
ProfileSection.Argument("path1", path1);
ProfileSection.Argument("path2", path2);
string[] arr1 = path1.Replace('/', '\\').Split('\\');
string[] arr2 = path2.Replace('/', '\\').Split('\\');
var minLen = Math.Min(arr1.Length, arr2.Length);
for (int i = 0; i < minLen; ++i)
{
var word1 = arr1[i];
var word2 = arr2[i];
if (!word1.EqualsIgnoreCase(word2))
{
break;
}
path += word1 + '\\';
}
path = path.TrimEnd('\\');
ProfileSection.Result(path);
}
return path;
}
[NotNull]
public virtual string GenerateTempFolderPath([NotNull] string folder)
{
Assert.ArgumentNotNull(folder, nameof(folder));
return Path.Combine(folder, Guid.NewGuid().ToString());
}
[CanBeNull]
public virtual IEnumerable<string> GetAncestors([NotNull] string path)
{
Assert.ArgumentNotNull(path, nameof(path));
DirectoryInfo dir = new DirectoryInfo(path);
while (dir != null && dir.Exists)
{
path = dir.FullName;
yield return path;
dir = dir.Parent;
}
}
public virtual string[] GetDirectories(string path)
{
return Directory.GetDirectories(path);
}
public virtual string[] GetDirectories(string path, string pattern)
{
return Directory.GetDirectories(path, pattern);
}
public virtual string GetDirectoryRoot(string path)
{
return Directory.GetDirectoryRoot(path);
}
public virtual int GetDistance(string directory1, string directory2)
{
Assert.ArgumentNotNullOrEmpty(directory1, nameof(directory1));
Assert.ArgumentNotNullOrEmpty(directory2, nameof(directory2));
using (new ProfileSection("Get distance", this))
{
ProfileSection.Argument("directory1", directory1);
ProfileSection.Argument("directory2", directory2);
directory1 = directory1.TrimEnd('\\');
directory2 = directory2.TrimEnd('\\');
var root1 = GetPathRoot(directory1);
var root2 = GetPathRoot(directory2);
Assert.IsTrue(HaveSameRoot(root1, root2), $"The '{directory1}' and '{directory2}' paths has different roots so unaplicable");
var arr1 = directory1.Split('\\');
var arr2 = directory2.Split('\\');
var len = Math.Min(arr1.Length, arr2.Length) - 1;
var common = 0;
for (int i = 0; i < len && arr1[i].EqualsIgnoreCase(arr2[i]); ++i)
{
common++;
}
var distance = arr1.Length + arr2.Length - 2 * common - 2;
return ProfileSection.Result(distance);
}
}
public string[] GetFileSystemEntries(string path)
{
return Directory.GetFileSystemEntries(path);
}
public virtual string[] GetFiles(string path, string filter, SearchOption searchMode)
{
return Directory.GetFiles(path, filter, searchMode);
}
public virtual string[] GetFiles(string path, string filter)
{
return Directory.GetFiles(path, filter);
}
public virtual string[] GetFiles(string path)
{
return Directory.GetFiles(path);
}
public virtual DirectoryInfo GetParent(string path)
{
return Directory.GetParent(path);
}
public virtual string GetPathRoot(string path)
{
if (path.Length == 2 && path[1] == ':')
{
path += "\\";
}
return Path.GetPathRoot(path);
}
public TempFolder GetTempFolder(string path = null, bool? rooted = null)
{
return new TempFolder(FileSystem, path, rooted);
}
public string GetVirtualPath(string databaseFilePath)
{
return databaseFilePath.Substring("C:\\".Length);
}
public virtual bool HasDriveLetter([NotNull] string folder)
{
Assert.ArgumentNotNull(folder, nameof(folder));
return folder.Length >= 3 && char.IsLetter(folder[0]) && folder[1] == ':' && folder[2] == '\\';
}
public virtual bool HaveSameRoot(string directory1, string directory2)
{
using (new ProfileSection("Have same root", this))
{
ProfileSection.Argument("directory1", directory1);
ProfileSection.Argument("directory2", directory2);
var root1 = GetPathRoot(directory1);
var root2 = GetPathRoot(directory2);
bool haveSameRoot = root2.EqualsIgnoreCase(root1);
return ProfileSection.Result(haveSameRoot);
}
}
[NotNull]
public virtual string MapPath([NotNull] string virtualPath, [NotNull] string rootPath)
{
Assert.ArgumentNotNull(virtualPath, nameof(virtualPath));
Assert.ArgumentNotNullOrEmpty(rootPath, nameof(rootPath));
if (HasDriveLetter(virtualPath))
{
return virtualPath;
}
return Path.Combine(rootPath, virtualPath.TrimStart("/", "~/"));
}
public virtual void Move(string path, string newPath)
{
Directory.Move(path, newPath);
}
public string RegisterTempFolder(string tempFolderPath)
{
var tempFoldersCacheFilePath = Path.Combine(ApplicationManager.TempFolder, "tempFolders.txt");
System.IO.File.AppendAllLines(tempFoldersCacheFilePath, new[]
{
tempFolderPath
});
return tempFolderPath;
}
public virtual void TryDelete([NotNull] string path)
{
Assert.ArgumentNotNull(path, nameof(path));
try
{
Delete(path);
}
catch (Exception ex)
{
Log.Warn(ex, $"Cannot delete the {path} file. {ex.Message}");
}
}
#endregion
#region Protected methods
[NotNull]
protected virtual DirectoryInfo GetChild([NotNull] DirectoryInfo extracted, [NotNull] string folderName)
{
Assert.ArgumentNotNull(extracted, nameof(extracted));
Assert.ArgumentNotNullOrEmpty(folderName, nameof(folderName));
DirectoryInfo[] websites = extracted.GetDirectories(folderName);
Assert.IsTrue(websites != null && websites.Length > 0,
$"Can't find extracted {folderName} folder here: {extracted.FullName}");
return websites[0];
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Threading;
using ImageResizer;
using Nop.Core;
using Nop.Core.Data;
using Nop.Core.Domain.Catalog;
using Nop.Core.Domain.Media;
using Nop.Data;
using Nop.Services.Configuration;
using Nop.Services.Events;
using Nop.Services.Logging;
using Nop.Services.Seo;
namespace Nop.Services.Media
{
/// <summary>
/// Picture service
/// </summary>
public partial class PictureService : IPictureService
{
#region Const
private const int MULTIPLE_THUMB_DIRECTORIES_LENGTH = 3;
#endregion
#region Fields
private readonly IRepository<Picture> _pictureRepository;
private readonly IRepository<ProductPicture> _productPictureRepository;
private readonly ISettingService _settingService;
private readonly IWebHelper _webHelper;
private readonly ILogger _logger;
private readonly IDbContext _dbContext;
private readonly IEventPublisher _eventPublisher;
private readonly MediaSettings _mediaSettings;
private readonly IDataProvider _dataProvider;
#endregion
#region Ctor
/// <summary>
/// Ctor
/// </summary>
/// <param name="pictureRepository">Picture repository</param>
/// <param name="productPictureRepository">Product picture repository</param>
/// <param name="settingService">Setting service</param>
/// <param name="webHelper">Web helper</param>
/// <param name="logger">Logger</param>
/// <param name="dbContext">Database context</param>
/// <param name="eventPublisher">Event publisher</param>
/// <param name="mediaSettings">Media settings</param>
/// <param name="dataProvider">Data provider</param>
public PictureService(IRepository<Picture> pictureRepository,
IRepository<ProductPicture> productPictureRepository,
ISettingService settingService,
IWebHelper webHelper,
ILogger logger,
IDbContext dbContext,
IEventPublisher eventPublisher,
MediaSettings mediaSettings,
IDataProvider dataProvider)
{
this._pictureRepository = pictureRepository;
this._productPictureRepository = productPictureRepository;
this._settingService = settingService;
this._webHelper = webHelper;
this._logger = logger;
this._dbContext = dbContext;
this._eventPublisher = eventPublisher;
this._mediaSettings = mediaSettings;
this._dataProvider = dataProvider;
}
#endregion
#region Utilities
/// <summary>
/// Calculates picture dimensions whilst maintaining aspect
/// </summary>
/// <param name="originalSize">The original picture size</param>
/// <param name="targetSize">The target picture size (longest side)</param>
/// <param name="resizeType">Resize type</param>
/// <param name="ensureSizePositive">A value indicatingh whether we should ensure that size values are positive</param>
/// <returns></returns>
protected virtual Size CalculateDimensions(Size originalSize, int targetSize,
ResizeType resizeType = ResizeType.LongestSide, bool ensureSizePositive = true)
{
float width, height;
switch (resizeType)
{
case ResizeType.LongestSide:
if (originalSize.Height > originalSize.Width)
{
// portrait
width = originalSize.Width * (targetSize / (float)originalSize.Height);
height = targetSize;
}
else
{
// landscape or square
width = targetSize;
height = originalSize.Height * (targetSize / (float) originalSize.Width);
}
break;
case ResizeType.Width:
width = targetSize;
height = originalSize.Height * (targetSize / (float)originalSize.Width);
break;
case ResizeType.Height:
width = originalSize.Width * (targetSize / (float)originalSize.Height);
height = targetSize;
break;
default:
throw new Exception("Not supported ResizeType");
}
if (ensureSizePositive)
{
if (width < 1)
width = 1;
if (height < 1)
height = 1;
}
//we invoke Math.Round to ensure that no white background is rendered - http://www.nopcommerce.com/boards/t/40616/image-resizing-bug.aspx
return new Size((int)Math.Round(width), (int)Math.Round(height));
}
/// <summary>
/// Returns the file extension from mime type.
/// </summary>
/// <param name="mimeType">Mime type</param>
/// <returns>File extension</returns>
protected virtual string GetFileExtensionFromMimeType(string mimeType)
{
if (mimeType == null)
return null;
//also see System.Web.MimeMapping for more mime types
string[] parts = mimeType.Split('/');
string lastPart = parts[parts.Length - 1];
switch (lastPart)
{
case "pjpeg":
lastPart = "jpg";
break;
case "x-png":
lastPart = "png";
break;
case "x-icon":
lastPart = "ico";
break;
}
return lastPart;
}
/// <summary>
/// Loads a picture from file
/// </summary>
/// <param name="pictureId">Picture identifier</param>
/// <param name="mimeType">MIME type</param>
/// <returns>Picture binary</returns>
protected virtual byte[] LoadPictureFromFile(int pictureId, string mimeType)
{
string lastPart = GetFileExtensionFromMimeType(mimeType);
string fileName = string.Format("{0}_0.{1}", pictureId.ToString("0000000"), lastPart);
var filePath = GetPictureLocalPath(fileName);
if (!File.Exists(filePath))
return new byte[0];
return File.ReadAllBytes(filePath);
}
/// <summary>
/// Save picture on file system
/// </summary>
/// <param name="pictureId">Picture identifier</param>
/// <param name="pictureBinary">Picture binary</param>
/// <param name="mimeType">MIME type</param>
protected virtual void SavePictureInFile(int pictureId, byte[] pictureBinary, string mimeType)
{
string lastPart = GetFileExtensionFromMimeType(mimeType);
string fileName = string.Format("{0}_0.{1}", pictureId.ToString("0000000"), lastPart);
File.WriteAllBytes(GetPictureLocalPath(fileName), pictureBinary);
}
/// <summary>
/// Delete a picture on file system
/// </summary>
/// <param name="picture">Picture</param>
protected virtual void DeletePictureOnFileSystem(Picture picture)
{
if (picture == null)
throw new ArgumentNullException("picture");
string lastPart = GetFileExtensionFromMimeType(picture.MimeType);
string fileName = string.Format("{0}_0.{1}", picture.Id.ToString("0000000"), lastPart);
string filePath = GetPictureLocalPath(fileName);
if (File.Exists(filePath))
{
File.Delete(filePath);
}
}
/// <summary>
/// Delete picture thumbs
/// </summary>
/// <param name="picture">Picture</param>
protected virtual void DeletePictureThumbs(Picture picture)
{
string filter = string.Format("{0}*.*", picture.Id.ToString("0000000"));
var thumbDirectoryPath = CommonHelper.MapPath("~/content/images/thumbs");
string[] currentFiles = System.IO.Directory.GetFiles(thumbDirectoryPath, filter, SearchOption.AllDirectories);
foreach (string currentFileName in currentFiles)
{
var thumbFilePath = GetThumbLocalPath(currentFileName);
File.Delete(thumbFilePath);
}
}
/// <summary>
/// Get picture (thumb) local path
/// </summary>
/// <param name="thumbFileName">Filename</param>
/// <returns>Local picture thumb path</returns>
protected virtual string GetThumbLocalPath(string thumbFileName)
{
var thumbsDirectoryPath = CommonHelper.MapPath("~/content/images/thumbs");
if (_mediaSettings.MultipleThumbDirectories)
{
//get the first two letters of the file name
var fileNameWithoutExtension = Path.GetFileNameWithoutExtension(thumbFileName);
if (fileNameWithoutExtension != null && fileNameWithoutExtension.Length > MULTIPLE_THUMB_DIRECTORIES_LENGTH)
{
var subDirectoryName = fileNameWithoutExtension.Substring(0, MULTIPLE_THUMB_DIRECTORIES_LENGTH);
thumbsDirectoryPath = Path.Combine(thumbsDirectoryPath, subDirectoryName);
if (!System.IO.Directory.Exists(thumbsDirectoryPath))
{
System.IO.Directory.CreateDirectory(thumbsDirectoryPath);
}
}
}
var thumbFilePath = Path.Combine(thumbsDirectoryPath, thumbFileName);
return thumbFilePath;
}
/// <summary>
/// Get picture (thumb) URL
/// </summary>
/// <param name="thumbFileName">Filename</param>
/// <param name="storeLocation">Store location URL; null to use determine the current store location automatically</param>
/// <returns>Local picture thumb path</returns>
protected virtual string GetThumbUrl(string thumbFileName, string storeLocation = null)
{
storeLocation = !String.IsNullOrEmpty(storeLocation)
? storeLocation
: _webHelper.GetStoreLocation();
var url = storeLocation + "content/images/thumbs/";
if (_mediaSettings.MultipleThumbDirectories)
{
//get the first two letters of the file name
var fileNameWithoutExtension = Path.GetFileNameWithoutExtension(thumbFileName);
if (fileNameWithoutExtension != null && fileNameWithoutExtension.Length > MULTIPLE_THUMB_DIRECTORIES_LENGTH)
{
var subDirectoryName = fileNameWithoutExtension.Substring(0, MULTIPLE_THUMB_DIRECTORIES_LENGTH);
url = url + subDirectoryName + "/";
}
}
url = url + thumbFileName;
return url;
}
/// <summary>
/// Get picture local path. Used when images stored on file system (not in the database)
/// </summary>
/// <param name="fileName">Filename</param>
/// <returns>Local picture path</returns>
protected virtual string GetPictureLocalPath(string fileName)
{
return Path.Combine(CommonHelper.MapPath("~/content/images/"), fileName);
}
/// <summary>
/// Gets the loaded picture binary depending on picture storage settings
/// </summary>
/// <param name="picture">Picture</param>
/// <param name="fromDb">Load from database; otherwise, from file system</param>
/// <returns>Picture binary</returns>
protected virtual byte[] LoadPictureBinary(Picture picture, bool fromDb)
{
if (picture == null)
throw new ArgumentNullException("picture");
var result = fromDb
? picture.PictureBinary
: LoadPictureFromFile(picture.Id, picture.MimeType);
return result;
}
/// <summary>
/// Get a value indicating whether some file (thumb) already exists
/// </summary>
/// <param name="thumbFilePath">Thumb file path</param>
/// <param name="thumbFileName">Thumb file name</param>
/// <returns>Result</returns>
protected virtual bool GeneratedThumbExists(string thumbFilePath, string thumbFileName)
{
return File.Exists(thumbFilePath);
}
/// <summary>
/// Save a value indicating whether some file (thumb) already exists
/// </summary>
/// <param name="thumbFilePath">Thumb file path</param>
/// <param name="thumbFileName">Thumb file name</param>
/// <param name="mimeType">MIME type</param>
/// <param name="binary">Picture binary</param>
protected virtual void SaveThumb(string thumbFilePath, string thumbFileName, string mimeType, byte[] binary)
{
File.WriteAllBytes(thumbFilePath, binary);
}
#endregion
#region Getting picture local path/URL methods
/// <summary>
/// Gets the loaded picture binary depending on picture storage settings
/// </summary>
/// <param name="picture">Picture</param>
/// <returns>Picture binary</returns>
public virtual byte[] LoadPictureBinary(Picture picture)
{
return LoadPictureBinary(picture, this.StoreInDb);
}
/// <summary>
/// Get picture SEO friendly name
/// </summary>
/// <param name="name">Name</param>
/// <returns>Result</returns>
public virtual string GetPictureSeName(string name)
{
return SeoExtensions.GetSeName(name, true, false);
}
/// <summary>
/// Gets the default picture URL
/// </summary>
/// <param name="targetSize">The target picture size (longest side)</param>
/// <param name="defaultPictureType">Default picture type</param>
/// <param name="storeLocation">Store location URL; null to use determine the current store location automatically</param>
/// <returns>Picture URL</returns>
public virtual string GetDefaultPictureUrl(int targetSize = 0,
PictureType defaultPictureType = PictureType.Entity,
string storeLocation = null)
{
string defaultImageFileName;
switch (defaultPictureType)
{
case PictureType.Avatar:
defaultImageFileName = _settingService.GetSettingByKey("Media.Customer.DefaultAvatarImageName", "default-avatar.jpg");
break;
case PictureType.Entity:
default:
defaultImageFileName = _settingService.GetSettingByKey("Media.DefaultImageName", "default-image.png");
break;
}
string filePath = GetPictureLocalPath(defaultImageFileName);
if (!File.Exists(filePath))
{
return "";
}
if (targetSize == 0)
{
string url = (!String.IsNullOrEmpty(storeLocation)
? storeLocation
: _webHelper.GetStoreLocation())
+ "content/images/" + defaultImageFileName;
return url;
}
else
{
string fileExtension = Path.GetExtension(filePath);
string thumbFileName = string.Format("{0}_{1}{2}",
Path.GetFileNameWithoutExtension(filePath),
targetSize,
fileExtension);
var thumbFilePath = GetThumbLocalPath(thumbFileName);
if (!GeneratedThumbExists(thumbFilePath, thumbFileName))
{
using (var b = new Bitmap(filePath))
{
using (var destStream = new MemoryStream())
{
var newSize = CalculateDimensions(b.Size, targetSize);
ImageBuilder.Current.Build(b, destStream, new ResizeSettings
{
Width = newSize.Width,
Height = newSize.Height,
Scale = ScaleMode.Both,
Quality = _mediaSettings.DefaultImageQuality
});
var destBinary = destStream.ToArray();
SaveThumb(thumbFilePath, thumbFileName, "", destBinary);
}
}
}
var url = GetThumbUrl(thumbFileName, storeLocation);
return url;
}
}
/// <summary>
/// Get a picture URL
/// </summary>
/// <param name="pictureId">Picture identifier</param>
/// <param name="targetSize">The target picture size (longest side)</param>
/// <param name="showDefaultPicture">A value indicating whether the default picture is shown</param>
/// <param name="storeLocation">Store location URL; null to use determine the current store location automatically</param>
/// <param name="defaultPictureType">Default picture type</param>
/// <returns>Picture URL</returns>
public virtual string GetPictureUrl(int pictureId,
int targetSize = 0,
bool showDefaultPicture = true,
string storeLocation = null,
PictureType defaultPictureType = PictureType.Entity)
{
var picture = GetPictureById(pictureId);
return GetPictureUrl(picture, targetSize, showDefaultPicture, storeLocation, defaultPictureType);
}
/// <summary>
/// Get a picture URL
/// </summary>
/// <param name="picture">Picture instance</param>
/// <param name="targetSize">The target picture size (longest side)</param>
/// <param name="showDefaultPicture">A value indicating whether the default picture is shown</param>
/// <param name="storeLocation">Store location URL; null to use determine the current store location automatically</param>
/// <param name="defaultPictureType">Default picture type</param>
/// <returns>Picture URL</returns>
public virtual string GetPictureUrl(Picture picture,
int targetSize = 0,
bool showDefaultPicture = true,
string storeLocation = null,
PictureType defaultPictureType = PictureType.Entity)
{
string url = string.Empty;
byte[] pictureBinary = null;
if (picture != null)
pictureBinary = LoadPictureBinary(picture);
if (picture == null || pictureBinary == null || pictureBinary.Length == 0)
{
if (showDefaultPicture)
{
url = GetDefaultPictureUrl(targetSize, defaultPictureType, storeLocation);
}
return url;
}
if (picture.IsNew)
{
DeletePictureThumbs(picture);
//we do not validate picture binary here to ensure that no exception ("Parameter is not valid") will be thrown
picture = UpdatePicture(picture.Id,
pictureBinary,
picture.MimeType,
picture.SeoFilename,
picture.AltAttribute,
picture.TitleAttribute,
false,
false);
}
var seoFileName = picture.SeoFilename; // = GetPictureSeName(picture.SeoFilename); //just for sure
string lastPart = GetFileExtensionFromMimeType(picture.MimeType);
string thumbFileName;
if (targetSize == 0)
{
thumbFileName = !String.IsNullOrEmpty(seoFileName)
? string.Format("{0}_{1}.{2}", picture.Id.ToString("0000000"), seoFileName, lastPart)
: string.Format("{0}.{1}", picture.Id.ToString("0000000"), lastPart);
}
else
{
thumbFileName = !String.IsNullOrEmpty(seoFileName)
? string.Format("{0}_{1}_{2}.{3}", picture.Id.ToString("0000000"), seoFileName, targetSize, lastPart)
: string.Format("{0}_{1}.{2}", picture.Id.ToString("0000000"), targetSize, lastPart);
}
string thumbFilePath = GetThumbLocalPath(thumbFileName);
//the named mutex helps to avoid creating the same files in different threads,
//and does not decrease performance significantly, because the code is blocked only for the specific file.
using (var mutex = new Mutex(false, thumbFileName))
{
if(!GeneratedThumbExists(thumbFilePath, thumbFileName))
{
mutex.WaitOne();
//check, if the file was created, while we were waiting for the release of the mutex.
if (!GeneratedThumbExists(thumbFilePath, thumbFileName))
{
byte[] pictureBinaryResized;
//resizing required
if (targetSize != 0)
{
using (var stream = new MemoryStream(pictureBinary))
{
Bitmap b = null;
try
{
//try-catch to ensure that picture binary is really OK. Otherwise, we can get "Parameter is not valid" exception if binary is corrupted for some reasons
b = new Bitmap(stream);
}
catch (ArgumentException exc)
{
_logger.Error(string.Format("Error generating picture thumb. ID={0}", picture.Id),
exc);
}
if (b == null)
{
//bitmap could not be loaded for some reasons
return url;
}
using (var destStream = new MemoryStream())
{
var newSize = CalculateDimensions(b.Size, targetSize);
ImageBuilder.Current.Build(b, destStream, new ResizeSettings
{
Width = newSize.Width,
Height = newSize.Height,
Scale = ScaleMode.Both,
Quality = _mediaSettings.DefaultImageQuality
});
pictureBinaryResized = destStream.ToArray();
b.Dispose();
}
}
}
else
{
//create a copy of pictureBinary
pictureBinaryResized = pictureBinary.ToArray();
}
SaveThumb(thumbFilePath, thumbFileName, picture.MimeType, pictureBinaryResized);
}
mutex.ReleaseMutex();
}
}
url = GetThumbUrl(thumbFileName, storeLocation);
return url;
}
/// <summary>
/// Get a picture local path
/// </summary>
/// <param name="picture">Picture instance</param>
/// <param name="targetSize">The target picture size (longest side)</param>
/// <param name="showDefaultPicture">A value indicating whether the default picture is shown</param>
/// <returns></returns>
public virtual string GetThumbLocalPath(Picture picture, int targetSize = 0, bool showDefaultPicture = true)
{
string url = GetPictureUrl(picture, targetSize, showDefaultPicture);
if (String.IsNullOrEmpty(url))
return String.Empty;
return GetThumbLocalPath(Path.GetFileName(url));
}
#endregion
#region CRUD methods
/// <summary>
/// Gets a picture
/// </summary>
/// <param name="pictureId">Picture identifier</param>
/// <returns>Picture</returns>
public virtual Picture GetPictureById(int pictureId)
{
if (pictureId == 0)
return null;
return _pictureRepository.GetById(pictureId);
}
/// <summary>
/// Deletes a picture
/// </summary>
/// <param name="picture">Picture</param>
public virtual void DeletePicture(Picture picture)
{
if (picture == null)
throw new ArgumentNullException("picture");
//delete thumbs
DeletePictureThumbs(picture);
//delete from file system
if (!this.StoreInDb)
DeletePictureOnFileSystem(picture);
//delete from database
_pictureRepository.Delete(picture);
//event notification
_eventPublisher.EntityDeleted(picture);
}
/// <summary>
/// Gets a collection of pictures
/// </summary>
/// <param name="pageIndex">Current page</param>
/// <param name="pageSize">Items on each page</param>
/// <returns>Paged list of pictures</returns>
public virtual IPagedList<Picture> GetPictures(int pageIndex = 0, int pageSize = int.MaxValue)
{
var query = from p in _pictureRepository.Table
orderby p.Id descending
select p;
var pics = new PagedList<Picture>(query, pageIndex, pageSize);
return pics;
}
/// <summary>
/// Gets pictures by product identifier
/// </summary>
/// <param name="productId">Product identifier</param>
/// <param name="recordsToReturn">Number of records to return. 0 if you want to get all items</param>
/// <returns>Pictures</returns>
public virtual IList<Picture> GetPicturesByProductId(int productId, int recordsToReturn = 0)
{
if (productId == 0)
return new List<Picture>();
var query = from p in _pictureRepository.Table
join pp in _productPictureRepository.Table on p.Id equals pp.PictureId
orderby pp.DisplayOrder, pp.Id
where pp.ProductId == productId
select p;
if (recordsToReturn > 0)
query = query.Take(recordsToReturn);
var pics = query.ToList();
return pics;
}
/// <summary>
/// Inserts a picture
/// </summary>
/// <param name="pictureBinary">The picture binary</param>
/// <param name="mimeType">The picture MIME type</param>
/// <param name="seoFilename">The SEO filename</param>
/// <param name="altAttribute">"alt" attribute for "img" HTML element</param>
/// <param name="titleAttribute">"title" attribute for "img" HTML element</param>
/// <param name="isNew">A value indicating whether the picture is new</param>
/// <param name="validateBinary">A value indicating whether to validated provided picture binary</param>
/// <returns>Picture</returns>
public virtual Picture InsertPicture(byte[] pictureBinary, string mimeType, string seoFilename,
string altAttribute = null, string titleAttribute = null,
bool isNew = true, bool validateBinary = true)
{
mimeType = CommonHelper.EnsureNotNull(mimeType);
mimeType = CommonHelper.EnsureMaximumLength(mimeType, 20);
seoFilename = CommonHelper.EnsureMaximumLength(seoFilename, 100);
if (validateBinary)
pictureBinary = ValidatePicture(pictureBinary, mimeType);
var picture = new Picture
{
PictureBinary = this.StoreInDb ? pictureBinary : new byte[0],
MimeType = mimeType,
SeoFilename = seoFilename,
AltAttribute = altAttribute,
TitleAttribute = titleAttribute,
IsNew = isNew,
};
_pictureRepository.Insert(picture);
if (!this.StoreInDb)
SavePictureInFile(picture.Id, pictureBinary, mimeType);
//event notification
_eventPublisher.EntityInserted(picture);
return picture;
}
/// <summary>
/// Updates the picture
/// </summary>
/// <param name="pictureId">The picture identifier</param>
/// <param name="pictureBinary">The picture binary</param>
/// <param name="mimeType">The picture MIME type</param>
/// <param name="seoFilename">The SEO filename</param>
/// <param name="altAttribute">"alt" attribute for "img" HTML element</param>
/// <param name="titleAttribute">"title" attribute for "img" HTML element</param>
/// <param name="isNew">A value indicating whether the picture is new</param>
/// <param name="validateBinary">A value indicating whether to validated provided picture binary</param>
/// <returns>Picture</returns>
public virtual Picture UpdatePicture(int pictureId, byte[] pictureBinary, string mimeType,
string seoFilename, string altAttribute = null, string titleAttribute = null,
bool isNew = true, bool validateBinary = true)
{
mimeType = CommonHelper.EnsureNotNull(mimeType);
mimeType = CommonHelper.EnsureMaximumLength(mimeType, 20);
seoFilename = CommonHelper.EnsureMaximumLength(seoFilename, 100);
if (validateBinary)
pictureBinary = ValidatePicture(pictureBinary, mimeType);
var picture = GetPictureById(pictureId);
if (picture == null)
return null;
//delete old thumbs if a picture has been changed
if (seoFilename != picture.SeoFilename)
DeletePictureThumbs(picture);
picture.PictureBinary = this.StoreInDb ? pictureBinary : new byte[0];
picture.MimeType = mimeType;
picture.SeoFilename = seoFilename;
picture.AltAttribute = altAttribute;
picture.TitleAttribute = titleAttribute;
picture.IsNew = isNew;
_pictureRepository.Update(picture);
if (!this.StoreInDb)
SavePictureInFile(picture.Id, pictureBinary, mimeType);
//event notification
_eventPublisher.EntityUpdated(picture);
return picture;
}
/// <summary>
/// Updates a SEO filename of a picture
/// </summary>
/// <param name="pictureId">The picture identifier</param>
/// <param name="seoFilename">The SEO filename</param>
/// <returns>Picture</returns>
public virtual Picture SetSeoFilename(int pictureId, string seoFilename)
{
var picture = GetPictureById(pictureId);
if (picture == null)
throw new ArgumentException("No picture found with the specified id");
//update if it has been changed
if (seoFilename != picture.SeoFilename)
{
//update picture
picture = UpdatePicture(picture.Id,
LoadPictureBinary(picture),
picture.MimeType,
seoFilename,
picture.AltAttribute,
picture.TitleAttribute,
true,
false);
}
return picture;
}
/// <summary>
/// Validates input picture dimensions
/// </summary>
/// <param name="pictureBinary">Picture binary</param>
/// <param name="mimeType">MIME type</param>
/// <returns>Picture binary or throws an exception</returns>
public virtual byte[] ValidatePicture(byte[] pictureBinary, string mimeType)
{
using (var destStream = new MemoryStream())
{
ImageBuilder.Current.Build(pictureBinary, destStream, new ResizeSettings
{
MaxWidth = _mediaSettings.MaximumImageSize,
MaxHeight = _mediaSettings.MaximumImageSize,
Quality = _mediaSettings.DefaultImageQuality
});
return destStream.ToArray();
}
}
/// <summary>
/// Helper class for making pictures hashes from DB
/// </summary>
private class HashItem: IComparable, IComparable<HashItem>
{
public int PictureId { get; set; }
public byte[] Hash { get; set; }
public int CompareTo(object obj)
{
return CompareTo(obj as HashItem);
}
public int CompareTo(HashItem other)
{
return other == null ? -1 : PictureId.CompareTo(other.PictureId);
}
}
/// <summary>
/// Get pictures hashes
/// </summary>
/// <param name="picturesIds">Pictures Ids</param>
/// <returns></returns>
public IDictionary<int, string> GetPicturesHash(int[] picturesIds)
{
var supportedLengthOfBinaryHash = _dataProvider.SupportedLengthOfBinaryHash();
if(supportedLengthOfBinaryHash == 0 || !picturesIds.Any())
return new Dictionary<int, string>();
const string strCommand = "SELECT [Id] as [PictureId], HASHBYTES('sha1', substring([PictureBinary], 0, {0})) as [Hash] FROM [Picture] where id in ({1})";
return _dbContext.SqlQuery<HashItem>(String.Format(strCommand, supportedLengthOfBinaryHash, picturesIds.Select(p => p.ToString()).Aggregate((all, current) => all + ", " + current))).Distinct()
.ToDictionary(p => p.PictureId, p => BitConverter.ToString(p.Hash).Replace("-", ""));
}
#endregion
#region Properties
/// <summary>
/// Gets or sets a value indicating whether the images should be stored in data base.
/// </summary>
public virtual bool StoreInDb
{
get
{
return _settingService.GetSettingByKey("Media.Images.StoreInDB", true);
}
set
{
//check whether it's a new value
if (this.StoreInDb == value)
return;
//save the new setting value
_settingService.SetSetting("Media.Images.StoreInDB", value);
int pageIndex = 0;
const int pageSize = 400;
var originalProxyCreationEnabled = _dbContext.ProxyCreationEnabled;
try
{
//we set this property for performance optimization
//it could be critical if you we have several thousand pictures
_dbContext.ProxyCreationEnabled = false;
while (true)
{
var pictures = this.GetPictures(pageIndex, pageSize);
pageIndex++;
//all pictures converted?
if (!pictures.Any())
break;
foreach (var picture in pictures)
{
var pictureBinary = LoadPictureBinary(picture, !value);
//we used the code below before. but it's too slow
//let's do it manually (uncommented code) - copy some logic from "UpdatePicture" method
/*just update a picture (all required logic is in "UpdatePicture" method)
we do not validate picture binary here to ensure that no exception ("Parameter is not valid") will be thrown when "moving" pictures
UpdatePicture(picture.Id,
pictureBinary,
picture.MimeType,
picture.SeoFilename,
true,
false);*/
if (value)
//delete from file system. now it's in the database
DeletePictureOnFileSystem(picture);
else
//now on file system
SavePictureInFile(picture.Id, pictureBinary, picture.MimeType);
//update appropriate properties
picture.PictureBinary = value ? pictureBinary : new byte[0];
picture.IsNew = true;
//raise event?
//_eventPublisher.EntityUpdated(picture);
}
//save all at once
_pictureRepository.Update(pictures);
//detach them in order to release memory
foreach (var picture in pictures)
{
_dbContext.Detach(picture);
}
}
}
finally
{
_dbContext.ProxyCreationEnabled = originalProxyCreationEnabled;
}
}
}
#endregion
}
}
| |
using System;
using System.Collections;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Windows.Forms;
namespace VRS.UI.Controls
{
/// <summary>
/// ComboBox control.
/// </summary>
[DefaultEvent("SelectedIndexChanged"),]
public class WComboBox : WButtonEdit
{
private System.ComponentModel.IContainer components = null;
public event System.EventHandler SelectedIndexChanged = null;
private WComboPopUp m_WComboPopUp = null;
private int m_DropDownWidth = 100;
private int m_VisibleItems = 10;
private WComboItems m_WComboItems = null;
private WComboItem m_SelectedItem = null;
/// <summary>
/// Default constructor.
/// </summary>
public WComboBox()
{
// This call is required by the Windows.Forms Form Designer.
InitializeComponent();
// TODO: Add any initialization after the InitForm call
m_pTextBox.LostFocus += new System.EventHandler(this.m_pTextBox_OnLostFocus);
m_WComboItems = new WComboItems(this);
m_DrawGrayImgForReadOnly = false;
m_DropDownWidth = this.Width;
}
#region function Dispose
/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose( bool disposing )
{
if( disposing )
{
if(components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
}
#endregion
#region Component Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
((System.ComponentModel.ISupportInitialize)(this)).BeginInit();
this.SuspendLayout();
//
// m_pTextBox
//
this.m_pTextBox.ProccessMessage += new VRS.UI.Controls.WMessage_EventHandler(this.m_pTextBox_ProccessMessage);
//
// WComboBox
//
this.Controls.AddRange(new System.Windows.Forms.Control[] {
this.m_pTextBox});
this.Name = "WComboBox";
this.ViewStyle.BorderColor = System.Drawing.Color.DarkGray;
this.ViewStyle.BorderHotColor = System.Drawing.Color.Black;
this.ViewStyle.ButtonColor = System.Drawing.SystemColors.Control;
this.ViewStyle.ButtonHotColor = System.Drawing.Color.FromArgb(((System.Byte)(182)), ((System.Byte)(193)), ((System.Byte)(214)));
this.ViewStyle.ButtonPressedColor = System.Drawing.Color.FromArgb(((System.Byte)(210)), ((System.Byte)(218)), ((System.Byte)(232)));
this.ViewStyle.ControlBackColor = System.Drawing.SystemColors.Control;
this.ViewStyle.EditColor = System.Drawing.Color.White;
this.ViewStyle.EditDisabledColor = System.Drawing.Color.Gainsboro;
this.ViewStyle.EditFocusedColor = System.Drawing.Color.Beige;
this.ViewStyle.EditReadOnlyColor = System.Drawing.Color.White;
this.ViewStyle.FlashColor = System.Drawing.Color.Pink;
((System.ComponentModel.ISupportInitialize)(this)).EndInit();
this.ResumeLayout(false);
}
#endregion
#region Events handling
#region function OnPopUp_SelectionChanged
private void OnPopUp_SelectionChanged(object sender,WComboSelChanged_EventArgs e)
{
this.Text = e.Text;
m_SelectedItem = e.Item;
OnSelectedIndexChanged();
}
#endregion
#region function OnPopUp_Closed
private void OnPopUp_Closed(object sender,System.EventArgs e)
{
m_DroppedDown = false;
m_WComboPopUp.Dispose();
Invalidate(false);
if(!this.ContainsFocus){
this.BackColor = m_ViewStyle.GetEditColor(this.ReadOnly,this.Enabled);
}
}
#endregion
#region function m_pTextBox_ProccessMessage
private bool m_pTextBox_ProccessMessage(object sender,ref System.Windows.Forms.Message m)
{
if(m_DroppedDown && m_WComboPopUp != null && IsNeeded(ref m)){
// Forward message to PopUp Form
m_WComboPopUp.PostMessage(ref m);
return true;
}
return false;
}
#endregion
#region function m_pTextBox_OnLostFocus
private void m_pTextBox_OnLostFocus(object sender, System.EventArgs e)
{
if(m_DroppedDown && m_WComboPopUp != null&& !m_WComboPopUp.ClientRectangle.Contains(m_WComboPopUp.PointToClient(Control.MousePosition))){
m_WComboPopUp.Close();
m_DroppedDown = false;
}
}
#endregion
#endregion
#region override OnButtonPressed
protected override void OnButtonPressed()
{
if(m_DroppedDown){
return;
}
ShowPopUp();
}
#endregion
#region override OnPlusKeyPressed
protected override void OnPlusKeyPressed()
{
if(m_DroppedDown){
return;
}
ShowPopUp();
}
#endregion
#region override OnSizeChanged
protected override void OnSizeChanged(System.EventArgs e)
{
base.OnSizeChanged(e);
if(this.DesignMode){
m_DropDownWidth = this.Width;
}
}
#endregion
#region function ShowPopUp
private void ShowPopUp()
{
Point pt = new Point(this.Left,this.Bottom + 1);
m_WComboPopUp = new WComboPopUp(this,m_ViewStyle,m_WComboItems.ToArray(),m_VisibleItems,this.Text,m_DropDownWidth);
m_WComboPopUp.Location = this.Parent.PointToScreen(pt);
m_WComboPopUp.SelectionChanged += new SelectionChangedHandler(this.OnPopUp_SelectionChanged);
m_WComboPopUp.Closed += new System.EventHandler(this.OnPopUp_Closed);
User32.ShowWindow(m_WComboPopUp.Handle,4);
m_WComboPopUp.m_Start = true;
m_DroppedDown = true;
}
#endregion
#region function SelectItemByTag
public void SelectItemByTag(object tag)
{
if(tag == null){
return;
}
int index = 0;
foreach(WComboItem it in this.Items){
if(it.Tag.ToString() == tag.ToString()){
this.SelectedIndex = index;
}
index++;
}
}
#endregion
#region function IsNeeded
private bool IsNeeded(ref System.Windows.Forms.Message m)
{
if(m.Msg == (int)Msgs.WM_MOUSEWHEEL){
return true;
}
if(m.Msg == (int)Msgs.WM_KEYUP || m.Msg == (int)Msgs.WM_KEYDOWN){
return true;
}
if(m.Msg == (int)Msgs.WM_CHAR){
return true;
}
return false;
}
#endregion
#region Properties Implementation
public int DropDownWidth
{
get{ return m_DropDownWidth; }
set{ m_DropDownWidth = value; }
}
public int VisibleItems
{
get{ return m_VisibleItems; }
set{ m_VisibleItems = value; }
}
public WComboItems Items
{
get{ return m_WComboItems; }
}
public WComboItem SelectedItem
{
get{ return m_SelectedItem; }
}
public int SelectedIndex
{
get{
if(this.SelectedItem != null){
return Items.IndexOf(this.SelectedItem);
}
else{
return -1;
}
}
set{
if(value > -1 && value < this.Items.Count){
m_SelectedItem = this.Items[value];
this.Text = m_SelectedItem.Text;
}
}
}
#endregion
#region Events Implementation
private void OnSelectedIndexChanged()
{
if(SelectedIndexChanged != null){
SelectedIndexChanged(this,new System.EventArgs());
}
}
#endregion
}
}
| |
/*
###
# # ######### _______ _ _ ______ _ _
## ######## @ ## |______ | | | ____ | |
################## | |_____| |_____| |_____|
## ############# f r a m e w o r k
# # #########
###
(c) 2015 - 2017 FUGU framework project
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Net.Sockets;
namespace Fugu.Ftp
{
/// <summary>
/// The FTP client
/// </summary>
public class FtpClient : IFtpClient
{
/// <summary>
/// Creates the new instance
/// </summary>
/// <param name="endPoint">The FTP's endpoint</param>
/// <param name="credentials">The FTP's credentials</param>
public FtpClient(EndPoint endPoint, NetworkCredential credentials)
{
Contract.NotNull(endPoint, nameof(endPoint));
EndPoint = endPoint;
Credentials = credentials;
}
/// <summary>
/// The FTP's endpoint
/// </summary>
public EndPoint EndPoint { get; }
/// <summary>
/// The FTP's credentials
/// </summary>
public NetworkCredential Credentials { get; }
/// <summary>
/// Returns all files in the folder
/// </summary>
/// <param name="relativePath">The relative path to the folder</param>
/// <returns>All files</returns>
public IEnumerable<string> GetFileList(string relativePath)
{
Contract.NotNull(relativePath, nameof(relativePath));
using (var ftpConnection = InitNewConnection())
{
// init and open the connection
ftpConnection.Open();
// change working directory
ftpConnection.ChangeWorkingDirectory(relativePath);
// change to binary mode
ftpConnection.SendCommand(FtpCommand.ModeBinary);
// read the list of files
string[] files;
using (var transferSocket = ftpConnection.OpenTransferSocket())
{
ftpConnection.SendCommand(FtpCommand.GetFilesList);
string message = transferSocket.RecieveTextMessage();
files = message.Split(new string[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries);
}
// clear command socket
ftpConnection.GetAndCheckResponse(true, 226, 250);
// change to ASCII mode
ftpConnection.SendCommand(FtpCommand.ModeAscii);
// choose only files from the list
List<string> onlyFiles = new List<string>();
foreach (var file in files)
{
var sizeFileResponse = ftpConnection.SendCommand(FtpCommand.FileSize, file);
if (sizeFileResponse.Status == 213)
{
onlyFiles.Add(file);
}
// it raises error 451 for files with "." in the name
else if (sizeFileResponse.Status == 451
&& file.Contains("."))
{
onlyFiles.Add(file);
}
}
return onlyFiles.ToArray();
}
}
/// <summary>
/// Returns the file's content
/// </summary>
/// <param name="relativeFullPath">The relative path to the file</param>
/// <returns>The file's content</returns>
public byte[] DownloadFile(string relativeFullPath)
{
Contract.NotNull(relativeFullPath, nameof(relativeFullPath));
byte[] content;
using (var ftpConnection = InitNewConnection())
{
// init and open the connection
ftpConnection.Open();
// change to binary mode
ftpConnection.SendCommand(FtpCommand.ModeBinary);
// download file's content
using (var transferSocket = ftpConnection.OpenTransferSocket())
{
ftpConnection.SendCommand(FtpCommand.DownloadFile, relativeFullPath);
using (var stream = new MemoryStream())
{
byte[] buffer = new byte[4 * 1024];
int length;
while ((length = transferSocket.Receive(buffer, buffer.Length, SocketFlags.None)) > 0)
{
stream.Write(buffer, 0, length);
}
content = stream.ToArray();
}
}
// clear command socket
ftpConnection.GetAndCheckResponse(true, 226, 250);
}
return content;
}
/// <summary>
/// Uploads the file's content
/// </summary>
/// <param name="relativeFullPath">The relative path to the file</param>
/// <param name="content">The file's content</param>
/// <param name="transferType">The transfer's type</param>
public void UploadFile(string relativeFullPath, byte[] content, FtpTransferType transferType)
{
Contract.NotNull(relativeFullPath, nameof(relativeFullPath));
Contract.NotNull(content, nameof(content));
using (Stream fileStream = new MemoryStream(content))
{
using (var ftpConnection = InitNewConnection())
{
// init and open the connection
ftpConnection.Open();
// switch to correct mode
switch (transferType)
{
case FtpTransferType.ASCII:
ftpConnection.SendCommand(FtpCommand.ModeAscii);
break;
case FtpTransferType.Binary:
ftpConnection.SendCommand(FtpCommand.ModeBinary);
break;
}
// upload file's content
using (var transferSocket = ftpConnection.OpenTransferSocket())
{
ftpConnection.SendCommand(FtpCommand.UploadFile, relativeFullPath);
const int bufferSize = 4 * 1024;
byte[] buffer = new byte[bufferSize];
int length;
while ((length = fileStream.Read(buffer, 0, bufferSize)) > 0)
{
transferSocket.Send(buffer, length, SocketFlags.None);
}
}
// clear command socket
ftpConnection.GetAndCheckResponse(true, 226, 250);
}
}
}
/// <summary>
/// Deletes the file
/// </summary>
/// <param name="relativeFullPath">The relative path to the file</param>
public void DeleteFile(string relativeFullPath)
{
Contract.NotNull(relativeFullPath, nameof(relativeFullPath));
using (var ftpConnection = InitNewConnection())
{
// init and open the connection
ftpConnection.Open();
// change to binary mode
ftpConnection.SendCommand(FtpCommand.ModeBinary);
// delete file
ftpConnection.SendCommand(FtpCommand.DeleteFile, relativeFullPath);
}
}
/// <summary>
/// Inits the new FTP connection
/// </summary>
/// <returns>The new FTP connection</returns>
private FtpConnection InitNewConnection()
{
var ftpConnection = new FtpConnection(EndPoint, Credentials);
return ftpConnection;
}
}
}
| |
// 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.CompilerServices;
public struct Point
{
public int w;
public int x;
public int y;
public int z;
[MethodImplAttribute(MethodImplOptions.NoInlining)]
public Point(int a, int b, int c, int d) { w=a; x=a; y=b; z=d; }
public int W
{
[MethodImplAttribute(MethodImplOptions.NoInlining)]
get { return this.w; }
[MethodImplAttribute(MethodImplOptions.NoInlining)]
set { this.w = value; }
}
public int X
{
[MethodImplAttribute(MethodImplOptions.NoInlining)]
get { return this.x; }
[MethodImplAttribute(MethodImplOptions.NoInlining)]
set { this.x = value; }
}
public int Y
{
[MethodImplAttribute(MethodImplOptions.NoInlining)]
get { return this.y; }
[MethodImplAttribute(MethodImplOptions.NoInlining)]
set { this.y = value; }
}
public int Z
{
[MethodImplAttribute(MethodImplOptions.NoInlining)]
get { return this.z; }
[MethodImplAttribute(MethodImplOptions.NoInlining)]
set { this.z = value; }
}
// Returns true if this represents 'origin' otherwise false.
[MethodImplAttribute(MethodImplOptions.NoInlining)]
public bool StructInstMethod() { return (x==0 && y == 0 && z==0); }
}
public class BringUpTest
{
const int Pass = 100;
const int Fail = -1;
[MethodImplAttribute(MethodImplOptions.NoInlining)]
public static int method_4S(Point p0, Point p1, Point p2, Point p3)
{
Console.Write("method_4S");
if (p0.W != 0)
return Fail;
if (p0.X != 0)
return Fail;
if (p0.Y != 0)
return Fail;
if (p0.Z != 0)
return Fail;
if (p1.W != 1)
return Fail;
if (p1.X != 1)
return Fail;
if (p1.Y != 1)
return Fail;
if (p1.Z != 1)
return Fail;
if (p2.W != 9)
return Fail;
if (p2.X != 99)
return Fail;
if (p2.Y != 999)
return Fail;
if (p2.Z != 9999)
return Fail;
if (p3.W != 10)
return Fail;
if (p3.X != 100)
return Fail;
if (p3.Y != 1000)
return Fail;
if (p3.Z != 10000)
return Fail;
Console.WriteLine(" Pass");
return Pass;
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
public static int method_4S4I(Point p0, Point p1, Point p2, Point p3, int i0, int i1, int i2, int i3)
{
Console.Write("method_4S4I");
if (i0 != 2)
return Fail;
if (i1 != 3)
return Fail;
if (i2 != 5)
return Fail;
if (i3 != 7)
return Fail;
if (p0.W != 0)
return Fail;
if (p0.X != 0)
return Fail;
if (p0.Y != 0)
return Fail;
if (p0.Z != 0)
return Fail;
if (p1.W != 1)
return Fail;
if (p1.X != 1)
return Fail;
if (p1.Y != 1)
return Fail;
if (p1.Z != 1)
return Fail;
if (p2.W != 9)
return Fail;
if (p2.X != 99)
return Fail;
if (p2.Y != 999)
return Fail;
if (p2.Z != 9999)
return Fail;
if (p3.W != 10)
return Fail;
if (p3.X != 100)
return Fail;
if (p3.Y != 1000)
return Fail;
if (p3.Z != 10000)
return Fail;
Console.WriteLine(" Pass");
return Pass;
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
public static int method_4I4S(int i0, int i1, int i2, int i3, Point p0, Point p1, Point p2, Point p3)
{
Console.Write("method_4I4S");
if (i0 != 2)
return Fail;
if (i1 != 3)
return Fail;
if (i2 != 5)
return Fail;
if (i3 != 7)
return Fail;
if (p0.W != 0)
return Fail;
if (p0.X != 0)
return Fail;
if (p0.Y != 0)
return Fail;
if (p0.Z != 0)
return Fail;
if (p1.W != 1)
return Fail;
if (p1.X != 1)
return Fail;
if (p1.Y != 1)
return Fail;
if (p1.Z != 1)
return Fail;
if (p2.W != 9)
return Fail;
if (p2.X != 99)
return Fail;
if (p2.Y != 999)
return Fail;
if (p2.Z != 9999)
return Fail;
if (p3.W != 10)
return Fail;
if (p3.X != 100)
return Fail;
if (p3.Y != 1000)
return Fail;
if (p3.Z != 10000)
return Fail;
Console.WriteLine(" Pass");
return Pass;
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
public static int method_1I4S(int i0, Point p0, Point p1, Point p2, Point p3)
{
Console.Write("method_1I4S");
if (i0 != 2)
return Fail;
if (p0.W != 0)
return Fail;
if (p0.X != 0)
return Fail;
if (p0.Y != 0)
return Fail;
if (p0.Z != 0)
return Fail;
if (p1.W != 1)
return Fail;
if (p1.X != 1)
return Fail;
if (p1.Y != 1)
return Fail;
if (p1.Z != 1)
return Fail;
if (p2.W != 9)
return Fail;
if (p2.X != 99)
return Fail;
if (p2.Y != 999)
return Fail;
if (p2.Z != 9999)
return Fail;
if (p3.W != 10)
return Fail;
if (p3.X != 100)
return Fail;
if (p3.Y != 1000)
return Fail;
if (p3.Z != 10000)
return Fail;
Console.WriteLine(" Pass");
return Pass;
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
public static int method_2I4S(int i0, int i1, Point p0, Point p1, Point p2, Point p3)
{
Console.Write("method_2I4S");
if (i0 != 2)
return Fail;
if (i1 != 3)
return Fail;
if (p0.W != 0)
return Fail;
if (p0.X != 0)
return Fail;
if (p0.Y != 0)
return Fail;
if (p0.Z != 0)
return Fail;
if (p1.W != 1)
return Fail;
if (p1.X != 1)
return Fail;
if (p1.Y != 1)
return Fail;
if (p1.Z != 1)
return Fail;
if (p2.W != 9)
return Fail;
if (p2.X != 99)
return Fail;
if (p2.Y != 999)
return Fail;
if (p2.Z != 9999)
return Fail;
if (p3.W != 10)
return Fail;
if (p3.X != 100)
return Fail;
if (p3.Y != 1000)
return Fail;
if (p3.Z != 10000)
return Fail;
Console.WriteLine(" Pass");
return Pass;
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
public static int method_3I4S(int i0, int i1, int i2, Point p0, Point p1, Point p2, Point p3)
{
Console.Write("method_3I4S");
if (i0 != 2)
return Fail;
if (i1 != 3)
return Fail;
if (i2 != 5)
return Fail;
if (p0.W != 0)
return Fail;
if (p0.X != 0)
return Fail;
if (p0.Y != 0)
return Fail;
if (p0.Z != 0)
return Fail;
if (p1.W != 1)
return Fail;
if (p1.X != 1)
return Fail;
if (p1.Y != 1)
return Fail;
if (p1.Z != 1)
return Fail;
if (p2.W != 9)
return Fail;
if (p2.X != 99)
return Fail;
if (p2.Y != 999)
return Fail;
if (p2.Z != 9999)
return Fail;
if (p3.W != 10)
return Fail;
if (p3.X != 100)
return Fail;
if (p3.Y != 1000)
return Fail;
if (p3.Z != 10000)
return Fail;
Console.WriteLine(" Pass");
return Pass;
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
public static int method_2I4S2D(int i0, int i1, Point p0, Point p1, Point p2, Point p3, double d0, double d1)
{
Console.Write("method_2I4S2D");
if (i0 != 2)
return Fail;
if (i1 != 3)
return Fail;
if (d0 != 11.0d)
return Fail;
if (d1 != 13.0d)
return Fail;
if (p0.W != 0)
return Fail;
if (p0.X != 0)
return Fail;
if (p0.Y != 0)
return Fail;
if (p0.Z != 0)
return Fail;
if (p1.W != 1)
return Fail;
if (p1.X != 1)
return Fail;
if (p1.Y != 1)
return Fail;
if (p1.Z != 1)
return Fail;
if (p2.W != 9)
return Fail;
if (p2.X != 99)
return Fail;
if (p2.Y != 999)
return Fail;
if (p2.Z != 9999)
return Fail;
if (p3.W != 10)
return Fail;
if (p3.X != 100)
return Fail;
if (p3.Y != 1000)
return Fail;
if (p3.Z != 10000)
return Fail;
Console.WriteLine(" Pass");
return Pass;
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
public static int method_2I2D4S(int i0, int i1, double d0, double d1, Point p0, Point p1, Point p2, Point p3)
{
Console.Write("method_2I2D4S");
if (i0 != 2)
return Fail;
if (i1 != 3)
return Fail;
if (d0 != 11.0d)
return Fail;
if (d1 != 13.0d)
return Fail;
if (p0.W != 0)
return Fail;
if (p0.X != 0)
return Fail;
if (p0.Y != 0)
return Fail;
if (p0.Z != 0)
return Fail;
if (p1.W != 1)
return Fail;
if (p1.X != 1)
return Fail;
if (p1.Y != 1)
return Fail;
if (p1.Z != 1)
return Fail;
if (p2.W != 9)
return Fail;
if (p2.X != 99)
return Fail;
if (p2.Y != 999)
return Fail;
if (p2.Z != 9999)
return Fail;
if (p3.W != 10)
return Fail;
if (p3.X != 100)
return Fail;
if (p3.Y != 1000)
return Fail;
if (p3.Z != 10000)
return Fail;
Console.WriteLine(" Pass");
return Pass;
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
public static int method_2I2D4S2D(int i0, int i1, double d0, double d1, Point p0, Point p1, Point p2, Point p3, double d2, double d3)
{
Console.Write("method_2I2D4S2D");
if (i0 != 2)
return Fail;
if (i1 != 3)
return Fail;
if (d0 != 11.0d)
return Fail;
if (d1 != 13.0d)
return Fail;
if (d2 != 15.0d)
return Fail;
if (d3 != 17.0d)
return Fail;
if (p0.W != 0)
return Fail;
if (p0.X != 0)
return Fail;
if (p0.Y != 0)
return Fail;
if (p0.Z != 0)
return Fail;
if (p1.W != 1)
return Fail;
if (p1.X != 1)
return Fail;
if (p1.Y != 1)
return Fail;
if (p1.Z != 1)
return Fail;
if (p2.W != 9)
return Fail;
if (p2.X != 99)
return Fail;
if (p2.Y != 999)
return Fail;
if (p2.Z != 9999)
return Fail;
if (p3.W != 10)
return Fail;
if (p3.X != 100)
return Fail;
if (p3.Y != 1000)
return Fail;
if (p3.Z != 10000)
return Fail;
Console.WriteLine(" Pass");
return Pass;
}
public static int Main()
{
int i0 = 2;
int i1 = 3;
int i2 = 5;
int i3 = 7;
double d0 = 11.0d;
double d1 = 13.0d;
double d2 = 15.0d;
double d3 = 17.0d;
Point p0;
Point p1;
Point p2;
Point p3;
p0.w = 0;
p0.x = 0;
p0.y = 0;
p0.z = 0;
p1.w = 1;
p1.x = 1;
p1.y = 1;
p1.z = 1;
p2.w = 9;
p2.x = 99;
p2.y = 999;
p2.z = 9999;
p3.w = 10;
p3.x = 100;
p3.y = 1000;
p3.z = 10000;
if (method_4S(p0,p1,p2,p3) != Pass)
return Fail;
if (method_4S4I(p0,p1,p2,p3, i0,i1,i2,i3) != Pass)
return Fail;
if (method_4I4S(i0,i1,i2,i3, p0,p1,p2,p3) != Pass)
return Fail;
if (method_1I4S(i0, p0,p1,p2,p3) != Pass)
return Fail;
if (method_2I4S(i0,i1, p0,p1,p2,p3) != Pass)
return Fail;
if (method_3I4S(i0,i1,i2, p0,p1,p2,p3) != Pass)
return Fail;
if (method_2I4S2D(i0,i1, p0,p1,p2,p3, d0,d1) != Pass)
return Fail;
if (method_2I2D4S(i0,i1, d0,d1, p0,p1,p2,p3) != Pass)
return Fail;
if (method_2I2D4S2D(i0,i1, d0,d1, p0,p1,p2,p3, d2,d3) != Pass)
return Fail;
return Pass;
}
}
| |
// Code generated by Microsoft (R) AutoRest Code Generator 1.0.1.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace applicationGateway
{
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Models;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// Extension methods for NetworkInterfacesOperations.
/// </summary>
public static partial class NetworkInterfacesOperationsExtensions
{
/// <summary>
/// Deletes the specified network interface.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='networkInterfaceName'>
/// The name of the network interface.
/// </param>
public static void Delete(this INetworkInterfacesOperations operations, string resourceGroupName, string networkInterfaceName)
{
operations.DeleteAsync(resourceGroupName, networkInterfaceName).GetAwaiter().GetResult();
}
/// <summary>
/// Deletes the specified network interface.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='networkInterfaceName'>
/// The name of the network interface.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task DeleteAsync(this INetworkInterfacesOperations operations, string resourceGroupName, string networkInterfaceName, CancellationToken cancellationToken = default(CancellationToken))
{
(await operations.DeleteWithHttpMessagesAsync(resourceGroupName, networkInterfaceName, null, cancellationToken).ConfigureAwait(false)).Dispose();
}
/// <summary>
/// Gets information about the specified network interface.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='networkInterfaceName'>
/// The name of the network interface.
/// </param>
/// <param name='expand'>
/// Expands referenced resources.
/// </param>
public static NetworkInterface Get(this INetworkInterfacesOperations operations, string resourceGroupName, string networkInterfaceName, string expand = default(string))
{
return operations.GetAsync(resourceGroupName, networkInterfaceName, expand).GetAwaiter().GetResult();
}
/// <summary>
/// Gets information about the specified network interface.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='networkInterfaceName'>
/// The name of the network interface.
/// </param>
/// <param name='expand'>
/// Expands referenced resources.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<NetworkInterface> GetAsync(this INetworkInterfacesOperations operations, string resourceGroupName, string networkInterfaceName, string expand = default(string), CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetWithHttpMessagesAsync(resourceGroupName, networkInterfaceName, expand, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Creates or updates a network interface.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='networkInterfaceName'>
/// The name of the network interface.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to the create or update network interface operation.
/// </param>
public static NetworkInterface CreateOrUpdate(this INetworkInterfacesOperations operations, string resourceGroupName, string networkInterfaceName, NetworkInterface parameters)
{
return operations.CreateOrUpdateAsync(resourceGroupName, networkInterfaceName, parameters).GetAwaiter().GetResult();
}
/// <summary>
/// Creates or updates a network interface.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='networkInterfaceName'>
/// The name of the network interface.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to the create or update network interface operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<NetworkInterface> CreateOrUpdateAsync(this INetworkInterfacesOperations operations, string resourceGroupName, string networkInterfaceName, NetworkInterface parameters, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.CreateOrUpdateWithHttpMessagesAsync(resourceGroupName, networkInterfaceName, parameters, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Gets all network interfaces in a subscription.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
public static IPage<NetworkInterface> ListAll(this INetworkInterfacesOperations operations)
{
return operations.ListAllAsync().GetAwaiter().GetResult();
}
/// <summary>
/// Gets all network interfaces 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<NetworkInterface>> ListAllAsync(this INetworkInterfacesOperations operations, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListAllWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Gets all network interfaces 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<NetworkInterface> List(this INetworkInterfacesOperations operations, string resourceGroupName)
{
return operations.ListAsync(resourceGroupName).GetAwaiter().GetResult();
}
/// <summary>
/// Gets all network interfaces 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<NetworkInterface>> ListAsync(this INetworkInterfacesOperations operations, string resourceGroupName, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListWithHttpMessagesAsync(resourceGroupName, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Gets all route tables applied to a network interface.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='networkInterfaceName'>
/// The name of the network interface.
/// </param>
public static EffectiveRouteListResult GetEffectiveRouteTable(this INetworkInterfacesOperations operations, string resourceGroupName, string networkInterfaceName)
{
return operations.GetEffectiveRouteTableAsync(resourceGroupName, networkInterfaceName).GetAwaiter().GetResult();
}
/// <summary>
/// Gets all route tables applied to a network interface.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='networkInterfaceName'>
/// The name of the network interface.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<EffectiveRouteListResult> GetEffectiveRouteTableAsync(this INetworkInterfacesOperations operations, string resourceGroupName, string networkInterfaceName, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetEffectiveRouteTableWithHttpMessagesAsync(resourceGroupName, networkInterfaceName, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Gets all network security groups applied to a network interface.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='networkInterfaceName'>
/// The name of the network interface.
/// </param>
public static EffectiveNetworkSecurityGroupListResult ListEffectiveNetworkSecurityGroups(this INetworkInterfacesOperations operations, string resourceGroupName, string networkInterfaceName)
{
return operations.ListEffectiveNetworkSecurityGroupsAsync(resourceGroupName, networkInterfaceName).GetAwaiter().GetResult();
}
/// <summary>
/// Gets all network security groups applied to a network interface.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='networkInterfaceName'>
/// The name of the network interface.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<EffectiveNetworkSecurityGroupListResult> ListEffectiveNetworkSecurityGroupsAsync(this INetworkInterfacesOperations operations, string resourceGroupName, string networkInterfaceName, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListEffectiveNetworkSecurityGroupsWithHttpMessagesAsync(resourceGroupName, networkInterfaceName, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Gets information about all network interfaces in a virtual machine in a
/// virtual machine scale set.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='virtualMachineScaleSetName'>
/// The name of the virtual machine scale set.
/// </param>
/// <param name='virtualmachineIndex'>
/// The virtual machine index.
/// </param>
public static IPage<NetworkInterface> ListVirtualMachineScaleSetVMNetworkInterfaces(this INetworkInterfacesOperations operations, string resourceGroupName, string virtualMachineScaleSetName, string virtualmachineIndex)
{
return operations.ListVirtualMachineScaleSetVMNetworkInterfacesAsync(resourceGroupName, virtualMachineScaleSetName, virtualmachineIndex).GetAwaiter().GetResult();
}
/// <summary>
/// Gets information about all network interfaces in a virtual machine in a
/// virtual machine scale set.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='virtualMachineScaleSetName'>
/// The name of the virtual machine scale set.
/// </param>
/// <param name='virtualmachineIndex'>
/// The virtual machine index.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<NetworkInterface>> ListVirtualMachineScaleSetVMNetworkInterfacesAsync(this INetworkInterfacesOperations operations, string resourceGroupName, string virtualMachineScaleSetName, string virtualmachineIndex, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListVirtualMachineScaleSetVMNetworkInterfacesWithHttpMessagesAsync(resourceGroupName, virtualMachineScaleSetName, virtualmachineIndex, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Gets all network interfaces in a virtual machine scale set.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='virtualMachineScaleSetName'>
/// The name of the virtual machine scale set.
/// </param>
public static IPage<NetworkInterface> ListVirtualMachineScaleSetNetworkInterfaces(this INetworkInterfacesOperations operations, string resourceGroupName, string virtualMachineScaleSetName)
{
return operations.ListVirtualMachineScaleSetNetworkInterfacesAsync(resourceGroupName, virtualMachineScaleSetName).GetAwaiter().GetResult();
}
/// <summary>
/// Gets all network interfaces in a virtual machine scale set.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='virtualMachineScaleSetName'>
/// The name of the virtual machine scale set.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<NetworkInterface>> ListVirtualMachineScaleSetNetworkInterfacesAsync(this INetworkInterfacesOperations operations, string resourceGroupName, string virtualMachineScaleSetName, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListVirtualMachineScaleSetNetworkInterfacesWithHttpMessagesAsync(resourceGroupName, virtualMachineScaleSetName, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Get the specified network interface in a virtual machine scale set.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='virtualMachineScaleSetName'>
/// The name of the virtual machine scale set.
/// </param>
/// <param name='virtualmachineIndex'>
/// The virtual machine index.
/// </param>
/// <param name='networkInterfaceName'>
/// The name of the network interface.
/// </param>
/// <param name='expand'>
/// Expands referenced resources.
/// </param>
public static NetworkInterface GetVirtualMachineScaleSetNetworkInterface(this INetworkInterfacesOperations operations, string resourceGroupName, string virtualMachineScaleSetName, string virtualmachineIndex, string networkInterfaceName, string expand = default(string))
{
return operations.GetVirtualMachineScaleSetNetworkInterfaceAsync(resourceGroupName, virtualMachineScaleSetName, virtualmachineIndex, networkInterfaceName, expand).GetAwaiter().GetResult();
}
/// <summary>
/// Get the specified network interface in a virtual machine scale set.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='virtualMachineScaleSetName'>
/// The name of the virtual machine scale set.
/// </param>
/// <param name='virtualmachineIndex'>
/// The virtual machine index.
/// </param>
/// <param name='networkInterfaceName'>
/// The name of the network interface.
/// </param>
/// <param name='expand'>
/// Expands referenced resources.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<NetworkInterface> GetVirtualMachineScaleSetNetworkInterfaceAsync(this INetworkInterfacesOperations operations, string resourceGroupName, string virtualMachineScaleSetName, string virtualmachineIndex, string networkInterfaceName, string expand = default(string), CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetVirtualMachineScaleSetNetworkInterfaceWithHttpMessagesAsync(resourceGroupName, virtualMachineScaleSetName, virtualmachineIndex, networkInterfaceName, expand, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Deletes the specified network interface.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='networkInterfaceName'>
/// The name of the network interface.
/// </param>
public static void BeginDelete(this INetworkInterfacesOperations operations, string resourceGroupName, string networkInterfaceName)
{
operations.BeginDeleteAsync(resourceGroupName, networkInterfaceName).GetAwaiter().GetResult();
}
/// <summary>
/// Deletes the specified network interface.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='networkInterfaceName'>
/// The name of the network interface.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task BeginDeleteAsync(this INetworkInterfacesOperations operations, string resourceGroupName, string networkInterfaceName, CancellationToken cancellationToken = default(CancellationToken))
{
(await operations.BeginDeleteWithHttpMessagesAsync(resourceGroupName, networkInterfaceName, null, cancellationToken).ConfigureAwait(false)).Dispose();
}
/// <summary>
/// Creates or updates a network interface.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='networkInterfaceName'>
/// The name of the network interface.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to the create or update network interface operation.
/// </param>
public static NetworkInterface BeginCreateOrUpdate(this INetworkInterfacesOperations operations, string resourceGroupName, string networkInterfaceName, NetworkInterface parameters)
{
return operations.BeginCreateOrUpdateAsync(resourceGroupName, networkInterfaceName, parameters).GetAwaiter().GetResult();
}
/// <summary>
/// Creates or updates a network interface.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='networkInterfaceName'>
/// The name of the network interface.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to the create or update network interface operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<NetworkInterface> BeginCreateOrUpdateAsync(this INetworkInterfacesOperations operations, string resourceGroupName, string networkInterfaceName, NetworkInterface parameters, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.BeginCreateOrUpdateWithHttpMessagesAsync(resourceGroupName, networkInterfaceName, parameters, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Gets all route tables applied to a network interface.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='networkInterfaceName'>
/// The name of the network interface.
/// </param>
public static EffectiveRouteListResult BeginGetEffectiveRouteTable(this INetworkInterfacesOperations operations, string resourceGroupName, string networkInterfaceName)
{
return operations.BeginGetEffectiveRouteTableAsync(resourceGroupName, networkInterfaceName).GetAwaiter().GetResult();
}
/// <summary>
/// Gets all route tables applied to a network interface.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='networkInterfaceName'>
/// The name of the network interface.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<EffectiveRouteListResult> BeginGetEffectiveRouteTableAsync(this INetworkInterfacesOperations operations, string resourceGroupName, string networkInterfaceName, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.BeginGetEffectiveRouteTableWithHttpMessagesAsync(resourceGroupName, networkInterfaceName, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Gets all network security groups applied to a network interface.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='networkInterfaceName'>
/// The name of the network interface.
/// </param>
public static EffectiveNetworkSecurityGroupListResult BeginListEffectiveNetworkSecurityGroups(this INetworkInterfacesOperations operations, string resourceGroupName, string networkInterfaceName)
{
return operations.BeginListEffectiveNetworkSecurityGroupsAsync(resourceGroupName, networkInterfaceName).GetAwaiter().GetResult();
}
/// <summary>
/// Gets all network security groups applied to a network interface.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='networkInterfaceName'>
/// The name of the network interface.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<EffectiveNetworkSecurityGroupListResult> BeginListEffectiveNetworkSecurityGroupsAsync(this INetworkInterfacesOperations operations, string resourceGroupName, string networkInterfaceName, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.BeginListEffectiveNetworkSecurityGroupsWithHttpMessagesAsync(resourceGroupName, networkInterfaceName, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Gets all network interfaces 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<NetworkInterface> ListAllNext(this INetworkInterfacesOperations operations, string nextPageLink)
{
return operations.ListAllNextAsync(nextPageLink).GetAwaiter().GetResult();
}
/// <summary>
/// Gets all network interfaces 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<NetworkInterface>> ListAllNextAsync(this INetworkInterfacesOperations 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 interfaces 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<NetworkInterface> ListNext(this INetworkInterfacesOperations operations, string nextPageLink)
{
return operations.ListNextAsync(nextPageLink).GetAwaiter().GetResult();
}
/// <summary>
/// Gets all network interfaces 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<NetworkInterface>> ListNextAsync(this INetworkInterfacesOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Gets information about all network interfaces in a virtual machine in a
/// virtual machine scale set.
/// </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<NetworkInterface> ListVirtualMachineScaleSetVMNetworkInterfacesNext(this INetworkInterfacesOperations operations, string nextPageLink)
{
return operations.ListVirtualMachineScaleSetVMNetworkInterfacesNextAsync(nextPageLink).GetAwaiter().GetResult();
}
/// <summary>
/// Gets information about all network interfaces in a virtual machine in a
/// virtual machine scale set.
/// </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<NetworkInterface>> ListVirtualMachineScaleSetVMNetworkInterfacesNextAsync(this INetworkInterfacesOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListVirtualMachineScaleSetVMNetworkInterfacesNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Gets all network interfaces in a virtual machine scale set.
/// </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<NetworkInterface> ListVirtualMachineScaleSetNetworkInterfacesNext(this INetworkInterfacesOperations operations, string nextPageLink)
{
return operations.ListVirtualMachineScaleSetNetworkInterfacesNextAsync(nextPageLink).GetAwaiter().GetResult();
}
/// <summary>
/// Gets all network interfaces in a virtual machine scale set.
/// </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<NetworkInterface>> ListVirtualMachineScaleSetNetworkInterfacesNextAsync(this INetworkInterfacesOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListVirtualMachineScaleSetNetworkInterfacesNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Web.Http;
using System.Web.Http.Controllers;
using System.Web.Http.Description;
using ClearScript.Installer.DemoWeb.Areas.HelpPage.ModelDescriptions;
using ClearScript.Installer.DemoWeb.Areas.HelpPage.Models;
namespace ClearScript.Installer.DemoWeb.Areas.HelpPage
{
public static class HelpPageConfigurationExtensions
{
private const string ApiModelPrefix = "MS_HelpPageApiModel_";
/// <summary>
/// Sets the documentation provider for help page.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="documentationProvider">The documentation provider.</param>
public static void SetDocumentationProvider(this HttpConfiguration config, IDocumentationProvider documentationProvider)
{
config.Services.Replace(typeof(IDocumentationProvider), documentationProvider);
}
/// <summary>
/// Sets the objects that will be used by the formatters to produce sample requests/responses.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sampleObjects">The sample objects.</param>
public static void SetSampleObjects(this HttpConfiguration config, IDictionary<Type, object> sampleObjects)
{
config.GetHelpPageSampleGenerator().SampleObjects = sampleObjects;
}
/// <summary>
/// Sets the sample request directly for the specified media type and action.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample request.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, new[] { "*" }), sample);
}
/// <summary>
/// Sets the sample request directly for the specified media type and action with parameters.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample request.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, parameterNames), sample);
}
/// <summary>
/// Sets the sample request directly for the specified media type of the action.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample response.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, new[] { "*" }), sample);
}
/// <summary>
/// Sets the sample response directly for the specified media type of the action with specific parameters.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample response.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, parameterNames), sample);
}
/// <summary>
/// Sets the sample directly for all actions with the specified media type.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample.</param>
/// <param name="mediaType">The media type.</param>
public static void SetSampleForMediaType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType), sample);
}
/// <summary>
/// Sets the sample directly for all actions with the specified type and media type.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="type">The parameter type or return type of an action.</param>
public static void SetSampleForType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, Type type)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, type), sample);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate request samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, new[] { "*" }), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate request samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, parameterNames), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate response samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, new[] { "*" }), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate response samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, parameterNames), type);
}
/// <summary>
/// Gets the help page sample generator.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <returns>The help page sample generator.</returns>
public static HelpPageSampleGenerator GetHelpPageSampleGenerator(this HttpConfiguration config)
{
return (HelpPageSampleGenerator)config.Properties.GetOrAdd(
typeof(HelpPageSampleGenerator),
k => new HelpPageSampleGenerator());
}
/// <summary>
/// Sets the help page sample generator.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sampleGenerator">The help page sample generator.</param>
public static void SetHelpPageSampleGenerator(this HttpConfiguration config, HelpPageSampleGenerator sampleGenerator)
{
config.Properties.AddOrUpdate(
typeof(HelpPageSampleGenerator),
k => sampleGenerator,
(k, o) => sampleGenerator);
}
/// <summary>
/// Gets the model description generator.
/// </summary>
/// <param name="config">The configuration.</param>
/// <returns>The <see cref="ModelDescriptionGenerator"/></returns>
public static ModelDescriptionGenerator GetModelDescriptionGenerator(this HttpConfiguration config)
{
return (ModelDescriptionGenerator)config.Properties.GetOrAdd(
typeof(ModelDescriptionGenerator),
k => InitializeModelDescriptionGenerator(config));
}
/// <summary>
/// Gets the model that represents an API displayed on the help page. The model is initialized on the first call and cached for subsequent calls.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="apiDescriptionId">The <see cref="ApiDescription"/> ID.</param>
/// <returns>
/// An <see cref="HelpPageApiModel"/>
/// </returns>
public static HelpPageApiModel GetHelpPageApiModel(this HttpConfiguration config, string apiDescriptionId)
{
object model;
string modelId = ApiModelPrefix + apiDescriptionId;
if (!config.Properties.TryGetValue(modelId, out model))
{
Collection<ApiDescription> apiDescriptions = config.Services.GetApiExplorer().ApiDescriptions;
ApiDescription apiDescription = apiDescriptions.FirstOrDefault(api => String.Equals(api.GetFriendlyId(), apiDescriptionId, StringComparison.OrdinalIgnoreCase));
if (apiDescription != null)
{
model = GenerateApiModel(apiDescription, config);
config.Properties.TryAdd(modelId, model);
}
}
return (HelpPageApiModel)model;
}
private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HttpConfiguration config)
{
HelpPageApiModel apiModel = new HelpPageApiModel()
{
ApiDescription = apiDescription,
};
ModelDescriptionGenerator modelGenerator = config.GetModelDescriptionGenerator();
HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator();
GenerateUriParameters(apiModel, modelGenerator);
GenerateRequestModelDescription(apiModel, modelGenerator, sampleGenerator);
GenerateResourceDescription(apiModel, modelGenerator);
GenerateSamples(apiModel, sampleGenerator);
return apiModel;
}
private static void GenerateUriParameters(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator)
{
ApiDescription apiDescription = apiModel.ApiDescription;
foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions)
{
if (apiParameter.Source == ApiParameterSource.FromUri)
{
HttpParameterDescriptor parameterDescriptor = apiParameter.ParameterDescriptor;
Type parameterType = null;
ModelDescription typeDescription = null;
ComplexTypeModelDescription complexTypeDescription = null;
if (parameterDescriptor != null)
{
parameterType = parameterDescriptor.ParameterType;
typeDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
complexTypeDescription = typeDescription as ComplexTypeModelDescription;
}
// Example:
// [TypeConverter(typeof(PointConverter))]
// public class Point
// {
// public Point(int x, int y)
// {
// X = x;
// Y = y;
// }
// public int X { get; set; }
// public int Y { get; set; }
// }
// Class Point is bindable with a TypeConverter, so Point will be added to UriParameters collection.
//
// public class Point
// {
// public int X { get; set; }
// public int Y { get; set; }
// }
// Regular complex class Point will have properties X and Y added to UriParameters collection.
if (complexTypeDescription != null
&& !IsBindableWithTypeConverter(parameterType))
{
foreach (ParameterDescription uriParameter in complexTypeDescription.Properties)
{
apiModel.UriParameters.Add(uriParameter);
}
}
else if (parameterDescriptor != null)
{
ParameterDescription uriParameter =
AddParameterDescription(apiModel, apiParameter, typeDescription);
if (!parameterDescriptor.IsOptional)
{
uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Required" });
}
object defaultValue = parameterDescriptor.DefaultValue;
if (defaultValue != null)
{
uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Default value is " + Convert.ToString(defaultValue, CultureInfo.InvariantCulture) });
}
}
else
{
Debug.Assert(parameterDescriptor == null);
// If parameterDescriptor is null, this is an undeclared route parameter which only occurs
// when source is FromUri. Ignored in request model and among resource parameters but listed
// as a simple string here.
ModelDescription modelDescription = modelGenerator.GetOrCreateModelDescription(typeof(string));
AddParameterDescription(apiModel, apiParameter, modelDescription);
}
}
}
}
private static bool IsBindableWithTypeConverter(Type parameterType)
{
if (parameterType == null)
{
return false;
}
return TypeDescriptor.GetConverter(parameterType).CanConvertFrom(typeof(string));
}
private static ParameterDescription AddParameterDescription(HelpPageApiModel apiModel,
ApiParameterDescription apiParameter, ModelDescription typeDescription)
{
ParameterDescription parameterDescription = new ParameterDescription
{
Name = apiParameter.Name,
Documentation = apiParameter.Documentation,
TypeDescription = typeDescription,
};
apiModel.UriParameters.Add(parameterDescription);
return parameterDescription;
}
private static void GenerateRequestModelDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator, HelpPageSampleGenerator sampleGenerator)
{
ApiDescription apiDescription = apiModel.ApiDescription;
foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions)
{
if (apiParameter.Source == ApiParameterSource.FromBody)
{
Type parameterType = apiParameter.ParameterDescriptor.ParameterType;
apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
apiModel.RequestDocumentation = apiParameter.Documentation;
}
else if (apiParameter.ParameterDescriptor != null &&
apiParameter.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage))
{
Type parameterType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription);
if (parameterType != null)
{
apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
}
}
}
}
private static void GenerateResourceDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator)
{
ResponseDescription response = apiModel.ApiDescription.ResponseDescription;
Type responseType = response.ResponseType ?? response.DeclaredType;
if (responseType != null && responseType != typeof(void))
{
apiModel.ResourceDescription = modelGenerator.GetOrCreateModelDescription(responseType);
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")]
private static void GenerateSamples(HelpPageApiModel apiModel, HelpPageSampleGenerator sampleGenerator)
{
try
{
foreach (var item in sampleGenerator.GetSampleRequests(apiModel.ApiDescription))
{
apiModel.SampleRequests.Add(item.Key, item.Value);
LogInvalidSampleAsError(apiModel, item.Value);
}
foreach (var item in sampleGenerator.GetSampleResponses(apiModel.ApiDescription))
{
apiModel.SampleResponses.Add(item.Key, item.Value);
LogInvalidSampleAsError(apiModel, item.Value);
}
}
catch (Exception e)
{
apiModel.ErrorMessages.Add(String.Format(CultureInfo.CurrentCulture,
"An exception has occurred while generating the sample. Exception message: {0}",
HelpPageSampleGenerator.UnwrapException(e).Message));
}
}
private static bool TryGetResourceParameter(ApiDescription apiDescription, HttpConfiguration config, out ApiParameterDescription parameterDescription, out Type resourceType)
{
parameterDescription = apiDescription.ParameterDescriptions.FirstOrDefault(
p => p.Source == ApiParameterSource.FromBody ||
(p.ParameterDescriptor != null && p.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage)));
if (parameterDescription == null)
{
resourceType = null;
return false;
}
resourceType = parameterDescription.ParameterDescriptor.ParameterType;
if (resourceType == typeof(HttpRequestMessage))
{
HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator();
resourceType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription);
}
if (resourceType == null)
{
parameterDescription = null;
return false;
}
return true;
}
private static ModelDescriptionGenerator InitializeModelDescriptionGenerator(HttpConfiguration config)
{
ModelDescriptionGenerator modelGenerator = new ModelDescriptionGenerator(config);
Collection<ApiDescription> apis = config.Services.GetApiExplorer().ApiDescriptions;
foreach (ApiDescription api in apis)
{
ApiParameterDescription parameterDescription;
Type parameterType;
if (TryGetResourceParameter(api, config, out parameterDescription, out parameterType))
{
modelGenerator.GetOrCreateModelDescription(parameterType);
}
}
return modelGenerator;
}
private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample)
{
InvalidSample invalidSample = sample as InvalidSample;
if (invalidSample != null)
{
apiModel.ErrorMessages.Add(invalidSample.ErrorMessage);
}
}
}
}
| |
namespace System
{
[Bridge.Convention(Member = Bridge.ConventionMember.Field | Bridge.ConventionMember.Method, Notation = Bridge.Notation.CamelCase)]
[Bridge.External]
[Bridge.Name("Math")]
public static class Math
{
[Bridge.Convention]
public const double E = 2.7182818284590452354;
[Bridge.Convention]
public const double PI = 3.14159265358979323846;
public static extern int Abs(int x);
public static extern double Abs(double x);
[Bridge.Template("{l}.abs()")]
public static extern long Abs(long l);
[Bridge.Template("{l}.abs()")]
public static extern decimal Abs(decimal l);
/// <summary>
/// Returns the larger of two 8-bit unsigned integers.
/// </summary>
/// <param name="val1">The first of two 8-bit unsigned integers to compare.</param>
/// <param name="val2">The second of two 8-bit unsigned integers to compare.</param>
/// <returns>Parameter val1 or val2, whichever is larger.</returns>
public static extern byte Max(byte val1, byte val2);
/// <summary>
/// Returns the larger of two 8-bit signed integers.
/// </summary>
/// <param name="val1">The first of two 8-bit signed integers to compare.</param>
/// <param name="val2">The second of two 8-bit signed integers to compare.</param>
/// <returns>Parameter val1 or val2, whichever is larger.</returns>
[CLSCompliant(false)]
public static extern sbyte Max(sbyte val1, sbyte val2);
/// <summary>
/// Returns the larger of two 16-bit signed integers.
/// </summary>
/// <param name="val1">The first of two 16-bit signed integers to compare.</param>
/// <param name="val2">The second of two 16-bit signed integers to compare.</param>
/// <returns>Parameter val1 or val2, whichever is larger.</returns>
public static extern short Max(short val1, short val2);
/// <summary>
/// Returns the larger of two 16-bit unsigned integers.
/// </summary>
/// <param name="val1">The first of two 16-bit unsigned integers to compare.</param>
/// <param name="val2">The second of two 16-bit unsigned integers to compare.</param>
/// <returns>Parameter val1 or val2, whichever is larger.</returns>
[CLSCompliant(false)]
public static extern ushort Max(ushort val1, ushort val2);
/// <summary>
/// Returns the larger of two single-precision floating-point numbers.
/// </summary>
/// <param name="val1">The first of two single-precision floating-point numbers to compare.</param>
/// <param name="val2">The second of two single-precision floating-point numbers to compare.</param>
/// <returns>Parameter val1 or val2, whichever is larger.</returns>
public static extern float Max(float val1, float val2);
/// <summary>
/// Returns the larger of two 32-bit signed integers.
/// </summary>
/// <param name="val1">The first of two 32-bit signed integers to compare.</param>
/// <param name="val2">The second of two 32-bit signed integers to compare.</param>
/// <returns>Parameter val1 or val2, whichever is larger.</returns>
public static extern int Max(int val1, int val2);
/// <summary>
/// Returns the larger of two 32-bit unsigned integers.
/// </summary>
/// <param name="val1">The first of two 32-bit unsigned integers to compare.</param>
/// <param name="val2">The second of two 32-bit unsigned integers to compare.</param>
/// <returns>Parameter val1 or val2, whichever is larger.</returns>
[CLSCompliant(false)]
public static extern uint Max(uint val1, uint val2);
/// <summary>
/// Returns the larger of two double-precision floating-point numbers.
/// </summary>
/// <param name="val1">The first of two double-precision floating-point numbers to compare.</param>
/// <param name="val2">The second of two double-precision floating-point numbers to compare.</param>
/// <returns>Parameter val1 or val2, whichever is larger.</returns>
public static extern double Max(double val1, double val2);
/// <summary>
/// Returns the larger of two 64-bit signed integers.
/// </summary>
/// <param name="val1">The first of two 64-bit signed integers to compare.</param>
/// <param name="val2">The second of two 64-bit signed integers to compare.</param>
/// <returns>Parameter val1 or val2, whichever is larger.</returns>
[Bridge.Template("System.Int64.max({val1}, {val2})")]
public static extern long Max(long val1, long val2);
/// <summary>
/// Returns the larger of two 64-bit unsigned integers.
/// </summary>
/// <param name="val1">The first of two 64-bit unsigned integers to compare.</param>
/// <param name="val2">The second of two 64-bit unsigned integers to compare.</param>
/// <returns>Parameter val1 or val2, whichever is larger.</returns>
[Bridge.Template("System.UInt64.max({val1}, {val2})")]
[CLSCompliant(false)]
public static extern ulong Max(ulong val1, ulong val2);
/// <summary>
/// Returns the larger of two decimal numbers.
/// </summary>
/// <param name="val1">The first of two decimal numbers to compare.</param>
/// <param name="val2">The second of two decimal numbers to compare.</param>
/// <returns>Parameter val1 or val2, whichever is larger.</returns>
[Bridge.Template("System.Decimal.max({val1}, {val2})")]
public static extern decimal Max(decimal val1, decimal val2);
/// <summary>
/// Returns the smaller of two 8-bit unsigned integers.
/// </summary>
/// <param name="val1">The first of two 8-bit unsigned integers to compare.</param>
/// <param name="val2">The second of two 8-bit unsigned integers to compare.</param>
/// <returns>Parameter val1 or val2, whichever is smaller.</returns>
public static extern byte Min(byte val1, byte val2);
/// <summary>
/// Returns the smaller of two 8-bit signed integers.
/// </summary>
/// <param name="val1">The first of two 8-bit signed integers to compare.</param>
/// <param name="val2">The second of two 8-bit signed integers to compare.</param>
/// <returns>Parameter val1 or val2, whichever is smaller.</returns>
[CLSCompliant(false)]
public static extern sbyte Min(sbyte val1, sbyte val2);
/// <summary>
/// Returns the smaller of two 16-bit signed integers.
/// </summary>
/// <param name="val1">The first of two 16-bit signed integers to compare.</param>
/// <param name="val2">The second of two 16-bit signed integers to compare.</param>
/// <returns>Parameter val1 or val2, whichever is smaller.</returns>
public static extern short Min(short val1, short val2);
/// <summary>
/// Returns the smaller of two 16-bit unsigned integers.
/// </summary>
/// <param name="val1">The first of two 16-bit unsigned integers to compare.</param>
/// <param name="val2">The second of two 16-bit unsigned integers to compare.</param>
/// <returns>Parameter val1 or val2, whichever is smaller.</returns>
[CLSCompliant(false)]
public static extern ushort Min(ushort val1, ushort val2);
/// <summary>
/// Returns the smaller of two single-precision floating-point numbers.
/// </summary>
/// <param name="val1">The first of two single-precision floating-point numbers to compare.</param>
/// <param name="val2">The second of two single-precision floating-point numbers to compare.</param>
/// <returns>Parameter val1 or val2, whichever is smaller.</returns>
public static extern float Min(float val1, float val2);
/// <summary>
/// Returns the smaller of two 32-bit signed integers.
/// </summary>
/// <param name="val1">The first of two 32-bit signed integers to compare.</param>
/// <param name="val2">The second of two 32-bit signed integers to compare.</param>
/// <returns>Parameter val1 or val2, whichever is smaller.</returns>
public static extern int Min(int val1, int val2);
/// <summary>
/// Returns the smaller of two 32-bit unsigned integers.
/// </summary>
/// <param name="val1">The first of two 32-bit unsigned integers to compare.</param>
/// <param name="val2">The second of two 32-bit unsigned integers to compare.</param>
/// <returns>Parameter val1 or val2, whichever is smaller.</returns>
[CLSCompliant(false)]
public static extern uint Min(uint val1, uint val2);
/// <summary>
/// Returns the smaller of two double-precision floating-point numbers.
/// </summary>
/// <param name="val1">The first of two double-precision floating-point numbers to compare.</param>
/// <param name="val2">The second of two double-precision floating-point numbers to compare.</param>
/// <returns>Parameter val1 or val2, whichever is smaller.</returns>
public static extern double Min(double val1, double val2);
/// <summary>
/// Returns the smaller of two 64-bit signed integers.
/// </summary>
/// <param name="val1">The first of two 64-bit signed integers to compare.</param>
/// <param name="val2">The second of two 64-bit signed integers to compare.</param>
/// <returns>Parameter val1 or val2, whichever is smaller.</returns>
[Bridge.Template("System.Int64.min({val1}, {val2})")]
public static extern long Min(long val1, long val2);
/// <summary>
/// Returns the smaller of two 64-bit unsigned integers.
/// </summary>
/// <param name="val1">The first of two 64-bit unsigned integers to compare.</param>
/// <param name="val2">The second of two 64-bit unsigned integers to compare.</param>
/// <returns>Parameter val1 or val2, whichever is smaller.</returns>
[Bridge.Template("System.UInt64.min({val1}, {val2})")]
[CLSCompliant(false)]
public static extern ulong Min(ulong val1, ulong val2);
/// <summary>
/// Returns the smaller of two decimal numbers.
/// </summary>
/// <param name="val1">The first of two decimal numbers to compare.</param>
/// <param name="val2">The second of two decimal numbers to compare.</param>
/// <returns>Parameter val1 or val2, whichever is smaller.</returns>
[Bridge.Template("System.Decimal.min({val1}, {val2})")]
public static extern decimal Min(decimal val1, decimal val2);
public static extern double Random();
public static extern double Sqrt(double x);
[Bridge.Template("{d}.ceil()")]
public static extern decimal Ceiling(decimal d);
[Bridge.Name("ceil")]
public static extern double Ceiling(double d);
public static extern double Floor(double x);
[Bridge.Template("{d}.floor()")]
public static extern decimal Floor(decimal d);
[Bridge.Template("System.Decimal.round({x}, 6)")]
public static extern decimal Round(decimal x);
[Bridge.Template("Bridge.Math.round({d}, 0, 6)")]
public static extern double Round(double d);
[Bridge.Template("Math.round({d})")]
public static extern double JsRound(double d);
[Bridge.Template("System.Decimal.toDecimalPlaces({d}, {digits}, 6)")]
public static extern decimal Round(decimal d, int digits);
[Bridge.Template("Bridge.Math.round({d}, {digits}, 6)")]
public static extern double Round(double d, int digits);
[Bridge.Template("System.Decimal.round({d}, {method})")]
public static extern decimal Round(decimal d, MidpointRounding method);
[Bridge.Template("Bridge.Math.round({d}, 0, {method})")]
public static extern double Round(double d, MidpointRounding method);
[Bridge.Template("System.Decimal.toDecimalPlaces({d}, {digits}, {method})")]
public static extern decimal Round(decimal d, int digits, MidpointRounding method);
[Bridge.Template("Bridge.Math.round({d}, {digits}, {method})")]
public static extern double Round(double d, int digits, MidpointRounding method);
[Bridge.Template("Bridge.Math.IEEERemainder({x}, {y})")]
public static extern double IEEERemainder(double x, double y);
public static extern double Exp(double x);
[Bridge.Template("{x}.exponential()")]
public static extern decimal Exp(decimal x);
[Bridge.Template("Bridge.Math.log({x})")]
public static extern double Log(double x);
[Bridge.Template("Bridge.Math.logWithBase({x}, {logBase})")]
public static extern double Log(double x, double logBase);
[Bridge.Template("Bridge.Math.logWithBase({x}, 10.0)")]
public static extern double Log10(double x);
[Bridge.Template("{x}.pow({y})")]
public static extern decimal Pow(decimal x, decimal y);
public static extern double Pow(double x, double y);
public static extern double Pow(int x, int y);
public static extern double Acos(double x);
public static extern double Asin(double x);
public static extern double Atan(double x);
public static extern double Atan2(double y, double x);
public static extern double Cos(double x);
public static extern double Sin(double x);
public static extern double Tan(double x);
[Bridge.Template("Bridge.Int.trunc({d})")]
public static extern double Truncate(double d);
[Bridge.Template("{d}.trunc()")]
public static extern decimal Truncate(decimal d);
[Bridge.Template("Bridge.Int.sign({value})")]
public static extern int Sign(double value);
[Bridge.Template("{value}.sign()")]
public static extern int Sign(decimal value);
[Bridge.Template("Bridge.Math.divRem({a}, {b}, {result})")]
public static extern int DivRem(int a, int b, out int result);
[Bridge.Template("System.Int64.divRem({a}, {b}, {result})")]
public static extern long DivRem(long a, long b, out long result);
[Bridge.Template("Bridge.Math.sinh({value})")]
public static extern double Sinh(double value);
[Bridge.Template("Bridge.Math.cosh({value})")]
public static extern double Cosh(double value);
[Bridge.Template("Bridge.Math.tanh({value})")]
public static extern double Tanh(double value);
}
}
| |
// Copyright Naked Objects Group Ltd, 45 Station Road, Henley on Thames, UK, RG9 1AT
// 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.Collections.Immutable;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
using NakedFramework;
using NakedFramework.Architecture.Adapter;
using NakedFramework.Architecture.Component;
using NakedFramework.Architecture.Facet;
using NakedFramework.Architecture.Reflect;
using NakedFramework.Architecture.SpecImmutable;
using NakedObjects.Reflector.Facet;
using NakedObjects.Reflector.FacetFactory;
// ReSharper disable UnusedMember.Global
// ReSharper disable UnusedMember.Local
namespace NakedObjects.Reflector.Test.FacetFactory;
[TestClass]
public class ViewModelFacetFactoryTest : AbstractFacetFactoryTest {
private ViewModelFacetFactory facetFactory;
protected override Type[] SupportedTypes => new[] { typeof(IViewModelFacet) };
protected override IFacetFactory FacetFactory => facetFactory;
[TestMethod]
public override void TestFeatureTypes() {
var featureTypes = facetFactory.FeatureTypes;
Assert.IsTrue(featureTypes.HasFlag(FeatureType.Objects));
Assert.IsFalse(featureTypes.HasFlag(FeatureType.Properties));
Assert.IsFalse(featureTypes.HasFlag(FeatureType.Collections));
Assert.IsFalse(featureTypes.HasFlag(FeatureType.Actions));
Assert.IsFalse(featureTypes.HasFlag(FeatureType.ActionParameters));
}
[TestMethod]
public void TestViewModelDerive() {
IImmutableDictionary<string, ITypeSpecBuilder> metamodel = new Dictionary<string, ITypeSpecBuilder>().ToImmutableDictionary();
metamodel = facetFactory.Process(Reflector, typeof(Class1), MethodRemover, Specification, metamodel);
var facet = Specification.GetFacet<IViewModelFacet>();
Assert.IsNotNull(facet);
var testClass = new Class1 { Value1 = "testValue1", Value2 = "testValue2" };
var mock = new Mock<INakedObjectAdapter>();
var value = mock.Object;
mock.Setup(no => no.Object).Returns(testClass);
var key = facet.Derive(value, null);
Assert.AreEqual(2, key.Length);
Assert.AreEqual(testClass.Value1, key[0]);
Assert.AreEqual(testClass.Value2, key[1]);
Assert.IsNotNull(metamodel);
}
[TestMethod]
public void TestViewModelNotPickedUp() {
IImmutableDictionary<string, ITypeSpecBuilder> metamodel = new Dictionary<string, ITypeSpecBuilder>().ToImmutableDictionary();
metamodel = facetFactory.Process(Reflector, typeof(Class2), MethodRemover, Specification, metamodel);
var facet = Specification.GetFacet(typeof(IViewModelFacet));
Assert.IsNull(facet);
Assert.IsNotNull(metamodel);
}
[TestMethod]
public void TestViewModelPickedUp() {
IImmutableDictionary<string, ITypeSpecBuilder> metamodel = new Dictionary<string, ITypeSpecBuilder>().ToImmutableDictionary();
var class1Type = typeof(Class1);
metamodel = facetFactory.Process(Reflector, class1Type, MethodRemover, Specification, metamodel);
var facet = Specification.GetFacet(typeof(IViewModelFacet));
Assert.IsNotNull(facet);
Assert.IsTrue(facet is ViewModelFacetConvention);
var m1 = class1Type.GetMethod("DeriveKeys");
var m2 = class1Type.GetMethod("PopulateUsingKeys");
AssertMethodsRemoved(new[] { m1, m2 });
Assert.IsNotNull(metamodel);
}
[TestMethod]
public void TestViewModelEditPickedUp() {
IImmutableDictionary<string, ITypeSpecBuilder> metamodel = new Dictionary<string, ITypeSpecBuilder>().ToImmutableDictionary();
var class3Type = typeof(Class3);
metamodel = facetFactory.Process(Reflector, class3Type, MethodRemover, Specification, metamodel);
var facet = Specification.GetFacet(typeof(IViewModelFacet));
Assert.IsNotNull(facet);
Assert.IsTrue(facet is ViewModelEditFacetConvention);
var m1 = class3Type.GetMethod("DeriveKeys");
var m2 = class3Type.GetMethod("PopulateUsingKeys");
AssertMethodsRemoved(new[] { m1, m2 });
Assert.IsNotNull(metamodel);
}
[TestMethod]
public void TestViewModelSwitchablePickedUp() {
IImmutableDictionary<string, ITypeSpecBuilder> metamodel = new Dictionary<string, ITypeSpecBuilder>().ToImmutableDictionary();
var class4Type = typeof(Class4);
metamodel = facetFactory.Process(Reflector, class4Type, MethodRemover, Specification, metamodel);
var facet = Specification.GetFacet(typeof(IViewModelFacet));
Assert.IsNotNull(facet);
Assert.IsTrue(facet is ViewModelSwitchableFacetConvention);
var m1 = class4Type.GetMethod("DeriveKeys");
var m2 = class4Type.GetMethod("PopulateUsingKeys");
var m3 = class4Type.GetMethod("IsEditView");
AssertMethodsRemoved(new[] { m1, m2, m3 });
Assert.IsNotNull(metamodel);
}
[TestMethod]
public void TestViewModelPopulate() {
IImmutableDictionary<string, ITypeSpecBuilder> metamodel = new Dictionary<string, ITypeSpecBuilder>().ToImmutableDictionary();
metamodel = facetFactory.Process(Reflector, typeof(Class1), MethodRemover, Specification, metamodel);
var facet = Specification.GetFacet<IViewModelFacet>();
Assert.IsNotNull(facet);
var testClass = new Class1();
var keys = new[] { "testValue1", "testValue2" };
var mock = new Mock<INakedObjectAdapter>();
var value = mock.Object;
mock.Setup(no => no.Object).Returns(testClass);
facet.Populate(keys, value, null);
Assert.AreEqual(keys[0], testClass.Value1);
Assert.AreEqual(keys[1], testClass.Value2);
Assert.IsNotNull(metamodel);
}
#region Nested type: Class1
private class Class1 : IViewModel {
public string Value1 { get; set; }
public string Value2 { get; set; }
#region IViewModel Members
public string[] DeriveKeys() {
return new[] { Value1, Value2 };
}
public void PopulateUsingKeys(string[] instanceId) {
Value1 = instanceId[0];
Value2 = instanceId[1];
}
#endregion
}
#endregion
#region Nested type: Class2
private class Class2 {
// ReSharper disable once UnusedMember.Local
public string[] DeriveKeys() => null;
// ReSharper disable once UnusedMember.Local
// ReSharper disable once UnusedParameter.Local
public void PopulateUsingKeys(string[] instanceId) { }
}
#endregion
#region Nested type: Class3
private class Class3 : IViewModelEdit {
private string Value1 { get; set; }
private string Value2 { get; set; }
#region IViewModelEdit Members
public string[] DeriveKeys() {
return new[] { Value1, Value2 };
}
public void PopulateUsingKeys(string[] instanceId) {
Value1 = instanceId[0];
Value2 = instanceId[1];
}
#endregion
}
#endregion
#region Nested type: Class4
private class Class4 : IViewModelSwitchable {
private string Value1 { get; set; }
private string Value2 { get; set; }
#region IViewModelSwitchable Members
public string[] DeriveKeys() {
return new[] { Value1, Value2 };
}
public void PopulateUsingKeys(string[] instanceId) {
Value1 = instanceId[0];
Value2 = instanceId[1];
}
public bool IsEditView() => false;
#endregion
}
#endregion
#region Setup/Teardown
[TestInitialize]
public override void SetUp() {
base.SetUp();
facetFactory = new ViewModelFacetFactory(GetOrder<ViewModelFacetFactory>(), LoggerFactory);
}
[TestCleanup]
public new void TearDown() {
facetFactory = null;
base.TearDown();
}
#endregion
}
| |
/*
* Swaggy Jenkins
*
* Jenkins API clients generated from Swagger / Open API specification
*
* The version of the OpenAPI document: 1.1.2-pre.0
* Contact: blah@cliffano.com
* Generated by: https://github.com/openapitools/openapi-generator.git
*/
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.IO;
using System.Runtime.Serialization;
using System.Text;
using System.Text.RegularExpressions;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json.Linq;
using System.ComponentModel.DataAnnotations;
using OpenAPIDateConverter = Org.OpenAPITools.Client.OpenAPIDateConverter;
namespace Org.OpenAPITools.Models
{
/// <summary>
/// GenericResource
/// </summary>
[DataContract(Name = "GenericResource")]
public partial class GenericResource : IEquatable<GenericResource>, IValidatableObject
{
/// <summary>
/// Initializes a new instance of the <see cref="GenericResource" /> class.
/// </summary>
/// <param name="_class">_class.</param>
/// <param name="displayName">displayName.</param>
/// <param name="durationInMillis">durationInMillis.</param>
/// <param name="id">id.</param>
/// <param name="result">result.</param>
/// <param name="startTime">startTime.</param>
public GenericResource(string _class = default(string), string displayName = default(string), int durationInMillis = default(int), string id = default(string), string result = default(string), string startTime = default(string))
{
this.Class = _class;
this.DisplayName = displayName;
this.DurationInMillis = durationInMillis;
this.Id = id;
this.Result = result;
this.StartTime = startTime;
}
/// <summary>
/// Gets or Sets Class
/// </summary>
[DataMember(Name = "_class", EmitDefaultValue = false)]
public string Class { get; set; }
/// <summary>
/// Gets or Sets DisplayName
/// </summary>
[DataMember(Name = "displayName", EmitDefaultValue = false)]
public string DisplayName { get; set; }
/// <summary>
/// Gets or Sets DurationInMillis
/// </summary>
[DataMember(Name = "durationInMillis", EmitDefaultValue = false)]
public int DurationInMillis { get; set; }
/// <summary>
/// Gets or Sets Id
/// </summary>
[DataMember(Name = "id", EmitDefaultValue = false)]
public string Id { get; set; }
/// <summary>
/// Gets or Sets Result
/// </summary>
[DataMember(Name = "result", EmitDefaultValue = false)]
public string Result { get; set; }
/// <summary>
/// Gets or Sets StartTime
/// </summary>
[DataMember(Name = "startTime", EmitDefaultValue = false)]
public string StartTime { get; set; }
/// <summary>
/// Returns the string presentation of the object
/// </summary>
/// <returns>String presentation of the object</returns>
public override string ToString()
{
var sb = new StringBuilder();
sb.Append("class GenericResource {\n");
sb.Append(" Class: ").Append(Class).Append("\n");
sb.Append(" DisplayName: ").Append(DisplayName).Append("\n");
sb.Append(" DurationInMillis: ").Append(DurationInMillis).Append("\n");
sb.Append(" Id: ").Append(Id).Append("\n");
sb.Append(" Result: ").Append(Result).Append("\n");
sb.Append(" StartTime: ").Append(StartTime).Append("\n");
sb.Append("}\n");
return sb.ToString();
}
/// <summary>
/// Returns the JSON string presentation of the object
/// </summary>
/// <returns>JSON string presentation of the object</returns>
public virtual string ToJson()
{
return Newtonsoft.Json.JsonConvert.SerializeObject(this, Newtonsoft.Json.Formatting.Indented);
}
/// <summary>
/// Returns true if objects are equal
/// </summary>
/// <param name="input">Object to be compared</param>
/// <returns>Boolean</returns>
public override bool Equals(object input)
{
return this.Equals(input as GenericResource);
}
/// <summary>
/// Returns true if GenericResource instances are equal
/// </summary>
/// <param name="input">Instance of GenericResource to be compared</param>
/// <returns>Boolean</returns>
public bool Equals(GenericResource input)
{
if (input == null)
return false;
return
(
this.Class == input.Class ||
(this.Class != null &&
this.Class.Equals(input.Class))
) &&
(
this.DisplayName == input.DisplayName ||
(this.DisplayName != null &&
this.DisplayName.Equals(input.DisplayName))
) &&
(
this.DurationInMillis == input.DurationInMillis ||
this.DurationInMillis.Equals(input.DurationInMillis)
) &&
(
this.Id == input.Id ||
(this.Id != null &&
this.Id.Equals(input.Id))
) &&
(
this.Result == input.Result ||
(this.Result != null &&
this.Result.Equals(input.Result))
) &&
(
this.StartTime == input.StartTime ||
(this.StartTime != null &&
this.StartTime.Equals(input.StartTime))
);
}
/// <summary>
/// Gets the hash code
/// </summary>
/// <returns>Hash code</returns>
public override int GetHashCode()
{
unchecked // Overflow is fine, just wrap
{
int hashCode = 41;
if (this.Class != null)
hashCode = hashCode * 59 + this.Class.GetHashCode();
if (this.DisplayName != null)
hashCode = hashCode * 59 + this.DisplayName.GetHashCode();
hashCode = hashCode * 59 + this.DurationInMillis.GetHashCode();
if (this.Id != null)
hashCode = hashCode * 59 + this.Id.GetHashCode();
if (this.Result != null)
hashCode = hashCode * 59 + this.Result.GetHashCode();
if (this.StartTime != null)
hashCode = hashCode * 59 + this.StartTime.GetHashCode();
return hashCode;
}
}
/// <summary>
/// To validate all properties of the instance
/// </summary>
/// <param name="validationContext">Validation context</param>
/// <returns>Validation Result</returns>
IEnumerable<System.ComponentModel.DataAnnotations.ValidationResult> IValidatableObject.Validate(ValidationContext validationContext)
{
yield break;
}
}
}
| |
/*******************************************************************************
INTEL CORPORATION PROPRIETARY INFORMATION
This software is supplied under the terms of a license agreement or nondisclosure
agreement with Intel Corporation and may not be copied or disclosed except in
accordance with the terms of that agreement
Copyright(c) 2012-2014 Intel Corporation. All Rights Reserved.
*******************************************************************************/
using UnityEngine;
using System.Collections;
namespace RSUnityToolkit
{
/// <summary>
/// Hand tracking rule - Processes Track Triggers
/// </summary>
[AddComponentMenu("")]
[TrackTrigger.TrackTriggerAtt]
public class HandTrackingRule : BaseRule
{
#region Public Fields
/// <summary>
/// Which hand to track
/// </summary>
public PXCMHandData.AccessOrderType WhichHand = PXCMHandData.AccessOrderType.ACCESS_ORDER_NEAR_TO_FAR;
/// <summary>
/// The index of the hand.
/// </summary>
public int HandIndex = 0;
/// <summary>
/// the index of the hand can change once more hands are visible. Should continuously track the detected hand no matter its' index
/// </summary>
public bool ContinuousTracking = false;
/// <summary>
/// The tracked joint.
/// </summary>
public PXCMHandData.JointType TrackedJoint = PXCMHandData.JointType.JOINT_WRIST;
/// <summary>
/// The real world box center. In centimiters.
/// </summary>
public Vector3 RealWorldBoxCenter = new Vector3(0, 0, 50);
/// <summary>
/// The real world box dimensions. In Centimiters.
/// </summary>
public Vector3 RealWorldBoxDimensions = new Vector3(100, 100, 100);
#endregion
#region Private Fields
private int _uniqueID = -1;
private Quaternion _zInvert = new Quaternion(0, 0, 1, 0f);
private Quaternion _yInvert = new Quaternion(0, 1, 0, 0f);
#endregion
#region C'tors
public HandTrackingRule(): base()
{
FriendlyName = "Hand Tracking";
}
#endregion
#region Public Methods
override public string GetIconPath()
{
return @"RulesIcons/hand-tracking";
}
override public string GetRuleDescription()
{
return "Track hand joint's position and orientation";
}
protected override bool OnRuleEnabled()
{
SenseToolkitManager.Instance.SetSenseOption(SenseOption.SenseOptionID.Hand);
return true;
}
protected override void OnRuleDisabled()
{
SenseToolkitManager.Instance.UnsetSenseOption(SenseOption.SenseOptionID.Hand);
}
public override bool Process(Trigger trigger)
{
trigger.ErrorDetected = false;
if (!SenseToolkitManager.Instance.IsSenseOptionSet(SenseOption.SenseOptionID.Hand))
{
trigger.ErrorDetected = true;
Debug.LogError("Hand Analysis Module Not Set");
return false;
}
if (!(trigger is TrackTrigger))
{
trigger.ErrorDetected = true;
return false;
}
bool success = false;
// make sure we have valid values
if (RealWorldBoxDimensions.x <= 0)
{
RealWorldBoxDimensions.x = 1;
}
if (RealWorldBoxDimensions.y <= 0)
{
RealWorldBoxDimensions.y = 1;
}
if (RealWorldBoxDimensions.z <= 0)
{
RealWorldBoxDimensions.z = 1;
}
if (SenseToolkitManager.Instance.Initialized && SenseToolkitManager.Instance.HandDataOutput != null)
{
PXCMHandData.IHand data = null;
if (SenseToolkitManager.Instance.HandDataOutput.QueryNumberOfHands() > 0 &&
((ContinuousTracking && SenseToolkitManager.Instance.HandDataOutput.QueryHandDataById (_uniqueID, out data) >= pxcmStatus.PXCM_STATUS_NO_ERROR)
||
SenseToolkitManager.Instance.HandDataOutput.QueryHandData(WhichHand, HandIndex, out data) >= pxcmStatus.PXCM_STATUS_NO_ERROR)
)
{
// Process Tracking
_uniqueID = data.QueryUniqueId();
PXCMHandData.JointData jointData;
data.QueryTrackedJoint(TrackedJoint, out jointData);
TrackTrigger specificTrigger = (TrackTrigger)trigger;
PXCMPoint3DF32 point = jointData.positionWorld;
Vector3 position = new Vector3(point.x, point.y, point.z);
position.x *= -100;
position.y *= 100;
position.z *= 100;
if ( position.x + position.y + position.z == 0)
{
return false;
}
TrackingUtilityClass.ClampToRealWorldInputBox(ref position, RealWorldBoxCenter, RealWorldBoxDimensions);
TrackingUtilityClass.Normalize(ref position, RealWorldBoxCenter, RealWorldBoxDimensions);
if (!float.IsNaN(position.x) && !float.IsNaN(position.y) && !float.IsNaN(position.z))
{
specificTrigger.Position = position;
}
else
{
return false;
}
Quaternion q = new Quaternion(jointData.globalOrientation.x, jointData.globalOrientation.y,
jointData.globalOrientation.z, jointData.globalOrientation.w);
q = q * _zInvert * _yInvert;
specificTrigger.RotationQuaternion = q;
success = true;
}
}
else
{
return false;
}
return success;
}
#endregion
}
}
| |
#if UNITY_4_2 || UNITY_4_1 || UNITY_4_0 || UNITY_3_5 || UNITY_3_4 || UNITY_3_3
#define UNITY_LE_4_3
#endif
using Pathfinding;
using UnityEditor;
using UnityEngine;
namespace Pathfinding {
public class GraphEditor : GraphEditorBase {
public AstarPathEditor editor;
public virtual void OnEnable () {
}
public virtual void OnDisable () {
}
public virtual void OnDestroy () {
}
public Object ObjectField (string label, Object obj, System.Type objType, bool allowSceneObjects) {
return ObjectField (new GUIContent (label),obj,objType,allowSceneObjects);
}
public Object ObjectField (GUIContent label, Object obj, System.Type objType, bool allowSceneObjects) {
#if UNITY_3_3
allowSceneObjects = true;
#endif
#if UNITY_3_3
obj = EditorGUILayout.ObjectField (label, obj, objType);
#else
obj = EditorGUILayout.ObjectField (label, obj, objType, allowSceneObjects);
#endif
if (obj != null) {
if (allowSceneObjects && !EditorUtility.IsPersistent (obj)) {
//Object is in the scene
Component com = obj as Component;
GameObject go = obj as GameObject;
if (com != null) {
go = com.gameObject;
}
if (go != null) {
UnityReferenceHelper urh = go.GetComponent<UnityReferenceHelper> ();
if (urh == null) {
if (FixLabel ("Object's GameObject must have a UnityReferenceHelper component attached")) {
go.AddComponent<UnityReferenceHelper>();
}
}
}
} else if (EditorUtility.IsPersistent (obj)) {
string path = AssetDatabase.GetAssetPath (obj);
System.Text.RegularExpressions.Regex rg = new System.Text.RegularExpressions.Regex(@"Resources[/|\\][^/]*$");
if (!rg.IsMatch(path)) {
if (FixLabel ("Object must be in the 'Resources' folder, top level")) {
if (!System.IO.Directory.Exists (Application.dataPath+"/Resources")) {
System.IO.Directory.CreateDirectory (Application.dataPath+"/Resources");
AssetDatabase.Refresh ();
}
string ext = System.IO.Path.GetExtension(path);
string error = AssetDatabase.MoveAsset (path,"Assets/Resources/"+obj.name+ext);
if (error == "") {
//Debug.Log ("Successful move");
path = AssetDatabase.GetAssetPath (obj);
} else {
Debug.LogError ("Couldn't move asset - "+error);
}
}
}
if (!AssetDatabase.IsMainAsset (obj) && obj.name != AssetDatabase.LoadMainAssetAtPath (path).name) {
if (FixLabel ("Due to technical reasons, the main asset must\nhave the same name as the referenced asset")) {
string error = AssetDatabase.RenameAsset (path,obj.name);
if (error == "") {
//Debug.Log ("Successful");
} else {
Debug.LogError ("Couldn't rename asset - "+error);
}
}
}
}
}
return obj;
}
/** Draws common graph settings */
public void OnBaseInspectorGUI (NavGraph target) {
int penalty = EditorGUILayout.IntField (new GUIContent ("Initial Penalty","Initial Penalty for nodes in this graph. Set during Scan."),(int)target.initialPenalty);
if (penalty < 0) penalty = 0;
target.initialPenalty = (uint)penalty;
}
/** Override to implement graph inspectors */
public virtual void OnInspectorGUI (NavGraph target) {
}
/** Override to implement scene GUI drawing for the graph */
public virtual void OnSceneGUI (NavGraph target) {
}
/** Override to implement scene Gizmos drawing for the graph editor */
public virtual void OnDrawGizmos () {
}
/** Draws a thin separator line */
public void Separator () {
GUIStyle separator = AstarPathEditor.astarSkin.FindStyle ("PixelBox3Separator");
if (separator == null) {
separator = new GUIStyle ();
}
Rect r = GUILayoutUtility.GetRect (new GUIContent (),separator);
if (Event.current.type == EventType.Repaint) {
separator.Draw (r,false,false,false,false);
}
}
/** Draws a small help box with a 'Fix' button to the right. \returns Boolean - Returns true if the button was clicked */
public bool FixLabel (string label, string buttonLabel = "Fix", int buttonWidth = 40) {
bool returnValue = false;
GUILayout.BeginHorizontal ();
GUILayout.Space (14*EditorGUI.indentLevel);
GUILayout.BeginHorizontal (AstarPathEditor.helpBox);
GUILayout.Label (label, EditorStyles.miniLabel,GUILayout.ExpandWidth (true));
if (GUILayout.Button (buttonLabel,EditorStyles.miniButton,GUILayout.Width (buttonWidth))) {
returnValue = true;
}
GUILayout.EndHorizontal ();
GUILayout.EndHorizontal ();
return returnValue;
}
/** Draws a small help box. Works with EditorGUI.indentLevel */
public void HelpBox (string label) {
GUILayout.BeginHorizontal ();
GUILayout.Space (14*EditorGUI.indentLevel);
GUILayout.Label (label, AstarPathEditor.helpBox);
GUILayout.EndHorizontal ();
}
/** Draws a toggle with a bold label to the right. Does not enable or disable GUI */
public bool ToggleGroup (string label, bool value) {
return ToggleGroup (new GUIContent (label),value);
}
/** Draws a toggle with a bold label to the right. Does not enable or disable GUI */
public bool ToggleGroup (GUIContent label, bool value) {
GUILayout.BeginHorizontal ();
GUILayout.Space (13*EditorGUI.indentLevel);
value = GUILayout.Toggle (value,"",GUILayout.Width (10));
GUIStyle boxHeader = AstarPathEditor.astarSkin.FindStyle ("CollisionHeader");
if (GUILayout.Button (label,boxHeader, GUILayout.Width (100))) {
value = !value;
}
GUILayout.EndHorizontal ();
return value;
}
/** Draws the inspector for a \link Pathfinding.GraphCollision GraphCollision class \endlink */
public void DrawCollisionEditor (GraphCollision collision) {
if (collision == null) {
collision = new GraphCollision ();
}
/*GUILayout.Space (5);
Rect r = EditorGUILayout.BeginVertical (AstarPathEditor.graphBoxStyle);
GUI.Box (r,"",AstarPathEditor.graphBoxStyle);
GUILayout.Space (2);*/
Separator ();
collision.use2D = EditorGUILayout.Toggle (new GUIContent ("Use 2D Physics", "Use the Physics2D API for collision checking"), collision.use2D );
#if UNITY_LE_4_3
if ( collision.use2D ) EditorGUILayout.HelpBox ("2D Physics is only supported from Unity 4.3 and up", MessageType.Error);
#endif
/*GUILayout.BeginHorizontal ();
GUIStyle boxHeader = AstarPathEditor.astarSkin.FindStyle ("CollisionHeader");
GUILayout.Label ("Collision testing",boxHeader);
collision.collisionCheck = GUILayout.Toggle (collision.collisionCheck,"");
bool preEnabledRoot = GUI.enabled;
GUI.enabled = collision.collisionCheck;
GUILayout.EndHorizontal ();*/
collision.collisionCheck = ToggleGroup ("Collision testing",collision.collisionCheck);
bool preEnabledRoot = GUI.enabled;
GUI.enabled = collision.collisionCheck;
//GUILayout.BeginHorizontal ();
collision.type = (ColliderType)EditorGUILayout.EnumPopup("Collider type",collision.type);
//new string[3] {"Sphere","Capsule","Ray"}
bool preEnabled = GUI.enabled;
if (collision.type != ColliderType.Capsule && collision.type != ColliderType.Sphere) {
GUI.enabled = false;
}
collision.diameter = EditorGUILayout.FloatField (new GUIContent ("Diameter","Diameter of the capsule or sphere. 1 equals one node width"),collision.diameter);
GUI.enabled = preEnabled;
if (collision.type != ColliderType.Capsule && collision.type != ColliderType.Ray) {
GUI.enabled = false;
}
collision.height = EditorGUILayout.FloatField (new GUIContent ("Height/Length","Height of cylinder or length of ray in world units"),collision.height);
GUI.enabled = preEnabled;
collision.collisionOffset = EditorGUILayout.FloatField (new GUIContent("Offset","Offset upwards from the node. Can be used so that obstacles can be used as ground and at the same time as obstacles for lower positioned nodes"),collision.collisionOffset);
//collision.mask = 1 << EditorGUILayout.LayerField ("Mask",Mathf.Clamp ((int)Mathf.Log (collision.mask,2),0,31));
collision.mask = EditorGUILayoutx.LayerMaskField ("Mask",collision.mask);
GUILayout.Space (2);
GUI.enabled = preEnabledRoot;
if ( collision.use2D ) {
GUI.enabled = false;
}
collision.heightCheck = ToggleGroup ("Height testing",collision.heightCheck);
GUI.enabled = collision.heightCheck && GUI.enabled;
/*GUILayout.BeginHorizontal ();
GUILayout.Label ("Height testing",boxHeader);
collision.heightCheck = GUILayout.Toggle (collision.heightCheck,"");
GUI.enabled = collision.heightCheck;
GUILayout.EndHorizontal ();*/
collision.fromHeight = EditorGUILayout.FloatField (new GUIContent ("Ray length","The height from which to check for ground"),collision.fromHeight);
collision.heightMask = EditorGUILayoutx.LayerMaskField ("Mask",collision.heightMask);
//collision.heightMask = 1 << EditorGUILayout.LayerField ("Mask",Mathf.Clamp ((int)Mathf.Log (collision.heightMask,2),0,31));
collision.thickRaycast = EditorGUILayout.Toggle (new GUIContent ("Thick Raycast", "Use a thick line instead of a thin line"),collision.thickRaycast);
editor.GUILayoutx.BeginFadeArea (collision.thickRaycast,"thickRaycastDiameter");
if (editor.GUILayoutx.DrawID ("thickRaycastDiameter")) {
EditorGUI.indentLevel++;
collision.thickRaycastDiameter = EditorGUILayout.FloatField (new GUIContent ("Diameter","Diameter of the thick raycast"),collision.thickRaycastDiameter);
EditorGUI.indentLevel--;
}
editor.GUILayoutx.EndFadeArea ();
collision.unwalkableWhenNoGround = EditorGUILayout.Toggle (new GUIContent ("Unwalkable when no ground","Make nodes unwalkable when no ground was found with the height raycast. If height raycast is turned off, this doesn't affect anything"), collision.unwalkableWhenNoGround);
GUI.enabled = preEnabledRoot;
//GUILayout.Space (2);
//EditorGUILayout.EndVertical ();
//GUILayout.Space (5);
}
/** Draws a wire cube using handles */
public static void DrawWireCube (Vector3 center, Vector3 size) {
size *= 0.5F;
Vector3 dx = new Vector3 (size.x,0,0);
Vector3 dy = new Vector3 (0,size.y,0);
Vector3 dz = new Vector3 (0,0,size.z);
Vector3 p1 = center-dy-dz-dx;
Vector3 p2 = center-dy-dz+dx;
Vector3 p3 = center-dy+dz+dx;
Vector3 p4 = center-dy+dz-dx;
Vector3 p5 = center+dy-dz-dx;
Vector3 p6 = center+dy-dz+dx;
Vector3 p7 = center+dy+dz+dx;
Vector3 p8 = center+dy+dz-dx;
/*Handles.DrawAAPolyLine (new Vector3[4] {p1,p2,p3,p4});
Handles.DrawAAPolyLine (new Vector3[4] {p5,p6,p7,p8});
Handles.DrawAAPolyLine (new Vector3[2] {p1,p5});
Handles.DrawAAPolyLine (new Vector3[2] {p2,p6});
Handles.DrawAAPolyLine (new Vector3[2] {p3,p7});
Handles.DrawAAPolyLine (new Vector3[2] {p4,p8});*/
Handles.DrawLine (p1,p2);
Handles.DrawLine (p2,p3);
Handles.DrawLine (p3,p4);
Handles.DrawLine (p4,p1);
Handles.DrawLine (p5,p6);
Handles.DrawLine (p6,p7);
Handles.DrawLine (p7,p8);
Handles.DrawLine (p8,p5);
Handles.DrawLine (p1,p5);
Handles.DrawLine (p2,p6);
Handles.DrawLine (p3,p7);
Handles.DrawLine (p4,p8);
}
/** \cond */
public static Texture2D lineTex;
/** \deprecated Test function, might not work. Uses undocumented editor features */
public static void DrawAALine (Vector3 a, Vector3 b) {
if (lineTex == null) {
lineTex = new Texture2D (1,4);
lineTex.SetPixels (new Color[4] {
Color.clear,
Color.black,
Color.black,
Color.clear,
});
lineTex.Apply ();
}
SceneView c = SceneView.lastActiveSceneView;
Vector3 tangent1 = Vector3.Cross ((b-a).normalized, c.camera.transform.position-a).normalized;
Handles.DrawAAPolyLine (lineTex,new Vector3[3] {a,b,b+tangent1*10});//,b+tangent1,a+tangent1});
}
/** \endcond */
}
}
| |
using System;
using System.Runtime.CompilerServices;
namespace Godot
{
/// <summary>
/// A pre-parsed relative or absolute path in a scene tree,
/// for use with <see cref="Node.GetNode(NodePath)"/> and similar functions.
/// It can reference a node, a resource within a node, or a property
/// of a node or resource.
/// For instance, <c>"Path2D/PathFollow2D/Sprite2D:texture:size"</c>
/// would refer to the <c>size</c> property of the <c>texture</c>
/// resource on the node named <c>"Sprite2D"</c> which is a child of
/// the other named nodes in the path.
/// You will usually just pass a string to <see cref="Node.GetNode(NodePath)"/>
/// and it will be automatically converted, but you may occasionally
/// want to parse a path ahead of time with NodePath.
/// Exporting a NodePath variable will give you a node selection widget
/// in the properties panel of the editor, which can often be useful.
/// A NodePath is composed of a list of slash-separated node names
/// (like a filesystem path) and an optional colon-separated list of
/// "subnames" which can be resources or properties.
///
/// Note: In the editor, NodePath properties are automatically updated when moving,
/// renaming or deleting a node in the scene tree, but they are never updated at runtime.
/// </summary>
/// <example>
/// Some examples of NodePaths include the following:
/// <code>
/// // No leading slash means it is relative to the current node.
/// new NodePath("A"); // Immediate child A.
/// new NodePath("A/B"); // A's child B.
/// new NodePath("."); // The current node.
/// new NodePath(".."); // The parent node.
/// new NodePath("../C"); // A sibling node C.
/// // A leading slash means it is absolute from the SceneTree.
/// new NodePath("/root"); // Equivalent to GetTree().Root
/// new NodePath("/root/Main"); // If your main scene's root node were named "Main".
/// new NodePath("/root/MyAutoload"); // If you have an autoloaded node or scene.
/// </code>
/// </example>
public sealed partial class NodePath : IDisposable
{
private bool _disposed = false;
private IntPtr ptr;
internal static IntPtr GetPtr(NodePath instance)
{
if (instance == null)
throw new NullReferenceException($"The instance of type {nameof(NodePath)} is null.");
if (instance._disposed)
throw new ObjectDisposedException(instance.GetType().FullName);
return instance.ptr;
}
~NodePath()
{
Dispose(false);
}
/// <summary>
/// Disposes of this <see cref="NodePath"/>.
/// </summary>
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
private void Dispose(bool disposing)
{
if (_disposed)
return;
if (ptr != IntPtr.Zero)
{
godot_icall_NodePath_Dtor(ptr);
ptr = IntPtr.Zero;
}
_disposed = true;
}
internal NodePath(IntPtr ptr)
{
this.ptr = ptr;
}
/// <summary>
/// Constructs an empty <see cref="NodePath"/>.
/// </summary>
public NodePath() : this(string.Empty) { }
/// <summary>
/// Constructs a <see cref="NodePath"/> from a string <paramref name="path"/>,
/// e.g.: <c>"Path2D/PathFollow2D/Sprite2D:texture:size"</c>.
/// A path is absolute if it starts with a slash. Absolute paths
/// are only valid in the global scene tree, not within individual
/// scenes. In a relative path, <c>"."</c> and <c>".."</c> indicate
/// the current node and its parent.
/// The "subnames" optionally included after the path to the target
/// node can point to resources or properties, and can also be nested.
/// </summary>
/// <example>
/// Examples of valid NodePaths (assuming that those nodes exist and
/// have the referenced resources or properties):
/// <code>
/// // Points to the Sprite2D node.
/// "Path2D/PathFollow2D/Sprite2D"
/// // Points to the Sprite2D node and its "texture" resource.
/// // GetNode() would retrieve "Sprite2D", while GetNodeAndResource()
/// // would retrieve both the Sprite2D node and the "texture" resource.
/// "Path2D/PathFollow2D/Sprite2D:texture"
/// // Points to the Sprite2D node and its "position" property.
/// "Path2D/PathFollow2D/Sprite2D:position"
/// // Points to the Sprite2D node and the "x" component of its "position" property.
/// "Path2D/PathFollow2D/Sprite2D:position:x"
/// // Absolute path (from "root")
/// "/root/Level/Path2D"
/// </code>
/// </example>
/// <param name="path"></param>
public NodePath(string path)
{
ptr = godot_icall_NodePath_Ctor(path);
}
/// <summary>
/// Converts a string to a <see cref="NodePath"/>.
/// </summary>
/// <param name="from">The string to convert.</param>
public static implicit operator NodePath(string from) => new NodePath(from);
/// <summary>
/// Converts this <see cref="NodePath"/> to a string.
/// </summary>
/// <param name="from">The <see cref="NodePath"/> to convert.</param>
public static implicit operator string(NodePath from) => from.ToString();
/// <summary>
/// Converts this <see cref="NodePath"/> to a string.
/// </summary>
/// <returns>A string representation of this <see cref="NodePath"/>.</returns>
public override string ToString()
{
return godot_icall_NodePath_operator_String(GetPtr(this));
}
/// <summary>
/// Returns a node path with a colon character (<c>:</c>) prepended,
/// transforming it to a pure property path with no node name (defaults
/// to resolving from the current node).
/// </summary>
/// <example>
/// <code>
/// // This will be parsed as a node path to the "x" property in the "position" node.
/// var nodePath = new NodePath("position:x");
/// // This will be parsed as a node path to the "x" component of the "position" property in the current node.
/// NodePath propertyPath = nodePath.GetAsPropertyPath();
/// GD.Print(propertyPath); // :position:x
/// </code>
/// </example>
/// <returns>The <see cref="NodePath"/> as a pure property path.</returns>
public NodePath GetAsPropertyPath()
{
return new NodePath(godot_icall_NodePath_get_as_property_path(GetPtr(this)));
}
/// <summary>
/// Returns all subnames concatenated with a colon character (<c>:</c>)
/// as separator, i.e. the right side of the first colon in a node path.
/// </summary>
/// <example>
/// <code>
/// var nodepath = new NodePath("Path2D/PathFollow2D/Sprite2D:texture:load_path");
/// GD.Print(nodepath.GetConcatenatedSubnames()); // texture:load_path
/// </code>
/// </example>
/// <returns>The subnames concatenated with <c>:</c>.</returns>
public string GetConcatenatedSubnames()
{
return godot_icall_NodePath_get_concatenated_subnames(GetPtr(this));
}
/// <summary>
/// Gets the node name indicated by <paramref name="idx"/> (0 to <see cref="GetNameCount"/>).
/// </summary>
/// <example>
/// <code>
/// var nodePath = new NodePath("Path2D/PathFollow2D/Sprite2D");
/// GD.Print(nodePath.GetName(0)); // Path2D
/// GD.Print(nodePath.GetName(1)); // PathFollow2D
/// GD.Print(nodePath.GetName(2)); // Sprite
/// </code>
/// </example>
/// <param name="idx">The name index.</param>
/// <returns>The name at the given index <paramref name="idx"/>.</returns>
public string GetName(int idx)
{
return godot_icall_NodePath_get_name(GetPtr(this), idx);
}
/// <summary>
/// Gets the number of node names which make up the path.
/// Subnames (see <see cref="GetSubnameCount"/>) are not included.
/// For example, <c>"Path2D/PathFollow2D/Sprite2D"</c> has 3 names.
/// </summary>
/// <returns>The number of node names which make up the path.</returns>
public int GetNameCount()
{
return godot_icall_NodePath_get_name_count(GetPtr(this));
}
/// <summary>
/// Gets the resource or property name indicated by <paramref name="idx"/> (0 to <see cref="GetSubnameCount"/>).
/// </summary>
/// <param name="idx">The subname index.</param>
/// <returns>The subname at the given index <paramref name="idx"/>.</returns>
public string GetSubname(int idx)
{
return godot_icall_NodePath_get_subname(GetPtr(this), idx);
}
/// <summary>
/// Gets the number of resource or property names ("subnames") in the path.
/// Each subname is listed after a colon character (<c>:</c>) in the node path.
/// For example, <c>"Path2D/PathFollow2D/Sprite2D:texture:load_path"</c> has 2 subnames.
/// </summary>
/// <returns>The number of subnames in the path.</returns>
public int GetSubnameCount()
{
return godot_icall_NodePath_get_subname_count(GetPtr(this));
}
/// <summary>
/// Returns <see langword="true"/> if the node path is absolute (as opposed to relative),
/// which means that it starts with a slash character (<c>/</c>). Absolute node paths can
/// be used to access the root node (<c>"/root"</c>) or autoloads (e.g. <c>"/global"</c>
/// if a "global" autoload was registered).
/// </summary>
/// <returns>If the <see cref="NodePath"/> is an absolute path.</returns>
public bool IsAbsolute()
{
return godot_icall_NodePath_is_absolute(GetPtr(this));
}
/// <summary>
/// Returns <see langword="true"/> if the node path is empty.
/// </summary>
/// <returns>If the <see cref="NodePath"/> is empty.</returns>
public bool IsEmpty()
{
return godot_icall_NodePath_is_empty(GetPtr(this));
}
[MethodImpl(MethodImplOptions.InternalCall)]
private static extern IntPtr godot_icall_NodePath_Ctor(string path);
[MethodImpl(MethodImplOptions.InternalCall)]
private static extern void godot_icall_NodePath_Dtor(IntPtr ptr);
[MethodImpl(MethodImplOptions.InternalCall)]
private static extern string godot_icall_NodePath_operator_String(IntPtr ptr);
[MethodImpl(MethodImplOptions.InternalCall)]
private static extern IntPtr godot_icall_NodePath_get_as_property_path(IntPtr ptr);
[MethodImpl(MethodImplOptions.InternalCall)]
private static extern string godot_icall_NodePath_get_concatenated_subnames(IntPtr ptr);
[MethodImpl(MethodImplOptions.InternalCall)]
private static extern string godot_icall_NodePath_get_name(IntPtr ptr, int arg1);
[MethodImpl(MethodImplOptions.InternalCall)]
private static extern int godot_icall_NodePath_get_name_count(IntPtr ptr);
[MethodImpl(MethodImplOptions.InternalCall)]
private static extern string godot_icall_NodePath_get_subname(IntPtr ptr, int arg1);
[MethodImpl(MethodImplOptions.InternalCall)]
private static extern int godot_icall_NodePath_get_subname_count(IntPtr ptr);
[MethodImpl(MethodImplOptions.InternalCall)]
private static extern bool godot_icall_NodePath_is_absolute(IntPtr ptr);
[MethodImpl(MethodImplOptions.InternalCall)]
private static extern bool godot_icall_NodePath_is_empty(IntPtr ptr);
}
}
| |
// 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.
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by google-apis-code-generator 1.5.1
// C# generator version: 1.38.0
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
/**
* \brief
* Google Play Developer API Version v1
*
* \section ApiInfo API Version Information
* <table>
* <tr><th>API
* <td><a href='https://developers.google.com/android-publisher'>Google Play Developer API</a>
* <tr><th>API Version<td>v1
* <tr><th>API Rev<td>20190205 (1496)
* <tr><th>API Docs
* <td><a href='https://developers.google.com/android-publisher'>
* https://developers.google.com/android-publisher</a>
* <tr><th>Discovery Name<td>androidpublisher
* </table>
*
* \section ForMoreInfo For More Information
*
* The complete API documentation for using Google Play Developer API can be found at
* <a href='https://developers.google.com/android-publisher'>https://developers.google.com/android-publisher</a>.
*
* For more information about the Google APIs Client Library for .NET, see
* <a href='https://developers.google.com/api-client-library/dotnet/get_started'>
* https://developers.google.com/api-client-library/dotnet/get_started</a>
*/
namespace Google.Apis.AndroidPublisher.v1
{
/// <summary>The AndroidPublisher Service.</summary>
public class AndroidPublisherService : Google.Apis.Services.BaseClientService
{
/// <summary>The API version.</summary>
public const string Version = "v1";
/// <summary>The discovery version used to generate this service.</summary>
public static Google.Apis.Discovery.DiscoveryVersion DiscoveryVersionUsed =
Google.Apis.Discovery.DiscoveryVersion.Version_1_0;
/// <summary>Constructs a new service.</summary>
public AndroidPublisherService() :
this(new Google.Apis.Services.BaseClientService.Initializer()) {}
/// <summary>Constructs a new service.</summary>
/// <param name="initializer">The service initializer.</param>
public AndroidPublisherService(Google.Apis.Services.BaseClientService.Initializer initializer)
: base(initializer)
{
purchases = new PurchasesResource(this);
}
/// <summary>Gets the service supported features.</summary>
public override System.Collections.Generic.IList<string> Features
{
get { return new string[0]; }
}
/// <summary>Gets the service name.</summary>
public override string Name
{
get { return "androidpublisher"; }
}
/// <summary>Gets the service base URI.</summary>
public override string BaseUri
{
get { return "https://www.googleapis.com/androidpublisher/v1/applications/"; }
}
/// <summary>Gets the service base path.</summary>
public override string BasePath
{
get { return "androidpublisher/v1/applications/"; }
}
#if !NET40
/// <summary>Gets the batch base URI; <c>null</c> if unspecified.</summary>
public override string BatchUri
{
get { return "https://www.googleapis.com/batch/androidpublisher/v1"; }
}
/// <summary>Gets the batch base path; <c>null</c> if unspecified.</summary>
public override string BatchPath
{
get { return "batch/androidpublisher/v1"; }
}
#endif
/// <summary>Available OAuth 2.0 scopes for use with the Google Play Developer API.</summary>
public class Scope
{
/// <summary>View and manage your Google Play Developer account</summary>
public static string Androidpublisher = "https://www.googleapis.com/auth/androidpublisher";
}
/// <summary>Available OAuth 2.0 scope constants for use with the Google Play Developer API.</summary>
public static class ScopeConstants
{
/// <summary>View and manage your Google Play Developer account</summary>
public const string Androidpublisher = "https://www.googleapis.com/auth/androidpublisher";
}
private readonly PurchasesResource purchases;
/// <summary>Gets the Purchases resource.</summary>
public virtual PurchasesResource Purchases
{
get { return purchases; }
}
}
///<summary>A base abstract class for AndroidPublisher requests.</summary>
public abstract class AndroidPublisherBaseServiceRequest<TResponse> : Google.Apis.Requests.ClientServiceRequest<TResponse>
{
///<summary>Constructs a new AndroidPublisherBaseServiceRequest instance.</summary>
protected AndroidPublisherBaseServiceRequest(Google.Apis.Services.IClientService service)
: base(service)
{
}
/// <summary>Data format for the response.</summary>
/// [default: json]
[Google.Apis.Util.RequestParameterAttribute("alt", Google.Apis.Util.RequestParameterType.Query)]
public virtual System.Nullable<AltEnum> Alt { get; set; }
/// <summary>Data format for the response.</summary>
public enum AltEnum
{
/// <summary>Responses with Content-Type of application/json</summary>
[Google.Apis.Util.StringValueAttribute("json")]
Json,
}
/// <summary>Selector specifying which fields to include in a partial response.</summary>
[Google.Apis.Util.RequestParameterAttribute("fields", Google.Apis.Util.RequestParameterType.Query)]
public virtual string Fields { get; set; }
/// <summary>API key. Your API key identifies your project and provides you with API access, quota, and reports.
/// Required unless you provide an OAuth 2.0 token.</summary>
[Google.Apis.Util.RequestParameterAttribute("key", Google.Apis.Util.RequestParameterType.Query)]
public virtual string Key { get; set; }
/// <summary>OAuth 2.0 token for the current user.</summary>
[Google.Apis.Util.RequestParameterAttribute("oauth_token", Google.Apis.Util.RequestParameterType.Query)]
public virtual string OauthToken { get; set; }
/// <summary>Returns response with indentations and line breaks.</summary>
/// [default: true]
[Google.Apis.Util.RequestParameterAttribute("prettyPrint", Google.Apis.Util.RequestParameterType.Query)]
public virtual System.Nullable<bool> PrettyPrint { get; set; }
/// <summary>An opaque string that represents a user for quota purposes. Must not exceed 40
/// characters.</summary>
[Google.Apis.Util.RequestParameterAttribute("quotaUser", Google.Apis.Util.RequestParameterType.Query)]
public virtual string QuotaUser { get; set; }
/// <summary>Deprecated. Please use quotaUser instead.</summary>
[Google.Apis.Util.RequestParameterAttribute("userIp", Google.Apis.Util.RequestParameterType.Query)]
public virtual string UserIp { get; set; }
/// <summary>Initializes AndroidPublisher parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add(
"alt", new Google.Apis.Discovery.Parameter
{
Name = "alt",
IsRequired = false,
ParameterType = "query",
DefaultValue = "json",
Pattern = null,
});
RequestParameters.Add(
"fields", new Google.Apis.Discovery.Parameter
{
Name = "fields",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"key", new Google.Apis.Discovery.Parameter
{
Name = "key",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"oauth_token", new Google.Apis.Discovery.Parameter
{
Name = "oauth_token",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"prettyPrint", new Google.Apis.Discovery.Parameter
{
Name = "prettyPrint",
IsRequired = false,
ParameterType = "query",
DefaultValue = "true",
Pattern = null,
});
RequestParameters.Add(
"quotaUser", new Google.Apis.Discovery.Parameter
{
Name = "quotaUser",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"userIp", new Google.Apis.Discovery.Parameter
{
Name = "userIp",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
}
}
/// <summary>The "purchases" collection of methods.</summary>
public class PurchasesResource
{
private const string Resource = "purchases";
/// <summary>The service which this resource belongs to.</summary>
private readonly Google.Apis.Services.IClientService service;
/// <summary>Constructs a new resource.</summary>
public PurchasesResource(Google.Apis.Services.IClientService service)
{
this.service = service;
}
/// <summary>Cancels a user's subscription purchase. The subscription remains valid until its expiration
/// time.</summary>
/// <param name="packageName">The package name of the application for which this subscription was purchased (for
/// example, 'com.some.thing').</param>
/// <param name="subscriptionId">The purchased subscription ID (for example,
/// 'monthly001').</param>
/// <param name="token">The token provided to the user's device when the subscription was
/// purchased.</param>
public virtual CancelRequest Cancel(string packageName, string subscriptionId, string token)
{
return new CancelRequest(service, packageName, subscriptionId, token);
}
/// <summary>Cancels a user's subscription purchase. The subscription remains valid until its expiration
/// time.</summary>
public class CancelRequest : AndroidPublisherBaseServiceRequest<string>
{
/// <summary>Constructs a new Cancel request.</summary>
public CancelRequest(Google.Apis.Services.IClientService service, string packageName, string subscriptionId, string token)
: base(service)
{
PackageName = packageName;
SubscriptionId = subscriptionId;
Token = token;
InitParameters();
}
/// <summary>The package name of the application for which this subscription was purchased (for example,
/// 'com.some.thing').</summary>
[Google.Apis.Util.RequestParameterAttribute("packageName", Google.Apis.Util.RequestParameterType.Path)]
public virtual string PackageName { get; private set; }
/// <summary>The purchased subscription ID (for example, 'monthly001').</summary>
[Google.Apis.Util.RequestParameterAttribute("subscriptionId", Google.Apis.Util.RequestParameterType.Path)]
public virtual string SubscriptionId { get; private set; }
/// <summary>The token provided to the user's device when the subscription was purchased.</summary>
[Google.Apis.Util.RequestParameterAttribute("token", Google.Apis.Util.RequestParameterType.Path)]
public virtual string Token { get; private set; }
///<summary>Gets the method name.</summary>
public override string MethodName
{
get { return "cancel"; }
}
///<summary>Gets the HTTP method.</summary>
public override string HttpMethod
{
get { return "POST"; }
}
///<summary>Gets the REST path.</summary>
public override string RestPath
{
get { return "{packageName}/subscriptions/{subscriptionId}/purchases/{token}/cancel"; }
}
/// <summary>Initializes Cancel parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add(
"packageName", new Google.Apis.Discovery.Parameter
{
Name = "packageName",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"subscriptionId", new Google.Apis.Discovery.Parameter
{
Name = "subscriptionId",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"token", new Google.Apis.Discovery.Parameter
{
Name = "token",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = null,
});
}
}
/// <summary>Checks whether a user's subscription purchase is valid and returns its expiry time.</summary>
/// <param name="packageName">The package name of the application for which this subscription was purchased (for
/// example, 'com.some.thing').</param>
/// <param name="subscriptionId">The purchased subscription ID (for example,
/// 'monthly001').</param>
/// <param name="token">The token provided to the user's device when the subscription was
/// purchased.</param>
public virtual GetRequest Get(string packageName, string subscriptionId, string token)
{
return new GetRequest(service, packageName, subscriptionId, token);
}
/// <summary>Checks whether a user's subscription purchase is valid and returns its expiry time.</summary>
public class GetRequest : AndroidPublisherBaseServiceRequest<Google.Apis.AndroidPublisher.v1.Data.SubscriptionPurchase>
{
/// <summary>Constructs a new Get request.</summary>
public GetRequest(Google.Apis.Services.IClientService service, string packageName, string subscriptionId, string token)
: base(service)
{
PackageName = packageName;
SubscriptionId = subscriptionId;
Token = token;
InitParameters();
}
/// <summary>The package name of the application for which this subscription was purchased (for example,
/// 'com.some.thing').</summary>
[Google.Apis.Util.RequestParameterAttribute("packageName", Google.Apis.Util.RequestParameterType.Path)]
public virtual string PackageName { get; private set; }
/// <summary>The purchased subscription ID (for example, 'monthly001').</summary>
[Google.Apis.Util.RequestParameterAttribute("subscriptionId", Google.Apis.Util.RequestParameterType.Path)]
public virtual string SubscriptionId { get; private set; }
/// <summary>The token provided to the user's device when the subscription was purchased.</summary>
[Google.Apis.Util.RequestParameterAttribute("token", Google.Apis.Util.RequestParameterType.Path)]
public virtual string Token { get; private set; }
///<summary>Gets the method name.</summary>
public override string MethodName
{
get { return "get"; }
}
///<summary>Gets the HTTP method.</summary>
public override string HttpMethod
{
get { return "GET"; }
}
///<summary>Gets the REST path.</summary>
public override string RestPath
{
get { return "{packageName}/subscriptions/{subscriptionId}/purchases/{token}"; }
}
/// <summary>Initializes Get parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add(
"packageName", new Google.Apis.Discovery.Parameter
{
Name = "packageName",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"subscriptionId", new Google.Apis.Discovery.Parameter
{
Name = "subscriptionId",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"token", new Google.Apis.Discovery.Parameter
{
Name = "token",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = null,
});
}
}
}
}
namespace Google.Apis.AndroidPublisher.v1.Data
{
/// <summary>A SubscriptionPurchase resource indicates the status of a user's subscription purchase.</summary>
public class SubscriptionPurchase : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>Whether the subscription will automatically be renewed when it reaches its current expiry
/// time.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("autoRenewing")]
public virtual System.Nullable<bool> AutoRenewing { get; set; }
/// <summary>Time at which the subscription was granted, in milliseconds since the Epoch.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("initiationTimestampMsec")]
public virtual System.Nullable<long> InitiationTimestampMsec { get; set; }
/// <summary>This kind represents a subscriptionPurchase object in the androidpublisher service.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("kind")]
public virtual string Kind { get; set; }
/// <summary>Time at which the subscription will expire, in milliseconds since the Epoch.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("validUntilTimestampMsec")]
public virtual System.Nullable<long> ValidUntilTimestampMsec { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
}
| |
#region License
/* Copyright (c) 2006 Leslie Sanford
*
* 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
#region Contact
/*
* Leslie Sanford
* Email: jabberdabber@hotmail.com
*/
#endregion
using System;
using System.ComponentModel;
using System.Diagnostics;
using System.Runtime.InteropServices;
namespace Sanford.Multimedia.Timers
{
/// <summary>
/// Defines constants for the multimedia Timer's event types.
/// </summary>
public enum TimerMode
{
/// <summary>
/// Timer event occurs once.
/// </summary>
OneShot,
/// <summary>
/// Timer event occurs periodically.
/// </summary>
Periodic
};
/// <summary>
/// Represents information about the multimedia Timer's capabilities.
/// </summary>
[StructLayout(LayoutKind.Sequential)]
public struct TimerCaps
{
/// <summary>
/// Minimum supported period in milliseconds.
/// </summary>
public int periodMin;
/// <summary>
/// Maximum supported period in milliseconds.
/// </summary>
public int periodMax;
public static TimerCaps Default
{
get
{
return new TimerCaps { periodMin = 1, periodMax = Int32.MaxValue };
}
}
}
/// <summary>
/// Represents the Windows multimedia timer.
/// </summary>
sealed class Timer : ITimer
{
#region Timer Members
#region Delegates
// Represents the method that is called by Windows when a timer event occurs.
private delegate void TimeProc(int id, int msg, int user, int param1, int param2);
// Represents methods that raise events.
private delegate void EventRaiser(EventArgs e);
#endregion
#region Win32 Multimedia Timer Functions
// Gets timer capabilities.
[DllImport("winmm.dll")]
private static extern int timeGetDevCaps(ref TimerCaps caps,
int sizeOfTimerCaps);
// Creates and starts the timer.
[DllImport("winmm.dll")]
private static extern int timeSetEvent(int delay, int resolution, TimeProc proc, IntPtr user, int mode);
// Stops and destroys the timer.
[DllImport("winmm.dll")]
private static extern int timeKillEvent(int id);
// Indicates that the operation was successful.
private const int TIMERR_NOERROR = 0;
#endregion
#region Fields
// Timer identifier.
private int timerID;
// Timer mode.
private volatile TimerMode mode;
// Period between timer events in milliseconds.
private volatile int period;
// Timer resolution in milliseconds.
private volatile int resolution;
// Called by Windows when a timer periodic event occurs.
private TimeProc timeProcPeriodic;
// Called by Windows when a timer one shot event occurs.
private TimeProc timeProcOneShot;
// Represents the method that raises the Tick event.
private EventRaiser tickRaiser;
// The ISynchronizeInvoke object to use for marshaling events.
private ISynchronizeInvoke synchronizingObject = null;
// Indicates whether or not the timer is running.
private bool running = false;
// Indicates whether or not the timer has been disposed.
private volatile bool disposed = false;
// For implementing IComponent.
private ISite site = null;
// Multimedia timer capabilities.
private static TimerCaps caps;
#endregion
#region Events
/// <summary>
/// Occurs when the Timer has started;
/// </summary>
public event EventHandler Started;
/// <summary>
/// Occurs when the Timer has stopped;
/// </summary>
public event EventHandler Stopped;
/// <summary>
/// Occurs when the time period has elapsed.
/// </summary>
public event EventHandler Tick;
#endregion
#region Construction
/// <summary>
/// Initialize class.
/// </summary>
static Timer()
{
// Get multimedia timer capabilities.
timeGetDevCaps(ref caps, Marshal.SizeOf(caps));
}
/// <summary>
/// Initializes a new instance of the Timer class with the specified IContainer.
/// </summary>
/// <param name="container">
/// The IContainer to which the Timer will add itself.
/// </param>
public Timer(IContainer container)
{
///
/// Required for Windows.Forms Class Composition Designer support
///
container.Add(this);
Initialize();
}
/// <summary>
/// Initializes a new instance of the Timer class.
/// </summary>
public Timer()
{
Initialize();
}
~Timer()
{
if(IsRunning)
{
// Stop and destroy timer.
timeKillEvent(timerID);
}
}
// Initialize timer with default values.
private void Initialize()
{
this.mode = TimerMode.Periodic;
this.period = Capabilities.periodMin;
this.resolution = 1;
running = false;
timeProcPeriodic = new TimeProc(TimerPeriodicEventCallback);
timeProcOneShot = new TimeProc(TimerOneShotEventCallback);
tickRaiser = new EventRaiser(OnTick);
}
#endregion
#region Methods
/// <summary>
/// Starts the timer.
/// </summary>
/// <exception cref="ObjectDisposedException">
/// The timer has already been disposed.
/// </exception>
/// <exception cref="TimerStartException">
/// The timer failed to start.
/// </exception>
public void Start()
{
#region Require
if(disposed)
{
throw new ObjectDisposedException("Timer");
}
#endregion
#region Guard
if(IsRunning)
{
return;
}
#endregion
// If the periodic event callback should be used.
if(Mode == TimerMode.Periodic)
{
// Create and start timer.
timerID = timeSetEvent(Period, Resolution, timeProcPeriodic, IntPtr.Zero, (int)Mode);
}
// Else the one shot event callback should be used.
else
{
// Create and start timer.
timerID = timeSetEvent(Period, Resolution, timeProcOneShot, IntPtr.Zero, (int)Mode);
}
// If the timer was created successfully.
if(timerID != 0)
{
running = true;
if(SynchronizingObject != null && SynchronizingObject.InvokeRequired)
{
SynchronizingObject.BeginInvoke(
new EventRaiser(OnStarted),
new object[] { EventArgs.Empty });
}
else
{
OnStarted(EventArgs.Empty);
}
}
else
{
throw new TimerStartException("Unable to start multimedia Timer.");
}
}
/// <summary>
/// Stops timer.
/// </summary>
/// <exception cref="ObjectDisposedException">
/// If the timer has already been disposed.
/// </exception>
public void Stop()
{
#region Require
if(disposed)
{
throw new ObjectDisposedException("Timer");
}
#endregion
#region Guard
if(!running)
{
return;
}
#endregion
// Stop and destroy timer.
int result = timeKillEvent(timerID);
Debug.Assert(result == TIMERR_NOERROR);
running = false;
if(SynchronizingObject != null && SynchronizingObject.InvokeRequired)
{
SynchronizingObject.BeginInvoke(
new EventRaiser(OnStopped),
new object[] { EventArgs.Empty });
}
else
{
OnStopped(EventArgs.Empty);
}
}
#region Callbacks
// Callback method called by the Win32 multimedia timer when a timer
// periodic event occurs.
private void TimerPeriodicEventCallback(int id, int msg, int user, int param1, int param2)
{
#region Guard
if(disposed)
{
return;
}
#endregion
if(synchronizingObject != null)
{
synchronizingObject.BeginInvoke(tickRaiser, new object[] { EventArgs.Empty });
}
else
{
OnTick(EventArgs.Empty);
}
}
// Callback method called by the Win32 multimedia timer when a timer
// one shot event occurs.
private void TimerOneShotEventCallback(int id, int msg, int user, int param1, int param2)
{
#region Guard
if(disposed)
{
return;
}
#endregion
if(synchronizingObject != null)
{
synchronizingObject.BeginInvoke(tickRaiser, new object[] { EventArgs.Empty });
Stop();
}
else
{
OnTick(EventArgs.Empty);
Stop();
}
}
#endregion
#region Event Raiser Methods
// Raises the Disposed event.
private void OnDisposed(EventArgs e)
{
EventHandler handler = Disposed;
if(handler != null)
{
handler(this, e);
}
}
// Raises the Started event.
private void OnStarted(EventArgs e)
{
EventHandler handler = Started;
if(handler != null)
{
handler(this, e);
}
}
// Raises the Stopped event.
private void OnStopped(EventArgs e)
{
EventHandler handler = Stopped;
if(handler != null)
{
handler(this, e);
}
}
// Raises the Tick event.
private void OnTick(EventArgs e)
{
EventHandler handler = Tick;
if(handler != null)
{
handler(this, e);
}
}
#endregion
#endregion
#region Properties
/// <summary>
/// Gets or sets the object used to marshal event-handler calls.
/// </summary>
public ISynchronizeInvoke SynchronizingObject
{
get
{
#region Require
if(disposed)
{
throw new ObjectDisposedException("Timer");
}
#endregion
return synchronizingObject;
}
set
{
#region Require
if(disposed)
{
throw new ObjectDisposedException("Timer");
}
#endregion
synchronizingObject = value;
}
}
/// <summary>
/// Gets or sets the time between Tick events.
/// </summary>
/// <exception cref="ObjectDisposedException">
/// If the timer has already been disposed.
/// </exception>
public int Period
{
get
{
#region Require
if(disposed)
{
throw new ObjectDisposedException("Timer");
}
#endregion
return period;
}
set
{
#region Require
if(disposed)
{
throw new ObjectDisposedException("Timer");
}
else if(value < Capabilities.periodMin || value > Capabilities.periodMax)
{
throw new ArgumentOutOfRangeException("Period", value,
"Multimedia Timer period out of range.");
}
#endregion
period = value;
if(IsRunning)
{
Stop();
Start();
}
}
}
/// <summary>
/// Gets or sets the timer resolution.
/// </summary>
/// <exception cref="ObjectDisposedException">
/// If the timer has already been disposed.
/// </exception>
/// <remarks>
/// The resolution is in milliseconds. The resolution increases
/// with smaller values; a resolution of 0 indicates periodic events
/// should occur with the greatest possible accuracy. To reduce system
/// overhead, however, you should use the maximum value appropriate
/// for your application.
/// </remarks>
public int Resolution
{
get
{
#region Require
if(disposed)
{
throw new ObjectDisposedException("Timer");
}
#endregion
return resolution;
}
set
{
#region Require
if(disposed)
{
throw new ObjectDisposedException("Timer");
}
else if(value < 0)
{
throw new ArgumentOutOfRangeException("Resolution", value,
"Multimedia timer resolution out of range.");
}
#endregion
resolution = value;
if(IsRunning)
{
Stop();
Start();
}
}
}
/// <summary>
/// Gets the timer mode.
/// </summary>
/// <exception cref="ObjectDisposedException">
/// If the timer has already been disposed.
/// </exception>
public TimerMode Mode
{
get
{
#region Require
if(disposed)
{
throw new ObjectDisposedException("Timer");
}
#endregion
return mode;
}
set
{
#region Require
if(disposed)
{
throw new ObjectDisposedException("Timer");
}
#endregion
mode = value;
if(IsRunning)
{
Stop();
Start();
}
}
}
/// <summary>
/// Gets a value indicating whether the Timer is running.
/// </summary>
public bool IsRunning
{
get
{
return running;
}
}
/// <summary>
/// Gets the timer capabilities.
/// </summary>
public static TimerCaps Capabilities
{
get
{
return caps;
}
}
#endregion
#endregion
#region IComponent Members
public event System.EventHandler Disposed;
public ISite Site
{
get
{
return site;
}
set
{
site = value;
}
}
#endregion
#region IDisposable Members
/// <summary>
/// Frees timer resources.
/// </summary>
public void Dispose()
{
#region Guard
if(disposed)
{
return;
}
#endregion
disposed = true;
if(running)
{
// Stop and destroy timer.
timeKillEvent(timerID);
}
OnDisposed(EventArgs.Empty);
}
#endregion
}
/// <summary>
/// The exception that is thrown when a timer fails to start.
/// </summary>
public class TimerStartException : ApplicationException
{
/// <summary>
/// Initializes a new instance of the TimerStartException class.
/// </summary>
/// <param name="message">
/// The error message that explains the reason for the exception.
/// </param>
public TimerStartException(string message) : base(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;
using System.Collections.Generic;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Org.Apache.REEF.Common.Tasks;
using Org.Apache.REEF.Examples.Tasks.HelloTask;
using Org.Apache.REEF.Tang.Annotations;
using Org.Apache.REEF.Tang.Examples;
using Org.Apache.REEF.Tang.Exceptions;
using Org.Apache.REEF.Tang.Implementations.Tang;
using Org.Apache.REEF.Tang.Interface;
using Org.Apache.REEF.Tang.Types;
using Org.Apache.REEF.Tang.Util;
namespace Org.Apache.REEF.Tang.Tests.ClassHierarchy
{
[TestClass]
public class TestClassHierarchy
{
public IClassHierarchy ns = null;
[TestInitialize]
public void TestSetup()
{
if (ns == null)
{
TangImpl.Reset();
ns = TangFactory.GetTang().GetClassHierarchy(new string[] { FileNames.Examples, FileNames.Common, FileNames.Tasks });
}
}
[TestCleanup]
public void TestCleanup()
{
}
[TestMethod]
public void TestString()
{
INode n = null;
try
{
n = ns.GetNode("System");
}
catch (ApplicationException)
{
}
catch (NameResolutionException)
{
}
Assert.IsNull(n);
Assert.IsNotNull(ns.GetNode(typeof(System.String).AssemblyQualifiedName));
string msg = null;
try
{
ns.GetNode("org.apache");
msg = "Didn't get expected exception";
}
catch (ApplicationException)
{
}
catch (NameResolutionException)
{
}
Assert.IsNull(msg, msg);
}
[TestMethod]
public void TestInt()
{
INode n = null;
try
{
n = ns.GetNode("System");
}
catch (ApplicationException)
{
}
catch (NameResolutionException)
{
}
Assert.IsNull(n);
Assert.IsNotNull(ns.GetNode(typeof(System.Int32).AssemblyQualifiedName));
string msg = null;
try
{
ns.GetNode("org.apache");
msg = "Didn't get expected exception";
}
catch (ApplicationException)
{
}
catch (NameResolutionException)
{
}
Assert.IsNull(msg, msg);
}
[TestMethod]
public void TestSimpleConstructors()
{
IClassNode cls = (IClassNode)ns.GetNode(typeof(SimpleConstructors).AssemblyQualifiedName);
Assert.IsTrue(cls.GetChildren().Count == 0);
IList<IConstructorDef> def = cls.GetInjectableConstructors();
Assert.AreEqual(3, def.Count);
}
[TestMethod]
public void TestTimer()
{
IClassNode timerClassNode = (IClassNode)ns.GetNode(typeof(Timer).AssemblyQualifiedName);
INode secondNode = ns.GetNode(typeof(Timer.Seconds).AssemblyQualifiedName);
Assert.AreEqual(secondNode.GetFullName(), ReflectionUtilities.GetAssemblyQualifiedName(typeof(Timer.Seconds)));
}
[TestMethod]
public void TestNamedParameterConstructors()
{
var node = ns.GetNode(typeof(NamedParameterConstructors).AssemblyQualifiedName);
Assert.AreEqual(node.GetFullName(), ReflectionUtilities.GetAssemblyQualifiedName(typeof(NamedParameterConstructors)));
}
[TestMethod]
public void TestArray()
{
Type t = (new string[0]).GetType();
INode node = ns.GetNode(t.AssemblyQualifiedName);
Assert.AreEqual(node.GetFullName(), t.AssemblyQualifiedName);
}
[TestMethod]
public void TestRepeatConstructorArg()
{
TestNegativeCase(typeof(RepeatConstructorArg),
"Repeated constructor parameter detected. Cannot inject constructor RepeatConstructorArg(int,int).");
}
[TestMethod]
public void TestRepeatConstructorArgClasses()
{
TestNegativeCase(typeof(RepeatConstructorArgClasses),
"Repeated constructor parameter detected. Cannot inject constructor RepeatConstructorArgClasses(A, A).");
}
[TestMethod]
public void testLeafRepeatedConstructorArgClasses()
{
INode node = ns.GetNode(typeof(LeafRepeatedConstructorArgClasses).AssemblyQualifiedName);
Assert.AreEqual(node.GetFullName(), typeof(LeafRepeatedConstructorArgClasses).AssemblyQualifiedName);
}
[TestMethod]
public void TestNamedRepeatConstructorArgClasses()
{
INode node = ns.GetNode(typeof(NamedRepeatConstructorArgClasses).AssemblyQualifiedName);
Assert.AreEqual(node.GetFullName(), typeof(NamedRepeatConstructorArgClasses).AssemblyQualifiedName);
}
[TestMethod]
public void TestResolveDependencies()
{
ns.GetNode(typeof(SimpleConstructors).AssemblyQualifiedName);
Assert.IsNotNull(ns.GetNode(typeof(string).AssemblyQualifiedName));
}
[TestMethod]
public void TestDocumentedLocalNamedParameter()
{
var node = ns.GetNode(typeof(DocumentedLocalNamedParameter).AssemblyQualifiedName);
Assert.AreEqual(node.GetFullName(), ReflectionUtilities.GetAssemblyQualifiedName(typeof(DocumentedLocalNamedParameter)));
}
[TestMethod]
public void TestNamedParameterTypeMismatch()
{
TestNegativeCase(typeof(NamedParameterTypeMismatch),
"Named parameter type mismatch in NamedParameterTypeMismatch. Constructor expects a System.String but Foo is a System.Int32.");
}
[TestMethod]
public void TestUnannotatedName()
{
TestNegativeCase(typeof(UnannotatedName),
"Named parameter UnannotatedName is missing its [NamedParameter] attribute.");
}
[TestMethod]
public void TestAnnotatedNotName()
{
TestNegativeCase(typeof(AnnotatedNotName),
"Found illegal [NamedParameter] AnnotatedNotName does not implement Name<T>.");
}
[TestMethod]
public void TestAnnotatedNameWrongInterface()
{
TestNegativeCase(typeof(AnnotatedNameWrongInterface),
"Found illegal [NamedParameter] AnnotatedNameWrongInterface does not implement Name<T>.");
}
[TestMethod]
public void TestAnnotatedNameMultipleInterfaces()
{
TestNegativeCase(typeof(AnnotatedNameMultipleInterfaces),
"Named parameter Org.Apache.REEF.Tang.Implementation.AnnotatedNameMultipleInterfaces implements multiple interfaces. It is only allowed to implement Name<T>.");
}
[TestMethod]
public void TestUnAnnotatedNameMultipleInterfaces()
{
TestNegativeCase(typeof(UnAnnotatedNameMultipleInterfaces),
"Named parameter Org.Apache.REEF.Tang.Implementation.UnAnnotatedNameMultipleInterfaces is missing its @NamedParameter annotation.");
}
[TestMethod]
public void TestNameWithConstructor()
{
TestNegativeCase(typeof(NameWithConstructor),
"Named parameter Org.Apache.REEF.Tang.Implementation.NameWithConstructor has a constructor. Named parameters must not declare any constructors.");
}
[TestMethod]
public void TestNameWithZeroArgInject()
{
TestNegativeCase(typeof(NameWithZeroArgInject),
"Named parameter Org.Apache.REEF.Tang.Implementation.NameWithZeroArgInject has an injectable constructor. Named parameters must not declare any constructors.");
}
[TestMethod]
public void TestInjectNonStaticLocalArgClass()
{
var node = ns.GetNode(typeof(InjectNonStaticLocalArgClass).AssemblyQualifiedName);
Assert.AreEqual(node.GetFullName(), typeof(InjectNonStaticLocalArgClass).AssemblyQualifiedName);
}
[TestMethod]
public void TestInjectNonStaticLocalType()
{
var node = ns.GetNode(typeof(InjectNonStaticLocalType).AssemblyQualifiedName);
Assert.AreEqual(node.GetFullName(), typeof(InjectNonStaticLocalType).AssemblyQualifiedName);
}
[TestMethod]
public void TestOKShortNames()
{
var node = ns.GetNode(typeof(ShortNameFooA).AssemblyQualifiedName);
Assert.AreEqual(node.GetFullName(), typeof(ShortNameFooA).AssemblyQualifiedName);
}
public void TestConflictingShortNames()
{
string msg = null;
try
{
var nodeA = ns.GetNode(typeof(ShortNameFooA).AssemblyQualifiedName);
var nodeB = ns.GetNode(typeof(ShortNameFooB).AssemblyQualifiedName);
msg =
"ShortNameFooA and ShortNameFooB have the same short name" +
nodeA.GetName() + nodeB.GetName();
}
catch (Exception e)
{
Console.WriteLine(e);
}
Assert.IsNull(msg, msg);
}
[TestMethod]
public void TestRoundTripInnerClassNames()
{
INode node = ns.GetNode(typeof(Nested.Inner).AssemblyQualifiedName);
Assert.AreEqual(node.GetFullName(), typeof(Nested.Inner).AssemblyQualifiedName);
}
[TestMethod]
public void TestRoundTripAnonInnerClassNames()
{
INode node1 = ns.GetNode(typeof(AnonNested.X1).AssemblyQualifiedName);
INode node2 = ns.GetNode(typeof(AnonNested.Y1).AssemblyQualifiedName);
Assert.AreNotEqual(node1.GetFullName(), node2.GetFullName());
Type t1 = ReflectionUtilities.GetTypeByName(node1.GetFullName());
Type t2 = ReflectionUtilities.GetTypeByName(node2.GetFullName());
Assert.AreNotSame(t1, t2);
}
[TestMethod]
public void TestNameCantBindWrongSubclassAsDefault()
{
TestNegativeCase(typeof(BadName),
"class org.apache.reef.tang.implementation.BadName defines a default class Int32 with a type that does not extend of its target's type string");
}
[TestMethod]
public void TestNameCantBindWrongSubclassOfArgumentAsDefault()
{
TestNegativeCase(typeof(BadNameForGeneric),
"class BadNameForGeneric defines a default class Int32 with a type that does not extend of its target's string in ISet<string>");
}
[TestMethod]
public void TestNameCantBindSubclassOfArgumentAsDefault()
{
ns = TangFactory.GetTang().GetClassHierarchy(new string[] { FileNames.Examples, FileNames.Common, FileNames.Tasks });
INode node = ns.GetNode(typeof(GoodNameForGeneric).AssemblyQualifiedName);
Assert.AreEqual(node.GetFullName(), typeof(GoodNameForGeneric).AssemblyQualifiedName);
}
[TestMethod]
public void TestInterfaceCantBindWrongImplAsDefault()
{
TestNegativeCase(typeof(IBadIfaceDefault),
"interface IBadIfaceDefault declares its default implementation to be non-subclass class string");
}
private void TestNegativeCase(Type clazz, string message)
{
string msg = null;
try
{
var node = ns.GetNode(typeof(IBadIfaceDefault).AssemblyQualifiedName);
msg = message + node.GetName();
}
catch (Exception)
{
}
Assert.IsNull(msg, msg);
}
[TestMethod]
public void TestParseableDefaultClassNotOK()
{
TestNegativeCase(typeof(BadParsableDefaultClass),
"Named parameter BadParsableDefaultClass defines default implementation for parsable type System.string");
}
[TestMethod]
public void testGenericTorture1()
{
g(typeof(GenericTorture1));
}
[TestMethod]
public void testGenericTorture2()
{
g(typeof(GenericTorture2));
}
[TestMethod]
public void testGenericTorture3()
{
g(typeof(GenericTorture3));
}
[TestMethod]
public void testGenericTorture4()
{
g(typeof(GenericTorture4));
}
public string s(Type t)
{
return ReflectionUtilities.GetAssemblyQualifiedName(t);
}
public INode g(Type t)
{
INode n = ns.GetNode(s(t));
Assert.IsNotNull(n);
return n;
}
[TestMethod]
public void TestHelloTaskNode()
{
var node = ns.GetNode(typeof(HelloTask).AssemblyQualifiedName);
Assert.AreEqual(node.GetFullName(), ReflectionUtilities.GetAssemblyQualifiedName(typeof(HelloTask)));
}
[TestMethod]
public void TestITackNode()
{
var node = ns.GetNode(typeof(ITask).AssemblyQualifiedName);
Assert.AreEqual(node.GetFullName(), ReflectionUtilities.GetAssemblyQualifiedName(typeof(ITask)));
}
[TestMethod]
public void TestNamedParameterIdentifier()
{
var node = ns.GetNode(typeof(TaskConfigurationOptions.Identifier).AssemblyQualifiedName);
Assert.AreEqual(node.GetFullName(), ReflectionUtilities.GetAssemblyQualifiedName(typeof(TaskConfigurationOptions.Identifier)));
}
[TestMethod]
public void TestInterface()
{
g(typeof(A));
g(typeof(MyInterface<int>));
g(typeof(MyInterface<string>));
g(typeof(B));
ITang tang = TangFactory.GetTang();
ICsConfigurationBuilder cb = tang.NewConfigurationBuilder();
cb.BindImplementation(GenericType<MyInterface<string>>.Class, GenericType<MyImplString>.Class);
cb.BindImplementation(GenericType<MyInterface<int>>.Class, GenericType<MyImplInt>.Class);
IConfiguration conf = cb.Build();
IInjector i = tang.NewInjector(conf);
var a = (A)i.GetInstance(typeof(A));
var implString = (MyImplString)i.GetInstance(typeof(MyImplString));
var implInt = (MyImplString)i.GetInstance(typeof(MyImplString));
var b = (B)i.GetInstance(typeof(B));
var c = (C)i.GetInstance(typeof(C));
Assert.IsNotNull(a);
Assert.IsNotNull(implString);
Assert.IsNotNull(implInt);
Assert.IsNotNull(b);
Assert.IsNotNull(c);
}
}
[NamedParameter]
class GenericTorture1 : Name<ISet<string>> {
}
[NamedParameter]
class GenericTorture2 : Name<ISet<ISet<string>>>
{
}
[NamedParameter]
class GenericTorture3 : Name<IDictionary<ISet<string>, ISet<string>>>
{
}
[NamedParameter]
class GenericTorture4 : Name<IDictionary<string, string>>
{
}
public interface MyInterface<T>
{
}
public class RepeatConstructorArg
{
[Inject]
public RepeatConstructorArg(int x, int y)
{
}
}
public class RepeatConstructorArgClasses
{
[Inject]
public RepeatConstructorArgClasses(A x, A y)
{
}
}
public class A : MyInterface<int>, MyInterface<string>
{
[Inject]
A()
{
}
}
public class MyImplString : MyInterface<string>
{
[Inject]
public MyImplString()
{
}
}
public class B
{
[Inject]
public B(MyInterface<string> b)
{
}
}
public class MyImplInt : MyInterface<int>
{
[Inject]
public MyImplInt()
{
}
}
public class C
{
[Inject]
public C(MyInterface<int> b)
{
}
}
public class LeafRepeatedConstructorArgClasses
{
public static class A
{
public class AA
{
}
}
public static class B
{
public class AA
{
}
}
public class C
{
[Inject]
public C(A.AA a, B.AA b)
{
}
}
}
class D
{
}
[NamedParameter]
class D1 : Name<D>
{
}
[NamedParameter]
class D2 : Name<D>
{
}
class NamedRepeatConstructorArgClasses
{
[Inject]
public NamedRepeatConstructorArgClasses([Parameter(typeof(D1))] D x, [Parameter(typeof(D2))] D y)
{
}
}
class NamedParameterTypeMismatch
{
[NamedParameter(Documentation = "doc.stuff", DefaultValue = "1")]
class Foo : Name<Int32>
{
}
[Inject]
public NamedParameterTypeMismatch([Parameter(Value = typeof(Foo))] string s)
{
}
}
class UnannotatedName : Name<string> {
}
interface I1
{
}
[NamedParameter(Documentation = "c")]
class AnnotatedNotName
{
}
[NamedParameter(Documentation = "c")]
class AnnotatedNameWrongInterface : I1
{
}
class UnAnnotatedNameMultipleInterfaces : Name<object>, I1
{
}
[NamedParameter(Documentation = "c")]
class AnnotatedNameMultipleInterfaces : Name<object>, I1
{
}
[NamedParameter(Documentation = "c")]
class NameWithConstructor : Name<object>
{
private NameWithConstructor(int i)
{
}
}
[NamedParameter]
class NameWithZeroArgInject : Name<object>
{
[Inject]
public NameWithZeroArgInject()
{
}
}
class InjectNonStaticLocalArgClass
{
class NonStaticLocal
{
}
[Inject]
InjectNonStaticLocalArgClass(NonStaticLocal x)
{
}
}
class InjectNonStaticLocalType
{
class NonStaticLocal
{
[Inject]
NonStaticLocal(NonStaticLocal x)
{
}
}
}
[NamedParameter(ShortName = "foo")]
public class ShortNameFooA : Name<String>
{
}
// when same short name is used, exception would throw when building the class hierarchy
[NamedParameter(ShortName = "foo")]
public class ShortNameFooB : Name<Int32>
{
}
class Nested
{
public class Inner
{
}
}
class AnonNested
{
public interface X
{
}
public class X1 : X
{
// int i;
}
public class Y1 : X
{
// int j;
}
public static X XObj = new X1();
public static X YObj = new Y1();
}
// Negative case: Int32 doesn't match string
[NamedParameter(DefaultClass = typeof(Int32))]
class BadName : Name<string>
{
}
// Negative case: Int32 doesn't match string in the ISet
[NamedParameter(DefaultClass = typeof(Int32))]
class BadNameForGeneric : Name<ISet<string>>
{
}
// Positive case: type matched. ISet is not in parsable list
[NamedParameter(DefaultClass = typeof(string))]
class GoodNameForGeneric : Name<ISet<string>>
{
}
[DefaultImplementation(typeof(string))]
interface IBadIfaceDefault
{
}
// negative case: type matched. However, string is in the parsable list and DefaultClass is not null.
[NamedParameter(DefaultClass = typeof(string))]
class BadParsableDefaultClass : Name<string>
{
}
}
| |
using Microsoft.IdentityModel.S2S.Protocols.OAuth2;
using Microsoft.IdentityModel.Tokens;
using Microsoft.SharePoint.Client;
using System;
using System.Net;
using System.Security.Principal;
using System.Web;
using System.Web.Configuration;
namespace Core.QueueWebJobUsageWeb
{
/// <summary>
/// Encapsulates all the information from SharePoint.
/// </summary>
public abstract class SharePointContext
{
public const string SPHostUrlKey = "SPHostUrl";
public const string SPAppWebUrlKey = "SPAppWebUrl";
public const string SPLanguageKey = "SPLanguage";
public const string SPClientTagKey = "SPClientTag";
public const string SPProductNumberKey = "SPProductNumber";
protected static readonly TimeSpan AccessTokenLifetimeTolerance = TimeSpan.FromMinutes(5.0);
private readonly Uri spHostUrl;
private readonly Uri spAppWebUrl;
private readonly string spLanguage;
private readonly string spClientTag;
private readonly string spProductNumber;
// <AccessTokenString, UtcExpiresOn>
protected Tuple<string, DateTime> userAccessTokenForSPHost;
protected Tuple<string, DateTime> userAccessTokenForSPAppWeb;
protected Tuple<string, DateTime> appOnlyAccessTokenForSPHost;
protected Tuple<string, DateTime> appOnlyAccessTokenForSPAppWeb;
/// <summary>
/// Gets the SharePoint host url from QueryString of the specified HTTP request.
/// </summary>
/// <param name="httpRequest">The specified HTTP request.</param>
/// <returns>The SharePoint host url. Returns <c>null</c> if the HTTP request doesn't contain the SharePoint host url.</returns>
public static Uri GetSPHostUrl(HttpRequestBase httpRequest)
{
if (httpRequest == null)
{
throw new ArgumentNullException("httpRequest");
}
string spHostUrlString = TokenHelper.EnsureTrailingSlash(httpRequest.QueryString[SPHostUrlKey]);
Uri spHostUrl;
if (Uri.TryCreate(spHostUrlString, UriKind.Absolute, out spHostUrl) &&
(spHostUrl.Scheme == Uri.UriSchemeHttp || spHostUrl.Scheme == Uri.UriSchemeHttps))
{
return spHostUrl;
}
return null;
}
/// <summary>
/// Gets the SharePoint host url from QueryString of the specified HTTP request.
/// </summary>
/// <param name="httpRequest">The specified HTTP request.</param>
/// <returns>The SharePoint host url. Returns <c>null</c> if the HTTP request doesn't contain the SharePoint host url.</returns>
public static Uri GetSPHostUrl(HttpRequest httpRequest)
{
return GetSPHostUrl(new HttpRequestWrapper(httpRequest));
}
/// <summary>
/// The SharePoint host url.
/// </summary>
public Uri SPHostUrl
{
get { return this.spHostUrl; }
}
/// <summary>
/// The SharePoint app web url.
/// </summary>
public Uri SPAppWebUrl
{
get { return this.spAppWebUrl; }
}
/// <summary>
/// The SharePoint language.
/// </summary>
public string SPLanguage
{
get { return this.spLanguage; }
}
/// <summary>
/// The SharePoint client tag.
/// </summary>
public string SPClientTag
{
get { return this.spClientTag; }
}
/// <summary>
/// The SharePoint product number.
/// </summary>
public string SPProductNumber
{
get { return this.spProductNumber; }
}
/// <summary>
/// The user access token for the SharePoint host.
/// </summary>
public abstract string UserAccessTokenForSPHost
{
get;
}
/// <summary>
/// The user access token for the SharePoint app web.
/// </summary>
public abstract string UserAccessTokenForSPAppWeb
{
get;
}
/// <summary>
/// The app only access token for the SharePoint host.
/// </summary>
public abstract string AppOnlyAccessTokenForSPHost
{
get;
}
/// <summary>
/// The app only access token for the SharePoint app web.
/// </summary>
public abstract string AppOnlyAccessTokenForSPAppWeb
{
get;
}
/// <summary>
/// Constructor.
/// </summary>
/// <param name="spHostUrl">The SharePoint host url.</param>
/// <param name="spAppWebUrl">The SharePoint app web url.</param>
/// <param name="spLanguage">The SharePoint language.</param>
/// <param name="spClientTag">The SharePoint client tag.</param>
/// <param name="spProductNumber">The SharePoint product number.</param>
protected SharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber)
{
if (spHostUrl == null)
{
throw new ArgumentNullException("spHostUrl");
}
if (string.IsNullOrEmpty(spLanguage))
{
throw new ArgumentNullException("spLanguage");
}
if (string.IsNullOrEmpty(spClientTag))
{
throw new ArgumentNullException("spClientTag");
}
if (string.IsNullOrEmpty(spProductNumber))
{
throw new ArgumentNullException("spProductNumber");
}
this.spHostUrl = spHostUrl;
this.spAppWebUrl = spAppWebUrl;
this.spLanguage = spLanguage;
this.spClientTag = spClientTag;
this.spProductNumber = spProductNumber;
}
/// <summary>
/// Creates a user ClientContext for the SharePoint host.
/// </summary>
/// <returns>A ClientContext instance.</returns>
public ClientContext CreateUserClientContextForSPHost()
{
return CreateClientContext(this.SPHostUrl, this.UserAccessTokenForSPHost);
}
/// <summary>
/// Creates a user ClientContext for the SharePoint app web.
/// </summary>
/// <returns>A ClientContext instance.</returns>
public ClientContext CreateUserClientContextForSPAppWeb()
{
return CreateClientContext(this.SPAppWebUrl, this.UserAccessTokenForSPAppWeb);
}
/// <summary>
/// Creates app only ClientContext for the SharePoint host.
/// </summary>
/// <returns>A ClientContext instance.</returns>
public ClientContext CreateAppOnlyClientContextForSPHost()
{
return CreateClientContext(this.SPHostUrl, this.AppOnlyAccessTokenForSPHost);
}
/// <summary>
/// Creates an app only ClientContext for the SharePoint app web.
/// </summary>
/// <returns>A ClientContext instance.</returns>
public ClientContext CreateAppOnlyClientContextForSPAppWeb()
{
return CreateClientContext(this.SPAppWebUrl, this.AppOnlyAccessTokenForSPAppWeb);
}
/// <summary>
/// Gets the database connection string from SharePoint for autohosted app.
/// </summary>
/// <returns>The database connection string. Returns <c>null</c> if the app is not autohosted or there is no database.</returns>
public string GetDatabaseConnectionString()
{
string dbConnectionString = null;
using (ClientContext clientContext = CreateAppOnlyClientContextForSPHost())
{
if (clientContext != null)
{
var result = AppInstance.RetrieveAppDatabaseConnectionString(clientContext);
clientContext.ExecuteQuery();
dbConnectionString = result.Value;
}
}
if (dbConnectionString == null)
{
const string LocalDBInstanceForDebuggingKey = "LocalDBInstanceForDebugging";
var dbConnectionStringSettings = WebConfigurationManager.ConnectionStrings[LocalDBInstanceForDebuggingKey];
dbConnectionString = dbConnectionStringSettings != null ? dbConnectionStringSettings.ConnectionString : null;
}
return dbConnectionString;
}
/// <summary>
/// Determines if the specified access token is valid.
/// It considers an access token as not valid if it is null, or it has expired.
/// </summary>
/// <param name="accessToken">The access token to verify.</param>
/// <returns>True if the access token is valid.</returns>
protected static bool IsAccessTokenValid(Tuple<string, DateTime> accessToken)
{
return accessToken != null &&
!string.IsNullOrEmpty(accessToken.Item1) &&
accessToken.Item2 > DateTime.UtcNow;
}
/// <summary>
/// Creates a ClientContext with the specified SharePoint site url and the access token.
/// </summary>
/// <param name="spSiteUrl">The site url.</param>
/// <param name="accessToken">The access token.</param>
/// <returns>A ClientContext instance.</returns>
private static ClientContext CreateClientContext(Uri spSiteUrl, string accessToken)
{
if (spSiteUrl != null && !string.IsNullOrEmpty(accessToken))
{
return TokenHelper.GetClientContextWithAccessToken(spSiteUrl.AbsoluteUri, accessToken);
}
return null;
}
}
/// <summary>
/// Redirection status.
/// </summary>
public enum RedirectionStatus
{
Ok,
ShouldRedirect,
CanNotRedirect
}
/// <summary>
/// Provides SharePointContext instances.
/// </summary>
public abstract class SharePointContextProvider
{
private static SharePointContextProvider current;
/// <summary>
/// The current SharePointContextProvider instance.
/// </summary>
public static SharePointContextProvider Current
{
get { return SharePointContextProvider.current; }
}
/// <summary>
/// Initializes the default SharePointContextProvider instance.
/// </summary>
static SharePointContextProvider()
{
if (!TokenHelper.IsHighTrustApp())
{
SharePointContextProvider.current = new SharePointAcsContextProvider();
}
else
{
SharePointContextProvider.current = new SharePointHighTrustContextProvider();
}
}
/// <summary>
/// Registers the specified SharePointContextProvider instance as current.
/// It should be called by Application_Start() in Global.asax.
/// </summary>
/// <param name="provider">The SharePointContextProvider to be set as current.</param>
public static void Register(SharePointContextProvider provider)
{
if (provider == null)
{
throw new ArgumentNullException("provider");
}
SharePointContextProvider.current = provider;
}
/// <summary>
/// Checks if it is necessary to redirect to SharePoint for user to authenticate.
/// </summary>
/// <param name="httpContext">The HTTP context.</param>
/// <param name="redirectUrl">The redirect url to SharePoint if the status is ShouldRedirect. <c>Null</c> if the status is Ok or CanNotRedirect.</param>
/// <returns>Redirection status.</returns>
public static RedirectionStatus CheckRedirectionStatus(HttpContextBase httpContext, out Uri redirectUrl)
{
if (httpContext == null)
{
throw new ArgumentNullException("httpContext");
}
redirectUrl = null;
if (SharePointContextProvider.Current.GetSharePointContext(httpContext) != null)
{
return RedirectionStatus.Ok;
}
const string SPHasRedirectedToSharePointKey = "SPHasRedirectedToSharePoint";
if (!string.IsNullOrEmpty(httpContext.Request.QueryString[SPHasRedirectedToSharePointKey]))
{
return RedirectionStatus.CanNotRedirect;
}
Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request);
if (spHostUrl == null)
{
return RedirectionStatus.CanNotRedirect;
}
if (StringComparer.OrdinalIgnoreCase.Equals(httpContext.Request.HttpMethod, "POST"))
{
return RedirectionStatus.CanNotRedirect;
}
Uri requestUrl = httpContext.Request.Url;
var queryNameValueCollection = HttpUtility.ParseQueryString(requestUrl.Query);
// Removes the values that are included in {StandardTokens}, as {StandardTokens} will be inserted at the beginning of the query string.
queryNameValueCollection.Remove(SharePointContext.SPHostUrlKey);
queryNameValueCollection.Remove(SharePointContext.SPAppWebUrlKey);
queryNameValueCollection.Remove(SharePointContext.SPLanguageKey);
queryNameValueCollection.Remove(SharePointContext.SPClientTagKey);
queryNameValueCollection.Remove(SharePointContext.SPProductNumberKey);
// Adds SPHasRedirectedToSharePoint=1.
queryNameValueCollection.Add(SPHasRedirectedToSharePointKey, "1");
UriBuilder returnUrlBuilder = new UriBuilder(requestUrl);
returnUrlBuilder.Query = queryNameValueCollection.ToString();
// Inserts StandardTokens.
const string StandardTokens = "{StandardTokens}";
string returnUrlString = returnUrlBuilder.Uri.AbsoluteUri;
returnUrlString = returnUrlString.Insert(returnUrlString.IndexOf("?") + 1, StandardTokens + "&");
// Constructs redirect url.
string redirectUrlString = TokenHelper.GetAppContextTokenRequestUrl(spHostUrl.AbsoluteUri, Uri.EscapeDataString(returnUrlString));
redirectUrl = new Uri(redirectUrlString, UriKind.Absolute);
return RedirectionStatus.ShouldRedirect;
}
/// <summary>
/// Checks if it is necessary to redirect to SharePoint for user to authenticate.
/// </summary>
/// <param name="httpContext">The HTTP context.</param>
/// <param name="redirectUrl">The redirect url to SharePoint if the status is ShouldRedirect. <c>Null</c> if the status is Ok or CanNotRedirect.</param>
/// <returns>Redirection status.</returns>
public static RedirectionStatus CheckRedirectionStatus(HttpContext httpContext, out Uri redirectUrl)
{
return CheckRedirectionStatus(new HttpContextWrapper(httpContext), out redirectUrl);
}
/// <summary>
/// Creates a SharePointContext instance with the specified HTTP request.
/// </summary>
/// <param name="httpRequest">The HTTP request.</param>
/// <returns>The SharePointContext instance. Returns <c>null</c> if errors occur.</returns>
public SharePointContext CreateSharePointContext(HttpRequestBase httpRequest)
{
if (httpRequest == null)
{
throw new ArgumentNullException("httpRequest");
}
// SPHostUrl
Uri spHostUrl = SharePointContext.GetSPHostUrl(httpRequest);
if (spHostUrl == null)
{
return null;
}
// SPAppWebUrl
string spAppWebUrlString = TokenHelper.EnsureTrailingSlash(httpRequest.QueryString[SharePointContext.SPAppWebUrlKey]);
Uri spAppWebUrl;
if (!Uri.TryCreate(spAppWebUrlString, UriKind.Absolute, out spAppWebUrl) ||
!(spAppWebUrl.Scheme == Uri.UriSchemeHttp || spAppWebUrl.Scheme == Uri.UriSchemeHttps))
{
spAppWebUrl = null;
}
// SPLanguage
string spLanguage = httpRequest.QueryString[SharePointContext.SPLanguageKey];
if (string.IsNullOrEmpty(spLanguage))
{
return null;
}
// SPClientTag
string spClientTag = httpRequest.QueryString[SharePointContext.SPClientTagKey];
if (string.IsNullOrEmpty(spClientTag))
{
return null;
}
// SPProductNumber
string spProductNumber = httpRequest.QueryString[SharePointContext.SPProductNumberKey];
if (string.IsNullOrEmpty(spProductNumber))
{
return null;
}
return CreateSharePointContext(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber, httpRequest);
}
/// <summary>
/// Creates a SharePointContext instance with the specified HTTP request.
/// </summary>
/// <param name="httpRequest">The HTTP request.</param>
/// <returns>The SharePointContext instance. Returns <c>null</c> if errors occur.</returns>
public SharePointContext CreateSharePointContext(HttpRequest httpRequest)
{
return CreateSharePointContext(new HttpRequestWrapper(httpRequest));
}
/// <summary>
/// Gets a SharePointContext instance associated with the specified HTTP context.
/// </summary>
/// <param name="httpContext">The HTTP context.</param>
/// <returns>The SharePointContext instance. Returns <c>null</c> if not found and a new instance can't be created.</returns>
public SharePointContext GetSharePointContext(HttpContextBase httpContext)
{
if (httpContext == null)
{
throw new ArgumentNullException("httpContext");
}
Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request);
if (spHostUrl == null)
{
return null;
}
SharePointContext spContext = LoadSharePointContext(httpContext);
if (spContext == null || !ValidateSharePointContext(spContext, httpContext))
{
spContext = CreateSharePointContext(httpContext.Request);
if (spContext != null)
{
SaveSharePointContext(spContext, httpContext);
}
}
return spContext;
}
/// <summary>
/// Gets a SharePointContext instance associated with the specified HTTP context.
/// </summary>
/// <param name="httpContext">The HTTP context.</param>
/// <returns>The SharePointContext instance. Returns <c>null</c> if not found and a new instance can't be created.</returns>
public SharePointContext GetSharePointContext(HttpContext httpContext)
{
return GetSharePointContext(new HttpContextWrapper(httpContext));
}
/// <summary>
/// Creates a SharePointContext instance.
/// </summary>
/// <param name="spHostUrl">The SharePoint host url.</param>
/// <param name="spAppWebUrl">The SharePoint app web url.</param>
/// <param name="spLanguage">The SharePoint language.</param>
/// <param name="spClientTag">The SharePoint client tag.</param>
/// <param name="spProductNumber">The SharePoint product number.</param>
/// <param name="httpRequest">The HTTP request.</param>
/// <returns>The SharePointContext instance. Returns <c>null</c> if errors occur.</returns>
protected abstract SharePointContext CreateSharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, HttpRequestBase httpRequest);
/// <summary>
/// Validates if the given SharePointContext can be used with the specified HTTP context.
/// </summary>
/// <param name="spContext">The SharePointContext.</param>
/// <param name="httpContext">The HTTP context.</param>
/// <returns>True if the given SharePointContext can be used with the specified HTTP context.</returns>
protected abstract bool ValidateSharePointContext(SharePointContext spContext, HttpContextBase httpContext);
/// <summary>
/// Loads the SharePointContext instance associated with the specified HTTP context.
/// </summary>
/// <param name="httpContext">The HTTP context.</param>
/// <returns>The SharePointContext instance. Returns <c>null</c> if not found.</returns>
protected abstract SharePointContext LoadSharePointContext(HttpContextBase httpContext);
/// <summary>
/// Saves the specified SharePointContext instance associated with the specified HTTP context.
/// <c>null</c> is accepted for clearing the SharePointContext instance associated with the HTTP context.
/// </summary>
/// <param name="spContext">The SharePointContext instance to be saved, or <c>null</c>.</param>
/// <param name="httpContext">The HTTP context.</param>
protected abstract void SaveSharePointContext(SharePointContext spContext, HttpContextBase httpContext);
}
#region ACS
/// <summary>
/// Encapsulates all the information from SharePoint in ACS mode.
/// </summary>
public class SharePointAcsContext : SharePointContext
{
private readonly string contextToken;
private readonly SharePointContextToken contextTokenObj;
/// <summary>
/// The context token.
/// </summary>
public string ContextToken
{
get { return this.contextTokenObj.ValidTo > DateTime.UtcNow ? this.contextToken : null; }
}
/// <summary>
/// The context token's "CacheKey" claim.
/// </summary>
public string CacheKey
{
get { return this.contextTokenObj.ValidTo > DateTime.UtcNow ? this.contextTokenObj.CacheKey : null; }
}
/// <summary>
/// The context token's "refreshtoken" claim.
/// </summary>
public string RefreshToken
{
get { return this.contextTokenObj.ValidTo > DateTime.UtcNow ? this.contextTokenObj.RefreshToken : null; }
}
public override string UserAccessTokenForSPHost
{
get
{
return GetAccessTokenString(ref this.userAccessTokenForSPHost,
() => TokenHelper.GetAccessToken(this.contextTokenObj, this.SPHostUrl.Authority));
}
}
public override string UserAccessTokenForSPAppWeb
{
get
{
if (this.SPAppWebUrl == null)
{
return null;
}
return GetAccessTokenString(ref this.userAccessTokenForSPAppWeb,
() => TokenHelper.GetAccessToken(this.contextTokenObj, this.SPAppWebUrl.Authority));
}
}
public override string AppOnlyAccessTokenForSPHost
{
get
{
return GetAccessTokenString(ref this.appOnlyAccessTokenForSPHost,
() => TokenHelper.GetAppOnlyAccessToken(TokenHelper.SharePointPrincipal, this.SPHostUrl.Authority, TokenHelper.GetRealmFromTargetUrl(this.SPHostUrl)));
}
}
public override string AppOnlyAccessTokenForSPAppWeb
{
get
{
if (this.SPAppWebUrl == null)
{
return null;
}
return GetAccessTokenString(ref this.appOnlyAccessTokenForSPAppWeb,
() => TokenHelper.GetAppOnlyAccessToken(TokenHelper.SharePointPrincipal, this.SPAppWebUrl.Authority, TokenHelper.GetRealmFromTargetUrl(this.SPAppWebUrl)));
}
}
public SharePointAcsContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, string contextToken, SharePointContextToken contextTokenObj)
: base(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber)
{
if (string.IsNullOrEmpty(contextToken))
{
throw new ArgumentNullException("contextToken");
}
if (contextTokenObj == null)
{
throw new ArgumentNullException("contextTokenObj");
}
this.contextToken = contextToken;
this.contextTokenObj = contextTokenObj;
}
/// <summary>
/// Ensures the access token is valid and returns it.
/// </summary>
/// <param name="accessToken">The access token to verify.</param>
/// <param name="tokenRenewalHandler">The token renewal handler.</param>
/// <returns>The access token string.</returns>
private static string GetAccessTokenString(ref Tuple<string, DateTime> accessToken, Func<OAuth2AccessTokenResponse> tokenRenewalHandler)
{
RenewAccessTokenIfNeeded(ref accessToken, tokenRenewalHandler);
return IsAccessTokenValid(accessToken) ? accessToken.Item1 : null;
}
/// <summary>
/// Renews the access token if it is not valid.
/// </summary>
/// <param name="accessToken">The access token to renew.</param>
/// <param name="tokenRenewalHandler">The token renewal handler.</param>
private static void RenewAccessTokenIfNeeded(ref Tuple<string, DateTime> accessToken, Func<OAuth2AccessTokenResponse> tokenRenewalHandler)
{
if (IsAccessTokenValid(accessToken))
{
return;
}
try
{
OAuth2AccessTokenResponse oAuth2AccessTokenResponse = tokenRenewalHandler();
DateTime expiresOn = oAuth2AccessTokenResponse.ExpiresOn;
if ((expiresOn - oAuth2AccessTokenResponse.NotBefore) > AccessTokenLifetimeTolerance)
{
// Make the access token get renewed a bit earlier than the time when it expires
// so that the calls to SharePoint with it will have enough time to complete successfully.
expiresOn -= AccessTokenLifetimeTolerance;
}
accessToken = Tuple.Create(oAuth2AccessTokenResponse.AccessToken, expiresOn);
}
catch (WebException)
{
}
}
}
/// <summary>
/// Default provider for SharePointAcsContext.
/// </summary>
public class SharePointAcsContextProvider : SharePointContextProvider
{
private const string SPContextKey = "SPContext";
private const string SPCacheKeyKey = "SPCacheKey";
protected override SharePointContext CreateSharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, HttpRequestBase httpRequest)
{
string contextTokenString = TokenHelper.GetContextTokenFromRequest(httpRequest);
if (string.IsNullOrEmpty(contextTokenString))
{
return null;
}
SharePointContextToken contextToken = null;
try
{
contextToken = TokenHelper.ReadAndValidateContextToken(contextTokenString, httpRequest.Url.Authority);
}
catch (WebException)
{
return null;
}
catch (AudienceUriValidationFailedException)
{
return null;
}
return new SharePointAcsContext(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber, contextTokenString, contextToken);
}
protected override bool ValidateSharePointContext(SharePointContext spContext, HttpContextBase httpContext)
{
SharePointAcsContext spAcsContext = spContext as SharePointAcsContext;
if (spAcsContext != null)
{
Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request);
string contextToken = TokenHelper.GetContextTokenFromRequest(httpContext.Request);
HttpCookie spCacheKeyCookie = httpContext.Request.Cookies[SPCacheKeyKey];
string spCacheKey = spCacheKeyCookie != null ? spCacheKeyCookie.Value : null;
return spHostUrl == spAcsContext.SPHostUrl &&
!string.IsNullOrEmpty(spAcsContext.CacheKey) &&
spCacheKey == spAcsContext.CacheKey &&
!string.IsNullOrEmpty(spAcsContext.ContextToken) &&
(string.IsNullOrEmpty(contextToken) || contextToken == spAcsContext.ContextToken);
}
return false;
}
protected override SharePointContext LoadSharePointContext(HttpContextBase httpContext)
{
return httpContext.Session[SPContextKey] as SharePointAcsContext;
}
protected override void SaveSharePointContext(SharePointContext spContext, HttpContextBase httpContext)
{
SharePointAcsContext spAcsContext = spContext as SharePointAcsContext;
if (spAcsContext != null)
{
HttpCookie spCacheKeyCookie = new HttpCookie(SPCacheKeyKey)
{
Value = spAcsContext.CacheKey,
Secure = true,
HttpOnly = true
};
httpContext.Response.AppendCookie(spCacheKeyCookie);
}
httpContext.Session[SPContextKey] = spAcsContext;
}
}
#endregion ACS
#region HighTrust
/// <summary>
/// Encapsulates all the information from SharePoint in HighTrust mode.
/// </summary>
public class SharePointHighTrustContext : SharePointContext
{
private readonly WindowsIdentity logonUserIdentity;
/// <summary>
/// The Windows identity for the current user.
/// </summary>
public WindowsIdentity LogonUserIdentity
{
get { return this.logonUserIdentity; }
}
public override string UserAccessTokenForSPHost
{
get
{
return GetAccessTokenString(ref this.userAccessTokenForSPHost,
() => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPHostUrl, this.LogonUserIdentity));
}
}
public override string UserAccessTokenForSPAppWeb
{
get
{
if (this.SPAppWebUrl == null)
{
return null;
}
return GetAccessTokenString(ref this.userAccessTokenForSPAppWeb,
() => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPAppWebUrl, this.LogonUserIdentity));
}
}
public override string AppOnlyAccessTokenForSPHost
{
get
{
return GetAccessTokenString(ref this.appOnlyAccessTokenForSPHost,
() => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPHostUrl, null));
}
}
public override string AppOnlyAccessTokenForSPAppWeb
{
get
{
if (this.SPAppWebUrl == null)
{
return null;
}
return GetAccessTokenString(ref this.appOnlyAccessTokenForSPAppWeb,
() => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPAppWebUrl, null));
}
}
public SharePointHighTrustContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, WindowsIdentity logonUserIdentity)
: base(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber)
{
if (logonUserIdentity == null)
{
throw new ArgumentNullException("logonUserIdentity");
}
this.logonUserIdentity = logonUserIdentity;
}
/// <summary>
/// Ensures the access token is valid and returns it.
/// </summary>
/// <param name="accessToken">The access token to verify.</param>
/// <param name="tokenRenewalHandler">The token renewal handler.</param>
/// <returns>The access token string.</returns>
private static string GetAccessTokenString(ref Tuple<string, DateTime> accessToken, Func<string> tokenRenewalHandler)
{
RenewAccessTokenIfNeeded(ref accessToken, tokenRenewalHandler);
return IsAccessTokenValid(accessToken) ? accessToken.Item1 : null;
}
/// <summary>
/// Renews the access token if it is not valid.
/// </summary>
/// <param name="accessToken">The access token to renew.</param>
/// <param name="tokenRenewalHandler">The token renewal handler.</param>
private static void RenewAccessTokenIfNeeded(ref Tuple<string, DateTime> accessToken, Func<string> tokenRenewalHandler)
{
if (IsAccessTokenValid(accessToken))
{
return;
}
DateTime expiresOn = DateTime.UtcNow.Add(TokenHelper.HighTrustAccessTokenLifetime);
if (TokenHelper.HighTrustAccessTokenLifetime > AccessTokenLifetimeTolerance)
{
// Make the access token get renewed a bit earlier than the time when it expires
// so that the calls to SharePoint with it will have enough time to complete successfully.
expiresOn -= AccessTokenLifetimeTolerance;
}
accessToken = Tuple.Create(tokenRenewalHandler(), expiresOn);
}
}
/// <summary>
/// Default provider for SharePointHighTrustContext.
/// </summary>
public class SharePointHighTrustContextProvider : SharePointContextProvider
{
private const string SPContextKey = "SPContext";
protected override SharePointContext CreateSharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, HttpRequestBase httpRequest)
{
WindowsIdentity logonUserIdentity = httpRequest.LogonUserIdentity;
if (logonUserIdentity == null || !logonUserIdentity.IsAuthenticated || logonUserIdentity.IsGuest || logonUserIdentity.User == null)
{
return null;
}
return new SharePointHighTrustContext(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber, logonUserIdentity);
}
protected override bool ValidateSharePointContext(SharePointContext spContext, HttpContextBase httpContext)
{
SharePointHighTrustContext spHighTrustContext = spContext as SharePointHighTrustContext;
if (spHighTrustContext != null)
{
Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request);
WindowsIdentity logonUserIdentity = httpContext.Request.LogonUserIdentity;
return spHostUrl == spHighTrustContext.SPHostUrl &&
logonUserIdentity != null &&
logonUserIdentity.IsAuthenticated &&
!logonUserIdentity.IsGuest &&
logonUserIdentity.User == spHighTrustContext.LogonUserIdentity.User;
}
return false;
}
protected override SharePointContext LoadSharePointContext(HttpContextBase httpContext)
{
return httpContext.Session[SPContextKey] as SharePointHighTrustContext;
}
protected override void SaveSharePointContext(SharePointContext spContext, HttpContextBase httpContext)
{
httpContext.Session[SPContextKey] = spContext as SharePointHighTrustContext;
}
}
#endregion HighTrust
}
| |
// <copyright file="EdgeDriverService.cs" company="WebDriver Committers">
// Licensed to the Software Freedom Conservancy (SFC) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The SFC 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 System;
using System.Globalization;
using System.Text;
using OpenQA.Selenium.Internal;
using OpenQA.Selenium.Chromium;
namespace OpenQA.Selenium.Edge
{
/// <summary>
/// Exposes the service provided by the native WebDriver executable.
/// </summary>
public sealed class EdgeDriverService : ChromiumDriverService
{
private const string MicrosoftWebDriverServiceFileName = "MicrosoftWebDriver.exe";
private const string MSEdgeDriverServiceFileName = "msedgedriver";
private static readonly Uri MicrosoftWebDriverDownloadUrl = new Uri("https://developer.microsoft.com/en-us/microsoft-edge/tools/webdriver/");
// Engine switching
private readonly bool usingChromium;
// Legacy properties
private string host;
private string package;
private bool? useSpecCompliantProtocol;
/// <summary>
/// Initializes a new instance of the <see cref="EdgeDriverService"/> class.
/// </summary>
/// <param name="executablePath">The full path to the EdgeDriver executable.</param>
/// <param name="executableFileName">The file name of the EdgeDriver executable.</param>
/// <param name="port">The port on which the EdgeDriver executable should listen.</param>
/// <param name="usingChromium">Whether to use the Legacy or Chromium EdgeDriver executable.</param>
private EdgeDriverService(string executablePath, string executableFileName, int port, bool usingChromium)
: base(executablePath, executableFileName, port, MicrosoftWebDriverDownloadUrl)
{
this.usingChromium = usingChromium;
}
/// <summary>
/// Gets a value indicating whether the driver service is using Edge Chromium.
/// </summary>
public bool UsingChromium
{
get { return this.usingChromium; }
}
/// <summary>
/// Gets or sets the value of the host adapter on which the Edge driver service should listen for connections.
/// </summary>
public string Host
{
get { return this.host; }
set { this.host = value; }
}
/// <summary>
/// Gets or sets the value of the package the Edge driver service will launch and automate.
/// </summary>
public string Package
{
get { return this.package; }
set { this.package = value; }
}
/// <summary>
/// Gets or sets a value indicating whether the service should use verbose logging.
/// </summary>
public bool UseVerboseLogging
{
get { return this.EnableVerboseLogging; }
set { this.EnableVerboseLogging = value; }
}
/// <summary>
/// Gets or sets a value indicating whether the <see cref="EdgeDriverService"/> instance
/// should use the a protocol dialect compliant with the W3C WebDriver Specification.
/// </summary>
/// <remarks>
/// Setting this property to a non-<see langword="null"/> value for driver
/// executables matched to versions of Windows before the 2018 Fall Creators
/// Update will result in the driver executable shutting down without
/// execution, and all commands will fail. Do not set this property unless
/// you are certain your version of the MicrosoftWebDriver.exe supports the
/// --w3c and --jwp command-line arguments.
/// </remarks>
public bool? UseSpecCompliantProtocol
{
get { return this.useSpecCompliantProtocol; }
set { this.useSpecCompliantProtocol = value; }
}
/// <summary>
/// Gets a value indicating whether the service has a shutdown API that can be called to terminate
/// it gracefully before forcing a termination.
/// </summary>
protected override bool HasShutdown
{
get
{
if (this.usingChromium || (this.useSpecCompliantProtocol.HasValue && !this.useSpecCompliantProtocol.Value))
{
return base.HasShutdown;
}
return false;
}
}
/// <summary>
/// Gets a value indicating the time to wait for the service to terminate before forcing it to terminate.
/// </summary>
protected override TimeSpan TerminationTimeout
{
// Use a very small timeout for terminating the Edge driver,
// because the executable does not have a clean shutdown command,
// which means we have to kill the process. Using a short timeout
// gets us to the termination point much faster.
get
{
if (this.usingChromium || (this.useSpecCompliantProtocol.HasValue && !this.useSpecCompliantProtocol.Value))
{
return base.TerminationTimeout;
}
return TimeSpan.FromMilliseconds(100);
}
}
/// <summary>
/// Gets the command-line arguments for the driver service.
/// </summary>
protected override string CommandLineArguments
{
get
{
return this.usingChromium ? base.CommandLineArguments : LegacyCommandLineArguments;
}
}
private string LegacyCommandLineArguments
{
get
{
StringBuilder argsBuilder = new StringBuilder(string.Format(CultureInfo.InvariantCulture, "--port={0}", this.Port));
if (!string.IsNullOrEmpty(this.host))
{
argsBuilder.Append(string.Format(CultureInfo.InvariantCulture, " --host={0}", this.host));
}
if (!string.IsNullOrEmpty(this.package))
{
argsBuilder.Append(string.Format(CultureInfo.InvariantCulture, " --package={0}", this.package));
}
if (this.UseVerboseLogging)
{
argsBuilder.Append(" --verbose");
}
if (this.SuppressInitialDiagnosticInformation)
{
argsBuilder.Append(" --silent");
}
if (this.useSpecCompliantProtocol.HasValue)
{
if (this.useSpecCompliantProtocol.Value)
{
argsBuilder.Append(" --w3c");
}
else
{
argsBuilder.Append(" --jwp");
}
}
return argsBuilder.ToString();
}
}
/// <summary>
/// Creates an instance of the EdgeDriverService for Edge Chromium.
/// </summary>
/// <returns>A EdgeDriverService that implements default settings.</returns>
public static EdgeDriverService CreateChromiumService()
{
return CreateDefaultServiceFromOptions(new EdgeOptions() { UseChromium = true });
}
/// <summary>
/// Creates an instance of the EdgeDriverService for Edge Chromium using a specified path to the WebDriver executable.
/// </summary>
/// <param name="driverPath">The directory containing the WebDriver executable.</param>
/// <returns>A EdgeDriverService using a random port.</returns>
public static EdgeDriverService CreateChromiumService(string driverPath)
{
return CreateDefaultServiceFromOptions(driverPath, EdgeDriverServiceFileName(true), new EdgeOptions() { UseChromium = true });
}
/// <summary>
/// Creates an instance of the EdgeDriverService for Edge Chromium using a specified path to the WebDriver executable with the given name.
/// </summary>
/// <param name="driverPath">The directory containing the WebDriver executable.</param>
/// <param name="driverExecutableFileName">The name of the WebDriver executable file.</param>
/// <returns>A EdgeDriverService using a random port.</returns>
public static EdgeDriverService CreateChromiumService(string driverPath, string driverExecutableFileName)
{
return CreateDefaultServiceFromOptions(driverPath, driverExecutableFileName, new EdgeOptions() { UseChromium = true });
}
/// <summary>
/// Creates an instance of the EdgeDriverService for Edge Chromium using a specified path to the WebDriver executable with the given name and listening port.
/// </summary>
/// <param name="driverPath">The directory containing the WebDriver executable.</param>
/// <param name="driverExecutableFileName">The name of the WebDriver executable file</param>
/// <param name="port">The port number on which the driver will listen</param>
/// <returns>A EdgeDriverService using the specified port.</returns>
public static EdgeDriverService CreateChromiumService(string driverPath, string driverExecutableFileName, int port)
{
return CreateDefaultServiceFromOptions(driverPath, driverExecutableFileName, port, new EdgeOptions() { UseChromium = true });
}
/// <summary>
/// Creates a default instance of the EdgeDriverService.
/// </summary>
/// <returns>A EdgeDriverService that implements default settings.</returns>
public static EdgeDriverService CreateDefaultService()
{
return CreateDefaultServiceFromOptions(new EdgeOptions());
}
/// <summary>
/// Creates a default instance of the EdgeDriverService using a specified path to the WebDriver executable.
/// </summary>
/// <param name="driverPath">The directory containing the WebDriver executable.</param>
/// <returns>A EdgeDriverService using a random port.</returns>
public static EdgeDriverService CreateDefaultService(string driverPath)
{
return CreateDefaultServiceFromOptions(driverPath, EdgeDriverServiceFileName(false), new EdgeOptions());
}
/// <summary>
/// Creates a default instance of the EdgeDriverService using a specified path to the WebDriver executable with the given name.
/// </summary>
/// <param name="driverPath">The directory containing the WebDriver executable.</param>
/// <param name="driverExecutableFileName">The name of the WebDriver executable file.</param>
/// <returns>A EdgeDriverService using a random port.</returns>
public static EdgeDriverService CreateDefaultService(string driverPath, string driverExecutableFileName)
{
return CreateDefaultServiceFromOptions(driverPath, driverExecutableFileName, new EdgeOptions());
}
/// <summary>
/// Creates a default instance of the EdgeDriverService using a specified path to the WebDriver executable with the given name and listening port.
/// </summary>
/// <param name="driverPath">The directory containing the WebDriver executable.</param>
/// <param name="driverExecutableFileName">The name of the WebDriver executable file</param>
/// <param name="port">The port number on which the driver will listen</param>
/// <returns>A EdgeDriverService using the specified port.</returns>
public static EdgeDriverService CreateDefaultService(string driverPath, string driverExecutableFileName, int port)
{
return CreateDefaultServiceFromOptions(driverPath, driverExecutableFileName, port, new EdgeOptions());
}
/// <summary>
/// Creates a default instance of the EdgeDriverService.
/// </summary>
/// <param name="options">An <see cref="EdgeOptions"/> object containing options for the service.</param>
/// <returns>A EdgeDriverService that implements default settings.</returns>
public static EdgeDriverService CreateDefaultServiceFromOptions(EdgeOptions options)
{
string serviceDirectory = DriverService.FindDriverServiceExecutable(EdgeDriverServiceFileName(options.UseChromium), MicrosoftWebDriverDownloadUrl);
return CreateDefaultServiceFromOptions(serviceDirectory, options);
}
/// <summary>
/// Creates a default instance of the EdgeDriverService using a specified path to the WebDriver executable.
/// </summary>
/// <param name="driverPath">The directory containing the WebDriver executable.</param>
/// <param name="options">An <see cref="EdgeOptions"/> object containing options for the service.</param>
/// <returns>A EdgeDriverService using a random port.</returns>
public static EdgeDriverService CreateDefaultServiceFromOptions(string driverPath, EdgeOptions options)
{
return CreateDefaultServiceFromOptions(driverPath, EdgeDriverServiceFileName(options.UseChromium), options);
}
/// <summary>
/// Creates a default instance of the EdgeDriverService using a specified path to the WebDriver executable with the given name.
/// </summary>
/// <param name="driverPath">The directory containing the WebDriver executable.</param>
/// <param name="driverExecutableFileName">The name of the WebDriver executable file.</param>
/// <param name="options">An <see cref="EdgeOptions"/> object containing options for the service.</param>
/// <returns>A EdgeDriverService using a random port.</returns>
public static EdgeDriverService CreateDefaultServiceFromOptions(string driverPath, string driverExecutableFileName, EdgeOptions options)
{
return CreateDefaultServiceFromOptions(driverPath, driverExecutableFileName, PortUtilities.FindFreePort(), options);
}
/// <summary>
/// Creates a default instance of the EdgeDriverService using a specified path to the WebDriver executable with the given name and listening port.
/// </summary>
/// <param name="driverPath">The directory containing the WebDriver executable.</param>
/// <param name="driverExecutableFileName">The name of the WebDriver executable file</param>
/// <param name="port">The port number on which the driver will listen</param>
/// <param name="options">An <see cref="EdgeOptions"/> object containing options for the service.</param>
/// <returns>A EdgeDriverService using the specified port.</returns>
public static EdgeDriverService CreateDefaultServiceFromOptions(string driverPath, string driverExecutableFileName, int port, EdgeOptions options)
{
return new EdgeDriverService(driverPath, driverExecutableFileName, port, options.UseChromium);
}
private static string EdgeDriverServiceFileName(bool useChromium)
{
return useChromium ? ChromiumDriverServiceFileName(MSEdgeDriverServiceFileName) : MicrosoftWebDriverServiceFileName;
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using Baseline;
using Weasel.Postgresql;
using Newtonsoft.Json.Linq;
using Shouldly;
namespace Marten.Schema.Testing
{
public static class Exception<T> where T : Exception
{
public static T ShouldBeThrownBy(Action action)
{
T exception = null;
try
{
action();
}
catch (Exception e)
{
exception = e.ShouldBeOfType<T>();
}
exception.ShouldNotBeNull("An exception was expected, but not thrown by the given action.");
return exception;
}
public static async Task<T> ShouldBeThrownByAsync(Func<Task> action)
{
T exception = null;
try
{
await action();
}
catch (Exception e)
{
exception = e.ShouldBeOfType<T>();
}
exception.ShouldNotBeNull("An exception was expected, but not thrown by the given action.");
return exception;
}
}
public delegate void MethodThatThrows();
public static class SpecificationExtensions
{
public static void ShouldBeSemanticallySameJsonAs(this string json, string expectedJson)
{
var actual = JToken.Parse(json);
var expected = JToken.Parse(expectedJson);
JToken.DeepEquals(expected, actual).ShouldBeTrue($"Expected:\n{expectedJson}\nGot:\n{json}");
}
public static void ShouldContain<T>(this IEnumerable<T> actual, Func<T, bool> expected)
{
actual.Count().ShouldBeGreaterThan(0);
actual.Any(expected).ShouldBeTrue();
}
public static void ShouldHaveTheSameElementsAs<T>(this IEnumerable<T> actual, IEnumerable<T> expected)
{
var actualList = (actual is IList tempActual) ? tempActual : actual.ToList();
var expectedList = (expected is IList tempExpected) ? tempExpected : expected.ToList();
ShouldHaveTheSameElementsAs(actualList, expectedList);
}
public static void ShouldHaveTheSameElementsAs<T>(this IEnumerable<T> actual, params T[] expected)
{
var actualList = (actual is IList tempActual) ? tempActual : actual.ToList();
var expectedList = (expected is IList tempExpected) ? tempExpected : expected.ToList();
ShouldHaveTheSameElementsAs(actualList, expectedList);
}
public static void ShouldHaveTheSameElementsAs(this IList actual, IList expected)
{
actual.ShouldNotBeNull();
expected.ShouldNotBeNull();
try
{
actual.Count.ShouldBe(expected.Count, $"Actual was " + actual.OfType<object>().Select(x => x.ToString()).Join(", "));
for (var i = 0; i < actual.Count; i++)
{
actual[i].ShouldBe(expected[i]);
}
}
catch (Exception)
{
Debug.WriteLine("ACTUAL:");
foreach (var o in actual)
{
Debug.WriteLine(o);
}
throw;
}
}
public static void ShouldBeNull(this object anObject)
{
anObject.ShouldBe(null);
}
public static void ShouldNotBeNull(this object anObject)
{
anObject.ShouldNotBe(null);
}
public static object ShouldBeTheSameAs(this object actual, object expected)
{
ReferenceEquals(actual, expected).ShouldBeTrue();
return expected;
}
public static T IsType<T>(this object actual)
{
actual.ShouldBeOfType(typeof(T));
return (T)actual;
}
public static object ShouldNotBeTheSameAs(this object actual, object expected)
{
ReferenceEquals(actual, expected).ShouldBeFalse();
return expected;
}
public static void ShouldNotBeOfType<T>(this object actual)
{
actual.ShouldNotBeOfType(typeof(T));
}
public static void ShouldNotBeOfType(this object actual, Type expected)
{
actual.GetType().ShouldNotBe(expected);
}
public static IComparable ShouldBeGreaterThan(this IComparable arg1, IComparable arg2)
{
(arg1.CompareTo(arg2) > 0).ShouldBeTrue();
return arg2;
}
public static string ShouldNotBeEmpty(this string aString)
{
aString.IsNotEmpty().ShouldBeTrue();
return aString;
}
public static void ShouldContain(this string actual, string expected, StringComparisonOption options = StringComparisonOption.Default)
{
if (options == StringComparisonOption.NormalizeWhitespaces)
{
actual = Regex.Replace(actual, @"\s+", " ");
expected = Regex.Replace(expected, @"\s+", " ");
}
actual.Contains(expected).ShouldBeTrue($"Actual: {actual}{Environment.NewLine}Expected: {expected}");
}
public static string ShouldNotContain(this string actual, string expected, StringComparisonOption options = StringComparisonOption.NormalizeWhitespaces)
{
if (options == StringComparisonOption.NormalizeWhitespaces)
{
actual = Regex.Replace(actual, @"\s+", " ");
expected = Regex.Replace(expected, @"\s+", " ");
}
actual.Contains(expected).ShouldBeFalse($"Actual: {actual}{Environment.NewLine}Expected: {expected}");
return actual;
}
public static void ShouldStartWith(this string actual, string expected)
{
actual.StartsWith(expected).ShouldBeTrue();
}
public static Exception ShouldBeThrownBy(this Type exceptionType, MethodThatThrows method)
{
Exception exception = null;
try
{
method();
}
catch (Exception e)
{
e.GetType().ShouldBe(exceptionType);
exception = e;
}
exception.ShouldNotBeNull("Expected {0} to be thrown.".ToFormat(exceptionType.FullName));
return exception;
}
public static void ShouldBeEqualWithDbPrecision(this DateTime actual, DateTime expected)
{
static DateTime toDbPrecision(DateTime date) => new DateTime(date.Ticks / 1000 * 1000);
toDbPrecision(actual).ShouldBe(toDbPrecision(expected));
}
public static void ShouldBeEqualWithDbPrecision(this DateTimeOffset actual, DateTimeOffset expected)
{
static DateTimeOffset toDbPrecision(DateTimeOffset date) => new DateTimeOffset(date.Ticks / 1000 * 1000, new TimeSpan(date.Offset.Ticks / 1000 * 1000));
toDbPrecision(actual).ShouldBe(toDbPrecision(expected));
}
public static void ShouldContain(this DbObjectName[] names, string qualifiedName)
{
if (names == null)
throw new ArgumentNullException(nameof(names));
var function = DbObjectName.Parse(qualifiedName);
names.ShouldContain(function);
}
}
public enum StringComparisonOption
{
Default,
NormalizeWhitespaces
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) Under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for Additional information regarding copyright ownership.
* The ASF licenses this file to You Under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed Under the License is distributed on an "AS Is" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations Under the License.
*/
namespace NPOI.HSSF.UserModel
{
using System;
using System.Collections;
using NPOI.SS.Formula;
using NPOI.SS.Formula.Eval;
using NPOI.SS.Formula.PTG;
using NPOI.SS.Formula.UDF;
using NPOI.SS.UserModel;
using System.Collections.Generic;
/**
* @author Amol S. Deshmukh < amolweb at ya hoo dot com >
*
*/
public class HSSFFormulaEvaluator : BaseFormulaEvaluator
{
// params to lookup the right constructor using reflection
private static readonly Type[] VALUE_CONTRUCTOR_CLASS_ARRAY = new Type[] { typeof(Ptg) };
private static readonly Type[] AREA3D_CONSTRUCTOR_CLASS_ARRAY = new Type[] { typeof(Ptg), typeof(ValueEval[]) };
private static readonly Type[] REFERENCE_CONSTRUCTOR_CLASS_ARRAY = new Type[] { typeof(Ptg), typeof(ValueEval) };
private static readonly Type[] REF3D_CONSTRUCTOR_CLASS_ARRAY = new Type[] { typeof(Ptg), typeof(ValueEval) };
// Maps for mapping *Eval to *Ptg
private static readonly Hashtable VALUE_EVALS_MAP = new Hashtable();
/*
* Following is the mapping between the Ptg tokens returned
* by the FormulaParser and the *Eval classes that are used
* by the FormulaEvaluator
*/
static HSSFFormulaEvaluator()
{
VALUE_EVALS_MAP[typeof(BoolPtg)] = typeof(BoolEval);
VALUE_EVALS_MAP[typeof(IntPtg)] = typeof(NumberEval);
VALUE_EVALS_MAP[typeof(NumberPtg)] = typeof(NumberEval);
VALUE_EVALS_MAP[typeof(StringPtg)] = typeof(StringEval);
}
protected IRow row;
protected ISheet sheet;
protected IWorkbook _book;
public HSSFFormulaEvaluator(IWorkbook workbook)
: this(workbook, null)
{
}
/**
* @param stabilityClassifier used to optimise caching performance. Pass <code>null</code>
* for the (conservative) assumption that any cell may have its definition changed after
* evaluation begins.
*/
public HSSFFormulaEvaluator(IWorkbook workbook, IStabilityClassifier stabilityClassifier)
: this(workbook, stabilityClassifier, null)
{
}
/**
* @param udfFinder pass <code>null</code> for default (AnalysisToolPak only)
*/
public HSSFFormulaEvaluator(IWorkbook workbook, IStabilityClassifier stabilityClassifier, UDFFinder udfFinder)
: base(new WorkbookEvaluator(HSSFEvaluationWorkbook.Create(workbook), stabilityClassifier, udfFinder))
{
_book = workbook;
}
/**
* @param stabilityClassifier used to optimise caching performance. Pass <code>null</code>
* for the (conservative) assumption that any cell may have its definition changed after
* evaluation begins.
* @param udfFinder pass <code>null</code> for default (AnalysisToolPak only)
*/
public static HSSFFormulaEvaluator Create(IWorkbook workbook, IStabilityClassifier stabilityClassifier, UDFFinder udfFinder)
{
return new HSSFFormulaEvaluator(workbook, stabilityClassifier, udfFinder);
}
protected override IRichTextString CreateRichTextString(string str)
{
return new HSSFRichTextString(str);
}
/**
* Coordinates several formula evaluators together so that formulas that involve external
* references can be evaluated.
* @param workbookNames the simple file names used to identify the workbooks in formulas
* with external links (for example "MyData.xls" as used in a formula "[MyData.xls]Sheet1!A1")
* @param evaluators all evaluators for the full set of workbooks required by the formulas.
*/
public static void SetupEnvironment(String[] workbookNames, HSSFFormulaEvaluator[] evaluators)
{
BaseFormulaEvaluator.SetupEnvironment(workbookNames, evaluators);
}
public override void SetupReferencedWorkbooks(Dictionary<String, IFormulaEvaluator> evaluators)
{
CollaboratingWorkbooksEnvironment.SetupFormulaEvaluator(evaluators);
}
/**
* Should be called to tell the cell value cache that the specified (value or formula) cell
* has changed.
* Failure to call this method after changing cell values will cause incorrect behaviour
* of the evaluate~ methods of this class
*/
public override void NotifyUpdateCell(ICell cell)
{
_bookEvaluator.NotifyUpdateCell(new HSSFEvaluationCell(cell));
}
/**
* Should be called to tell the cell value cache that the specified cell has just been
* deleted.
* Failure to call this method after changing cell values will cause incorrect behaviour
* of the evaluate~ methods of this class
*/
public override void NotifyDeleteCell(ICell cell)
{
_bookEvaluator.NotifyDeleteCell(new HSSFEvaluationCell(cell));
}
/**
* Should be called to tell the cell value cache that the specified (value or formula) cell
* has changed.
* Failure to call this method after changing cell values will cause incorrect behaviour
* of the evaluate~ methods of this class
*/
public override void NotifySetFormula(ICell cell)
{
_bookEvaluator.NotifyUpdateCell(new HSSFEvaluationCell(cell));
}
/**
* Returns a CellValue wrapper around the supplied ValueEval instance.
* @param cell
*/
protected override CellValue EvaluateFormulaCellValue(ICell cell)
{
ValueEval eval = _bookEvaluator.Evaluate(new HSSFEvaluationCell((HSSFCell)cell));
if (eval is BoolEval)
{
BoolEval be = (BoolEval)eval;
return CellValue.ValueOf(be.BooleanValue);
}
if (eval is NumberEval)
{
NumberEval ne = (NumberEval)eval;
return new CellValue(ne.NumberValue);
}
if (eval is StringEval)
{
StringEval ne = (StringEval)eval;
return new CellValue(ne.StringValue);
}
if (eval is ErrorEval)
{
return CellValue.GetError(((ErrorEval)eval).ErrorCode);
}
throw new InvalidOperationException("Unexpected eval class (" + eval.GetType().Name + ")");
}
/**
* If cell Contains formula, it Evaluates the formula, and
* puts the formula result back into the cell, in place
* of the old formula.
* Else if cell does not contain formula, this method leaves
* the cell UnChanged.
* Note that the same instance of Cell is returned to
* allow chained calls like:
* <pre>
* int EvaluatedCellType = evaluator.EvaluateInCell(cell).CellType;
* </pre>
* Be aware that your cell value will be Changed to hold the
* result of the formula. If you simply want the formula
* value computed for you, use {@link #EvaluateFormulaCell(HSSFCell)}
* @param cell
*/
public override ICell EvaluateInCell(ICell cell)
{
if (cell == null)
{
return null;
}
if (cell.CellType == CellType.Formula)
{
CellValue cv = EvaluateFormulaCellValue(cell);
SetCellValue(cell, cv);
SetCellType(cell, cv); // cell will no longer be a formula cell
}
return cell;
}
/**
* Loops over all cells in all sheets of the supplied
* workbook.
* For cells that contain formulas, their formulas are
* Evaluated, and the results are saved. These cells
* remain as formula cells.
* For cells that do not contain formulas, no Changes
* are made.
* This is a helpful wrapper around looping over all
* cells, and calling EvaluateFormulaCell on each one.
*/
public static void EvaluateAllFormulaCells(HSSFWorkbook wb)
{
EvaluateAllFormulaCells(wb, new HSSFFormulaEvaluator(wb));
}
/**
* Loops over all cells in all sheets of the supplied
* workbook.
* For cells that contain formulas, their formulas are
* evaluated, and the results are saved. These cells
* remain as formula cells.
* For cells that do not contain formulas, no changes
* are made.
* This is a helpful wrapper around looping over all
* cells, and calling evaluateFormulaCell on each one.
*/
public new static void EvaluateAllFormulaCells(IWorkbook wb)
{
BaseFormulaEvaluator.EvaluateAllFormulaCells(wb);
}
public override void EvaluateAll()
{
HSSFFormulaEvaluator.EvaluateAllFormulaCells(_book, this);
}
}
}
| |
// 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.Linq;
using SampleMetadata;
using Xunit;
namespace System.Reflection.Tests
{
public static partial class MethodTests
{
[Fact]
public unsafe static void TestMethods1()
{
TestMethods1Worker(typeof(ClassWithMethods1<>).Project());
TestMethods1Worker(typeof(ClassWithMethods1<int>).Project());
TestMethods1Worker(typeof(ClassWithMethods1<string>).Project());
}
private static void TestMethods1Worker(Type t)
{
const BindingFlags bf = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static | BindingFlags.DeclaredOnly;
MethodInfo m = t.GetMethod("Method1", bf);
Assert.Equal("Method1", m.Name);
Assert.Equal(t, m.DeclaringType);
Assert.Equal(t, m.ReflectedType);
Assert.False(m.IsGenericMethodDefinition);
Assert.False(m.IsConstructedGenericMethod());
Assert.False(m.IsGenericMethod);
Assert.Equal(MethodAttributes.Public | MethodAttributes.HideBySig, m.Attributes);
Assert.Equal(MethodImplAttributes.IL, m.MethodImplementationFlags);
Assert.Equal(CallingConventions.Standard | CallingConventions.HasThis, m.CallingConvention);
Type theT = t.GetGenericArguments()[0];
Assert.Equal(typeof(bool).Project(), m.ReturnType);
ParameterInfo rp = m.ReturnParameter;
Assert.Equal(null, rp.Name);
Assert.Equal(typeof(bool).Project(), rp.ParameterType);
Assert.Equal(m, rp.Member);
Assert.Equal(-1, rp.Position);
ParameterInfo[] ps = m.GetParameters();
Assert.Equal(2, ps.Length);
{
ParameterInfo p = ps[0];
Assert.Equal("x", p.Name);
Assert.Equal(typeof(int).Project(), p.ParameterType);
Assert.Equal(m, p.Member);
Assert.Equal(0, p.Position);
}
{
ParameterInfo p = ps[1];
Assert.Equal("t", p.Name);
Assert.Equal(theT, p.ParameterType);
Assert.Equal(m, p.Member);
Assert.Equal(1, p.Position);
}
TestUtils.AssertNewObjectReturnedEachTime(() => m.GetParameters());
m.TestMethodInfoInvariants();
}
[Fact]
public unsafe static void TestAllCoreTypes()
{
const BindingFlags bf = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static | BindingFlags.DeclaredOnly;
MethodInfo m = typeof(ClassWithMethods1<>).Project().GetMethod("TestPrimitives1", bf);
Assert.Equal(typeof(void).Project(), m.ReturnParameter.ParameterType);
ParameterInfo[] ps = m.GetParameters();
{
ParameterInfo p = ps.Single((p1) => p1.Name == "bo");
Assert.Equal(typeof(bool).Project(), p.ParameterType);
}
{
ParameterInfo p = ps.Single((p1) => p1.Name == "c");
Assert.Equal(typeof(char).Project(), p.ParameterType);
}
{
ParameterInfo p = ps.Single((p1) => p1.Name == "b");
Assert.Equal(typeof(byte).Project(), p.ParameterType);
}
{
ParameterInfo p = ps.Single((p1) => p1.Name == "s");
Assert.Equal(typeof(short).Project(), p.ParameterType);
}
{
ParameterInfo p = ps.Single((p1) => p1.Name == "i");
Assert.Equal(typeof(int).Project(), p.ParameterType);
}
{
ParameterInfo p = ps.Single((p1) => p1.Name == "l");
Assert.Equal(typeof(long).Project(), p.ParameterType);
}
{
ParameterInfo p = ps.Single((p1) => p1.Name == "ip");
Assert.Equal(typeof(IntPtr).Project(), p.ParameterType);
}
{
ParameterInfo p = ps.Single((p1) => p1.Name == "sb");
Assert.Equal(typeof(sbyte).Project(), p.ParameterType);
}
{
ParameterInfo p = ps.Single((p1) => p1.Name == "us");
Assert.Equal(typeof(ushort).Project(), p.ParameterType);
}
{
ParameterInfo p = ps.Single((p1) => p1.Name == "ui");
Assert.Equal(typeof(uint).Project(), p.ParameterType);
}
{
ParameterInfo p = ps.Single((p1) => p1.Name == "ul");
Assert.Equal(typeof(ulong).Project(), p.ParameterType);
}
{
ParameterInfo p = ps.Single((p1) => p1.Name == "uip");
Assert.Equal(typeof(UIntPtr).Project(), p.ParameterType);
}
{
ParameterInfo p = ps.Single((p1) => p1.Name == "fl");
Assert.Equal(typeof(float).Project(), p.ParameterType);
}
{
ParameterInfo p = ps.Single((p1) => p1.Name == "db");
Assert.Equal(typeof(double).Project(), p.ParameterType);
}
{
ParameterInfo p = ps.Single((p1) => p1.Name == "o");
Assert.Equal(typeof(object).Project(), p.ParameterType);
}
{
ParameterInfo p = ps.Single((p1) => p1.Name == "str");
Assert.Equal(typeof(string).Project(), p.ParameterType);
}
{
ParameterInfo p = ps.Single((p1) => p1.Name == "tr");
Assert.Equal(typeof(TypedReference).Project(), p.ParameterType);
}
}
[Fact]
public static void TestGenericMethods1()
{
TestGenericMethods1Worker(typeof(GenericClassWithGenericMethods1<,>).Project());
TestGenericMethods1Worker(typeof(GenericClassWithGenericMethods1<int, string>).Project());
}
private static void TestGenericMethods1Worker(Type t)
{
const BindingFlags bf = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static | BindingFlags.DeclaredOnly;
MethodInfo m = t.GetMethod("GenericMethod1", bf);
Assert.Equal(m, m.GetGenericMethodDefinition());
Assert.Equal("GenericMethod1", m.Name);
Assert.Equal(t, m.DeclaringType);
Assert.Equal(t, m.ReflectedType);
Assert.True(m.IsGenericMethodDefinition);
Assert.False(m.IsConstructedGenericMethod());
Assert.True(m.IsGenericMethod);
Type[] methodGenericParameters = m.GetGenericArguments();
Assert.Equal(2, methodGenericParameters.Length);
Type theT = t.GetGenericArguments()[0];
Type theU = t.GetGenericArguments()[1];
Type theM = m.GetGenericArguments()[0];
Type theN = m.GetGenericArguments()[1];
theM.TestGenericMethodParameterInvariants();
theN.TestGenericMethodParameterInvariants();
ParameterInfo[] ps = m.GetParameters();
Assert.Equal(1, ps.Length);
ParameterInfo p = ps[0];
Type actual = p.ParameterType;
//GenericClass5<N, M[], IEnumerable<U>, T[,], int>
Type expected = typeof(GenericClass5<,,,,>).Project().MakeGenericType(
theN,
theM.MakeArrayType(),
typeof(IEnumerable<>).Project().MakeGenericType(theU),
theT.MakeArrayType(2),
typeof(int).Project());
Assert.Equal(expected, actual);
m.TestGenericMethodInfoInvariants();
}
[Fact]
public static void TestConstructedGenericMethods1()
{
TestConstructedGenericMethods1Worker(typeof(GenericClassWithGenericMethods1<,>).Project());
TestConstructedGenericMethods1Worker(typeof(GenericClassWithGenericMethods1<int, string>).Project());
}
private static void TestConstructedGenericMethods1Worker(Type t)
{
const BindingFlags bf = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static | BindingFlags.DeclaredOnly;
MethodInfo gm = t.GetMethod("GenericMethod1", bf);
MethodInfo m = gm.MakeGenericMethod(typeof(object).Project(), typeof(string).Project());
Assert.Equal(gm, m.GetGenericMethodDefinition());
Assert.Equal("GenericMethod1", m.Name);
Assert.Equal(t, m.DeclaringType);
Assert.Equal(t, m.ReflectedType);
Assert.False(m.IsGenericMethodDefinition);
Assert.True(m.IsConstructedGenericMethod());
Assert.True(m.IsGenericMethod);
Type[] methodGenericParameters = m.GetGenericArguments();
Assert.Equal(2, methodGenericParameters.Length);
Type theT = t.GetGenericArguments()[0];
Type theU = t.GetGenericArguments()[1];
Type theM = m.GetGenericArguments()[0];
Type theN = m.GetGenericArguments()[1];
Assert.Equal(typeof(object).Project(), theM);
Assert.Equal(typeof(string).Project(), theN);
ParameterInfo[] ps = m.GetParameters();
Assert.Equal(1, ps.Length);
ParameterInfo p = ps[0];
Type actual = p.ParameterType;
//GenericClass5<N, M[], IEnumerable<U>, T[,], int>
Type expected = typeof(GenericClass5<,,,,>).Project().MakeGenericType(
theN,
theM.MakeArrayType(),
typeof(IEnumerable<>).Project().MakeGenericType(theU),
theT.MakeArrayType(2),
typeof(int).Project());
Assert.Equal(expected, actual);
m.TestConstructedGenericMethodInfoInvariants();
}
[Fact]
public unsafe static void TestCustomModifiers1()
{
using (MetadataLoadContext lc = new MetadataLoadContext(new CoreMetadataAssemblyResolver(), "mscorlib"))
{
Assembly a = lc.LoadFromByteArray(TestData.s_CustomModifiersImage);
Type t = a.GetType("N", throwOnError: true);
Type reqA = a.GetType("ReqA", throwOnError: true);
Type reqB = a.GetType("ReqB", throwOnError: true);
Type reqC = a.GetType("ReqC", throwOnError: true);
Type optA = a.GetType("OptA", throwOnError: true);
Type optB = a.GetType("OptB", throwOnError: true);
Type optC = a.GetType("OptC", throwOnError: true);
MethodInfo m = t.GetMethod("MyMethod");
ParameterInfo p = m.GetParameters()[0];
Type[] req = p.GetRequiredCustomModifiers();
Type[] opt = p.GetOptionalCustomModifiers();
Assert.Equal<Type>(new Type[] { reqA, reqB, reqC }, req);
Assert.Equal<Type>(new Type[] { optA, optB, optC }, opt);
TestUtils.AssertNewObjectReturnedEachTime(() => p.GetRequiredCustomModifiers());
TestUtils.AssertNewObjectReturnedEachTime(() => p.GetOptionalCustomModifiers());
}
}
[Fact]
public static void TestMethodBody1()
{
using (MetadataLoadContext lc = new MetadataLoadContext(new CoreMetadataAssemblyResolver(), "mscorlib"))
{
Assembly coreAssembly = lc.LoadFromStream(TestUtils.CreateStreamForCoreAssembly());
Assembly a = lc.LoadFromByteArray(TestData.s_AssemblyWithMethodBodyImage);
Type nonsense = a.GetType("Nonsense`1", throwOnError: true);
Type theT = nonsense.GetTypeInfo().GenericTypeParameters[0];
MethodInfo m = nonsense.GetMethod("Foo");
Type theM = m.GetGenericArguments()[0];
MethodBody mb = m.GetMethodBody();
byte[] il = mb.GetILAsByteArray();
Assert.Equal<byte>(TestData.s_AssemblyWithMethodBodyILBytes, il);
Assert.Equal(4, mb.MaxStackSize);
Assert.True(mb.InitLocals);
Assert.Equal(0x11000001, mb.LocalSignatureMetadataToken);
IList<LocalVariableInfo> lvis = mb.LocalVariables;
Assert.Equal(10, lvis.Count);
Assert.Equal(0, lvis[0].LocalIndex);
Assert.False(lvis[0].IsPinned);
Assert.Equal(coreAssembly.GetType("System.Single", throwOnError: true), lvis[0].LocalType);
Assert.Equal(1, lvis[1].LocalIndex);
Assert.False(lvis[1].IsPinned);
Assert.Equal(coreAssembly.GetType("System.Double", throwOnError: true), lvis[1].LocalType);
Assert.Equal(2, lvis[2].LocalIndex);
Assert.False(lvis[2].IsPinned);
Assert.Equal(theT, lvis[2].LocalType);
Assert.Equal(3, lvis[3].LocalIndex);
Assert.False(lvis[3].IsPinned);
Assert.Equal(theT.MakeArrayType(), lvis[3].LocalType);
Assert.Equal(4, lvis[4].LocalIndex);
Assert.False(lvis[4].IsPinned);
Assert.Equal(coreAssembly.GetType("System.Collections.Generic.IList`1", throwOnError: true).MakeGenericType(theM), lvis[4].LocalType);
Assert.Equal(5, lvis[5].LocalIndex);
Assert.False(lvis[5].IsPinned);
Assert.Equal(coreAssembly.GetType("System.String", throwOnError: true), lvis[5].LocalType);
Assert.Equal(6, lvis[6].LocalIndex);
Assert.False(lvis[6].IsPinned);
Assert.Equal(coreAssembly.GetType("System.Int32", throwOnError: true).MakeArrayType(), lvis[6].LocalType);
Assert.Equal(7, lvis[7].LocalIndex);
Assert.True(lvis[7].IsPinned);
Assert.Equal(coreAssembly.GetType("System.Int32", throwOnError: true).MakeByRefType(), lvis[7].LocalType);
Assert.Equal(8, lvis[8].LocalIndex);
Assert.False(lvis[8].IsPinned);
Assert.Equal(coreAssembly.GetType("System.Int32", throwOnError: true).MakeArrayType(), lvis[8].LocalType);
Assert.Equal(9, lvis[9].LocalIndex);
Assert.False(lvis[9].IsPinned);
Assert.Equal(coreAssembly.GetType("System.Boolean", throwOnError: true), lvis[9].LocalType);
IList<ExceptionHandlingClause> ehcs = mb.ExceptionHandlingClauses;
Assert.Equal(2, ehcs.Count);
ExceptionHandlingClause ehc = ehcs[0];
Assert.Equal(ExceptionHandlingClauseOptions.Finally, ehc.Flags);
Assert.Equal(97, ehc.TryOffset);
Assert.Equal(41, ehc.TryLength);
Assert.Equal(138, ehc.HandlerOffset);
Assert.Equal(5, ehc.HandlerLength);
ehc = ehcs[1];
Assert.Equal(ExceptionHandlingClauseOptions.Filter, ehc.Flags);
Assert.Equal(88, ehc.TryOffset);
Assert.Equal(58, ehc.TryLength);
Assert.Equal(172, ehc.HandlerOffset);
Assert.Equal(16, ehc.HandlerLength);
Assert.Equal(146, ehc.FilterOffset);
}
}
[Fact]
public static void TestEHClauses()
{
using (MetadataLoadContext lc = new MetadataLoadContext(new CoreMetadataAssemblyResolver(), "mscorlib"))
{
Assembly coreAssembly = lc.LoadFromStream(TestUtils.CreateStreamForCoreAssembly());
Assembly a = lc.LoadFromByteArray(TestData.s_AssemblyWithEhClausesImage);
Type gt = a.GetType("G`1", throwOnError: true);
Type et = a.GetType("MyException`2", throwOnError: true);
Type gtP0 = gt.GetGenericTypeParameters()[0];
Type etP0 = et.GetGenericTypeParameters()[0];
Type etP1 = et.GetGenericTypeParameters()[1];
{
MethodInfo m = gt.GetMethod("Catch");
Type theM = m.GetGenericArguments()[0];
MethodBody body = m.GetMethodBody();
IList<ExceptionHandlingClause> ehs = body.ExceptionHandlingClauses;
Assert.Equal(1, ehs.Count);
ExceptionHandlingClause eh = ehs[0];
Assert.Equal(ExceptionHandlingClauseOptions.Clause, eh.Flags);
Assert.Equal(1, eh.TryOffset);
Assert.Equal(15, eh.TryLength);
Assert.Equal(16, eh.HandlerOffset);
Assert.Equal(16, eh.HandlerLength);
Assert.Throws<InvalidOperationException>(() => eh.FilterOffset);
Assert.Equal(et.MakeGenericType(gtP0, theM), eh.CatchType);
}
{
Type sysInt32 = coreAssembly.GetType("System.Int32", throwOnError: true);
Type sysSingle = coreAssembly.GetType("System.Single", throwOnError: true);
MethodInfo m = gt.MakeGenericType(sysInt32).GetMethod("Catch").MakeGenericMethod(sysSingle);
MethodBody body = m.GetMethodBody();
IList<ExceptionHandlingClause> ehs = body.ExceptionHandlingClauses;
Assert.Equal(1, ehs.Count);
ExceptionHandlingClause eh = ehs[0];
Assert.Equal(ExceptionHandlingClauseOptions.Clause, eh.Flags);
Assert.Equal(1, eh.TryOffset);
Assert.Equal(15, eh.TryLength);
Assert.Equal(16, eh.HandlerOffset);
Assert.Equal(16, eh.HandlerLength);
Assert.Throws<InvalidOperationException>(() => eh.FilterOffset);
Assert.Equal(et.MakeGenericType(sysInt32, sysSingle), eh.CatchType);
}
{
MethodInfo m = gt.GetMethod("Finally");
MethodBody body = m.GetMethodBody();
IList<ExceptionHandlingClause> ehs = body.ExceptionHandlingClauses;
Assert.Equal(1, ehs.Count);
ExceptionHandlingClause eh = ehs[0];
Assert.Equal(ExceptionHandlingClauseOptions.Finally, eh.Flags);
Assert.Equal(1, eh.TryOffset);
Assert.Equal(15, eh.TryLength);
Assert.Equal(16, eh.HandlerOffset);
Assert.Equal(14, eh.HandlerLength);
Assert.Throws<InvalidOperationException>(() => eh.FilterOffset);
Assert.Throws<InvalidOperationException>(() => eh.CatchType);
}
{
MethodInfo m = gt.GetMethod("Fault");
MethodBody body = m.GetMethodBody();
IList<ExceptionHandlingClause> ehs = body.ExceptionHandlingClauses;
Assert.Equal(1, ehs.Count);
ExceptionHandlingClause eh = ehs[0];
Assert.Equal(ExceptionHandlingClauseOptions.Fault, eh.Flags);
Assert.Equal(1, eh.TryOffset);
Assert.Equal(15, eh.TryLength);
Assert.Equal(16, eh.HandlerOffset);
Assert.Equal(14, eh.HandlerLength);
Assert.Throws<InvalidOperationException>(() => eh.FilterOffset);
Assert.Throws<InvalidOperationException>(() => eh.CatchType);
}
{
MethodInfo m = gt.GetMethod("Filter");
MethodBody body = m.GetMethodBody();
IList<ExceptionHandlingClause> ehs = body.ExceptionHandlingClauses;
Assert.Equal(1, ehs.Count);
ExceptionHandlingClause eh = ehs[0];
Assert.Equal(ExceptionHandlingClauseOptions.Filter, eh.Flags);
Assert.Equal(1, eh.TryOffset);
Assert.Equal(15, eh.TryLength);
Assert.Equal(40, eh.HandlerOffset);
Assert.Equal(16, eh.HandlerLength);
Assert.Equal(16, eh.FilterOffset);
Assert.Throws<InvalidOperationException>(() => eh.CatchType);
}
}
}
[Fact]
public static void TestCallingConventions()
{
const BindingFlags bf = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static | BindingFlags.DeclaredOnly;
MethodBase[] mbs = (MethodBase[])(typeof(ExerciseCallingConventions).Project().GetMember("*", MemberTypes.Method | MemberTypes.Constructor, bf));
mbs = mbs.OrderBy(m => m.Name).ToArray();
Assert.Equal(5, mbs.Length);
Assert.Equal(".cctor", mbs[0].Name);
Assert.Equal(CallingConventions.Standard, mbs[0].CallingConvention);
Assert.Equal(".ctor", mbs[1].Name);
Assert.Equal(CallingConventions.Standard | CallingConventions.HasThis, mbs[1].CallingConvention);
Assert.Equal("InstanceMethod", mbs[2].Name);
Assert.Equal(CallingConventions.Standard | CallingConventions.HasThis, mbs[2].CallingConvention);
Assert.Equal("StaticMethod", mbs[3].Name);
Assert.Equal(CallingConventions.Standard, mbs[3].CallingConvention);
Assert.Equal("VirtualMethod", mbs[4].Name);
Assert.Equal(CallingConventions.Standard | CallingConventions.HasThis, mbs[4].CallingConvention);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Web.Http;
using System.Web.Http.Controllers;
using System.Web.Http.Description;
using ContosoUniversity.WebApi.Areas.HelpPage.ModelDescriptions;
using ContosoUniversity.WebApi.Areas.HelpPage.Models;
namespace ContosoUniversity.WebApi.Areas.HelpPage
{
public static class HelpPageConfigurationExtensions
{
private const string ApiModelPrefix = "MS_HelpPageApiModel_";
/// <summary>
/// Sets the documentation provider for help page.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="documentationProvider">The documentation provider.</param>
public static void SetDocumentationProvider(this HttpConfiguration config, IDocumentationProvider documentationProvider)
{
config.Services.Replace(typeof(IDocumentationProvider), documentationProvider);
}
/// <summary>
/// Sets the objects that will be used by the formatters to produce sample requests/responses.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sampleObjects">The sample objects.</param>
public static void SetSampleObjects(this HttpConfiguration config, IDictionary<Type, object> sampleObjects)
{
config.GetHelpPageSampleGenerator().SampleObjects = sampleObjects;
}
/// <summary>
/// Sets the sample request directly for the specified media type and action.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample request.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, new[] { "*" }), sample);
}
/// <summary>
/// Sets the sample request directly for the specified media type and action with parameters.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample request.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, parameterNames), sample);
}
/// <summary>
/// Sets the sample request directly for the specified media type of the action.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample response.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, new[] { "*" }), sample);
}
/// <summary>
/// Sets the sample response directly for the specified media type of the action with specific parameters.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample response.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, parameterNames), sample);
}
/// <summary>
/// Sets the sample directly for all actions with the specified media type.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample.</param>
/// <param name="mediaType">The media type.</param>
public static void SetSampleForMediaType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType), sample);
}
/// <summary>
/// Sets the sample directly for all actions with the specified type and media type.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="type">The parameter type or return type of an action.</param>
public static void SetSampleForType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, Type type)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, type), sample);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate request samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, new[] { "*" }), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate request samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, parameterNames), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate response samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, new[] { "*" }), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate response samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, parameterNames), type);
}
/// <summary>
/// Gets the help page sample generator.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <returns>The help page sample generator.</returns>
public static HelpPageSampleGenerator GetHelpPageSampleGenerator(this HttpConfiguration config)
{
return (HelpPageSampleGenerator)config.Properties.GetOrAdd(
typeof(HelpPageSampleGenerator),
k => new HelpPageSampleGenerator());
}
/// <summary>
/// Sets the help page sample generator.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sampleGenerator">The help page sample generator.</param>
public static void SetHelpPageSampleGenerator(this HttpConfiguration config, HelpPageSampleGenerator sampleGenerator)
{
config.Properties.AddOrUpdate(
typeof(HelpPageSampleGenerator),
k => sampleGenerator,
(k, o) => sampleGenerator);
}
/// <summary>
/// Gets the model description generator.
/// </summary>
/// <param name="config">The configuration.</param>
/// <returns>The <see cref="ModelDescriptionGenerator"/></returns>
public static ModelDescriptionGenerator GetModelDescriptionGenerator(this HttpConfiguration config)
{
return (ModelDescriptionGenerator)config.Properties.GetOrAdd(
typeof(ModelDescriptionGenerator),
k => InitializeModelDescriptionGenerator(config));
}
/// <summary>
/// Gets the model that represents an API displayed on the help page. The model is initialized on the first call and cached for subsequent calls.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="apiDescriptionId">The <see cref="ApiDescription"/> ID.</param>
/// <returns>
/// An <see cref="HelpPageApiModel"/>
/// </returns>
public static HelpPageApiModel GetHelpPageApiModel(this HttpConfiguration config, string apiDescriptionId)
{
object model;
string modelId = ApiModelPrefix + apiDescriptionId;
if (!config.Properties.TryGetValue(modelId, out model))
{
Collection<ApiDescription> apiDescriptions = config.Services.GetApiExplorer().ApiDescriptions;
ApiDescription apiDescription = apiDescriptions.FirstOrDefault(api => String.Equals(api.GetFriendlyId(), apiDescriptionId, StringComparison.OrdinalIgnoreCase));
if (apiDescription != null)
{
model = GenerateApiModel(apiDescription, config);
config.Properties.TryAdd(modelId, model);
}
}
return (HelpPageApiModel)model;
}
private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HttpConfiguration config)
{
HelpPageApiModel apiModel = new HelpPageApiModel()
{
ApiDescription = apiDescription,
};
ModelDescriptionGenerator modelGenerator = config.GetModelDescriptionGenerator();
HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator();
GenerateUriParameters(apiModel, modelGenerator);
GenerateRequestModelDescription(apiModel, modelGenerator, sampleGenerator);
GenerateResourceDescription(apiModel, modelGenerator);
GenerateSamples(apiModel, sampleGenerator);
return apiModel;
}
private static void GenerateUriParameters(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator)
{
ApiDescription apiDescription = apiModel.ApiDescription;
foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions)
{
if (apiParameter.Source == ApiParameterSource.FromUri)
{
HttpParameterDescriptor parameterDescriptor = apiParameter.ParameterDescriptor;
Type parameterType = null;
ModelDescription typeDescription = null;
ComplexTypeModelDescription complexTypeDescription = null;
if (parameterDescriptor != null)
{
parameterType = parameterDescriptor.ParameterType;
typeDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
complexTypeDescription = typeDescription as ComplexTypeModelDescription;
}
// Example:
// [TypeConverter(typeof(PointConverter))]
// public class Point
// {
// public Point(int x, int y)
// {
// X = x;
// Y = y;
// }
// public int X { get; set; }
// public int Y { get; set; }
// }
// Class Point is bindable with a TypeConverter, so Point will be added to UriParameters collection.
//
// public class Point
// {
// public int X { get; set; }
// public int Y { get; set; }
// }
// Regular complex class Point will have properties X and Y added to UriParameters collection.
if (complexTypeDescription != null
&& !IsBindableWithTypeConverter(parameterType))
{
foreach (ParameterDescription uriParameter in complexTypeDescription.Properties)
{
apiModel.UriParameters.Add(uriParameter);
}
}
else if (parameterDescriptor != null)
{
ParameterDescription uriParameter =
AddParameterDescription(apiModel, apiParameter, typeDescription);
if (!parameterDescriptor.IsOptional)
{
uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Required" });
}
object defaultValue = parameterDescriptor.DefaultValue;
if (defaultValue != null)
{
uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Default value is " + Convert.ToString(defaultValue, CultureInfo.InvariantCulture) });
}
}
else
{
Debug.Assert(parameterDescriptor == null);
// If parameterDescriptor is null, this is an undeclared route parameter which only occurs
// when source is FromUri. Ignored in request model and among resource parameters but listed
// as a simple string here.
ModelDescription modelDescription = modelGenerator.GetOrCreateModelDescription(typeof(string));
AddParameterDescription(apiModel, apiParameter, modelDescription);
}
}
}
}
private static bool IsBindableWithTypeConverter(Type parameterType)
{
if (parameterType == null)
{
return false;
}
return TypeDescriptor.GetConverter(parameterType).CanConvertFrom(typeof(string));
}
private static ParameterDescription AddParameterDescription(HelpPageApiModel apiModel,
ApiParameterDescription apiParameter, ModelDescription typeDescription)
{
ParameterDescription parameterDescription = new ParameterDescription
{
Name = apiParameter.Name,
Documentation = apiParameter.Documentation,
TypeDescription = typeDescription,
};
apiModel.UriParameters.Add(parameterDescription);
return parameterDescription;
}
private static void GenerateRequestModelDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator, HelpPageSampleGenerator sampleGenerator)
{
ApiDescription apiDescription = apiModel.ApiDescription;
foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions)
{
if (apiParameter.Source == ApiParameterSource.FromBody)
{
Type parameterType = apiParameter.ParameterDescriptor.ParameterType;
apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
apiModel.RequestDocumentation = apiParameter.Documentation;
}
else if (apiParameter.ParameterDescriptor != null &&
apiParameter.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage))
{
Type parameterType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription);
if (parameterType != null)
{
apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
}
}
}
}
private static void GenerateResourceDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator)
{
ResponseDescription response = apiModel.ApiDescription.ResponseDescription;
Type responseType = response.ResponseType ?? response.DeclaredType;
if (responseType != null && responseType != typeof(void))
{
apiModel.ResourceDescription = modelGenerator.GetOrCreateModelDescription(responseType);
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")]
private static void GenerateSamples(HelpPageApiModel apiModel, HelpPageSampleGenerator sampleGenerator)
{
try
{
foreach (var item in sampleGenerator.GetSampleRequests(apiModel.ApiDescription))
{
apiModel.SampleRequests.Add(item.Key, item.Value);
LogInvalidSampleAsError(apiModel, item.Value);
}
foreach (var item in sampleGenerator.GetSampleResponses(apiModel.ApiDescription))
{
apiModel.SampleResponses.Add(item.Key, item.Value);
LogInvalidSampleAsError(apiModel, item.Value);
}
}
catch (Exception e)
{
apiModel.ErrorMessages.Add(String.Format(CultureInfo.CurrentCulture,
"An exception has occurred while generating the sample. Exception message: {0}",
HelpPageSampleGenerator.UnwrapException(e).Message));
}
}
private static bool TryGetResourceParameter(ApiDescription apiDescription, HttpConfiguration config, out ApiParameterDescription parameterDescription, out Type resourceType)
{
parameterDescription = apiDescription.ParameterDescriptions.FirstOrDefault(
p => p.Source == ApiParameterSource.FromBody ||
(p.ParameterDescriptor != null && p.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage)));
if (parameterDescription == null)
{
resourceType = null;
return false;
}
resourceType = parameterDescription.ParameterDescriptor.ParameterType;
if (resourceType == typeof(HttpRequestMessage))
{
HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator();
resourceType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription);
}
if (resourceType == null)
{
parameterDescription = null;
return false;
}
return true;
}
private static ModelDescriptionGenerator InitializeModelDescriptionGenerator(HttpConfiguration config)
{
ModelDescriptionGenerator modelGenerator = new ModelDescriptionGenerator(config);
Collection<ApiDescription> apis = config.Services.GetApiExplorer().ApiDescriptions;
foreach (ApiDescription api in apis)
{
ApiParameterDescription parameterDescription;
Type parameterType;
if (TryGetResourceParameter(api, config, out parameterDescription, out parameterType))
{
modelGenerator.GetOrCreateModelDescription(parameterType);
}
}
return modelGenerator;
}
private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample)
{
InvalidSample invalidSample = sample as InvalidSample;
if (invalidSample != null)
{
apiModel.ErrorMessages.Add(invalidSample.ErrorMessage);
}
}
}
}
| |
/*
* Farseer Physics Engine based on Box2D.XNA port:
* Copyright (c) 2010 Ian Qvist
*
* Box2D.XNA port of Box2D:
* Copyright (c) 2009 Brandon Furtwangler, Nathan Furtwangler
*
* Original source Box2D:
* Copyright (c) 2006-2009 Erin Catto http://www.gphysics.com
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
* 3. This notice may not be removed or altered from any source distribution.
*/
using FarseerPhysics.Common;
using Microsoft.Xna.Framework;
namespace FarseerPhysics.Dynamics.Joints
{
// Point-to-point constraint
// Cdot = v2 - v1
// = v2 + cross(w2, r2) - v1 - cross(w1, r1)
// J = [-I -r1_skew I r2_skew ]
// Identity used:
// w k % (rx i + ry j) = w * (-ry i + rx j)
// Angle constraint
// Cdot = w2 - w1
// J = [0 0 -1 0 0 1]
// K = invI1 + invI2
/// <summary>
/// Friction joint. This is used for top-down friction.
/// It provides 2D translational friction and angular friction.
/// </summary>
public class FrictionJoint : Joint
{
private float _angularImpulse;
private float _angularMass;
private Vector2 _linearImpulse;
private Mat22 _linearMass;
public FrictionJoint(Body bodyA, Body bodyB, Vector2 anchor1, Vector2 anchor2)
: base(bodyA, bodyB)
{
JointType = JointType.Friction;
LocalAnchorA = anchor1;
LocalAnchorB = anchor2;
}
public Vector2 LocalAnchorA { get; private set; }
public Vector2 LocalAnchorB { get; private set; }
public override Vector2 WorldAnchorA
{
get { return BodyA.GetWorldPoint(LocalAnchorA); }
}
public override Vector2 WorldAnchorB
{
get { return BodyB.GetWorldPoint(LocalAnchorB); }
}
/// <summary>
/// The maximum friction force in N.
/// </summary>
public float MaxForce { get; set; }
/// <summary>
/// The maximum friction torque in N-m.
/// </summary>
public float MaxTorque { get; set; }
public override Vector2 GetReactionForce(float inv_dt)
{
return inv_dt * _linearImpulse;
}
public override float GetReactionTorque(float inv_dt)
{
return inv_dt * _angularImpulse;
}
internal override void InitVelocityConstraints(ref TimeStep step)
{
Body bA = BodyA;
Body bB = BodyB;
Transform xfA, xfB;
bA.GetTransform(out xfA);
bB.GetTransform(out xfB);
// Compute the effective mass matrix.
Vector2 rA = MathUtils.Multiply(ref xfA.R, LocalAnchorA - bA.LocalCenter);
Vector2 rB = MathUtils.Multiply(ref xfB.R, LocalAnchorB - bB.LocalCenter);
// J = [-I -r1_skew I r2_skew]
// [ 0 -1 0 1]
// r_skew = [-ry; rx]
// Matlab
// K = [ mA+r1y^2*iA+mB+r2y^2*iB, -r1y*iA*r1x-r2y*iB*r2x, -r1y*iA-r2y*iB]
// [ -r1y*iA*r1x-r2y*iB*r2x, mA+r1x^2*iA+mB+r2x^2*iB, r1x*iA+r2x*iB]
// [ -r1y*iA-r2y*iB, r1x*iA+r2x*iB, iA+iB]
float mA = bA.InvMass, mB = bB.InvMass;
float iA = bA.InvI, iB = bB.InvI;
Mat22 K1 = new Mat22();
K1.Col1.X = mA + mB;
K1.Col2.X = 0.0f;
K1.Col1.Y = 0.0f;
K1.Col2.Y = mA + mB;
Mat22 K2 = new Mat22();
K2.Col1.X = iA * rA.Y * rA.Y;
K2.Col2.X = -iA * rA.X * rA.Y;
K2.Col1.Y = -iA * rA.X * rA.Y;
K2.Col2.Y = iA * rA.X * rA.X;
Mat22 K3 = new Mat22();
K3.Col1.X = iB * rB.Y * rB.Y;
K3.Col2.X = -iB * rB.X * rB.Y;
K3.Col1.Y = -iB * rB.X * rB.Y;
K3.Col2.Y = iB * rB.X * rB.X;
Mat22 K12;
Mat22.Add(ref K1, ref K2, out K12);
Mat22 K;
Mat22.Add(ref K12, ref K3, out K);
_linearMass = K.Inverse;
_angularMass = iA + iB;
if (_angularMass > 0.0f)
{
_angularMass = 1.0f / _angularMass;
}
if (Settings.EnableWarmstarting)
{
// Scale impulses to support a variable time step.
_linearImpulse *= step.dtRatio;
_angularImpulse *= step.dtRatio;
Vector2 P = new Vector2(_linearImpulse.X, _linearImpulse.Y);
bA.LinearVelocityInternal -= mA * P;
bA.AngularVelocityInternal -= iA * (MathUtils.Cross(rA, P) + _angularImpulse);
bB.LinearVelocityInternal += mB * P;
bB.AngularVelocityInternal += iB * (MathUtils.Cross(rB, P) + _angularImpulse);
}
else
{
_linearImpulse = Vector2.Zero;
_angularImpulse = 0.0f;
}
}
internal override void SolveVelocityConstraints(ref TimeStep step)
{
Body bA = BodyA;
Body bB = BodyB;
Vector2 vA = bA.LinearVelocityInternal;
float wA = bA.AngularVelocityInternal;
Vector2 vB = bB.LinearVelocityInternal;
float wB = bB.AngularVelocityInternal;
float mA = bA.InvMass, mB = bB.InvMass;
float iA = bA.InvI, iB = bB.InvI;
Transform xfA, xfB;
bA.GetTransform(out xfA);
bB.GetTransform(out xfB);
Vector2 rA = MathUtils.Multiply(ref xfA.R, LocalAnchorA - bA.LocalCenter);
Vector2 rB = MathUtils.Multiply(ref xfB.R, LocalAnchorB - bB.LocalCenter);
// Solve angular friction
{
float Cdot = wB - wA;
float impulse = -_angularMass * Cdot;
float oldImpulse = _angularImpulse;
float maxImpulse = step.dt * MaxTorque;
_angularImpulse = MathUtils.Clamp(_angularImpulse + impulse, -maxImpulse, maxImpulse);
impulse = _angularImpulse - oldImpulse;
wA -= iA * impulse;
wB += iB * impulse;
}
// Solve linear friction
{
Vector2 Cdot = vB + MathUtils.Cross(wB, rB) - vA - MathUtils.Cross(wA, rA);
Vector2 impulse = -MathUtils.Multiply(ref _linearMass, Cdot);
Vector2 oldImpulse = _linearImpulse;
_linearImpulse += impulse;
float maxImpulse = step.dt * MaxForce;
if (_linearImpulse.LengthSquared() > maxImpulse * maxImpulse)
{
_linearImpulse.Normalize();
_linearImpulse *= maxImpulse;
}
impulse = _linearImpulse - oldImpulse;
vA -= mA * impulse;
wA -= iA * MathUtils.Cross(rA, impulse);
vB += mB * impulse;
wB += iB * MathUtils.Cross(rB, impulse);
}
bA.LinearVelocityInternal = vA;
bA.AngularVelocityInternal = wA;
bB.LinearVelocityInternal = vB;
bB.AngularVelocityInternal = wB;
}
internal override bool SolvePositionConstraints()
{
return true;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
#nullable disable warnings
using System;
using System.Buffers;
using System.Diagnostics;
using System.Runtime.CompilerServices;
#if IGNITOR
namespace Ignitor
#elif BLAZOR_WEBVIEW
namespace Microsoft.AspNetCore.Components.WebView
#elif COMPONENTS_SERVER
namespace Microsoft.AspNetCore.Components.Server.Circuits
#elif JS_INTEROP
namespace Microsoft.JSInterop.Infrastructure
#else
namespace Microsoft.AspNetCore.Components.RenderTree
#endif
{
/// <summary>
/// Implements a list that uses an array of objects to store the elements.
///
/// This differs from a <see cref="System.Collections.Generic.List{T}"/> in that
/// it not only grows as required but also shrinks if cleared with significant
/// excess capacity. This makes it useful for component rendering, because
/// components can be long-lived and re-render frequently, with the rendered size
/// varying dramatically depending on the user's navigation in the app.
/// </summary>
internal class ArrayBuilder<T> : IDisposable
{
// The following fields are memory mapped to the WASM client. Do not re-order or use auto-properties.
protected T[] _items;
protected int _itemsInUse;
private static readonly T[] Empty = Array.Empty<T>();
private readonly ArrayPool<T> _arrayPool;
private readonly int _minCapacity;
private bool _disposed;
/// <summary>
/// Constructs a new instance of <see cref="ArrayBuilder{T}"/>.
/// </summary>
public ArrayBuilder(int minCapacity = 32, ArrayPool<T> arrayPool = null)
{
_arrayPool = arrayPool ?? ArrayPool<T>.Shared;
_minCapacity = minCapacity;
_items = Empty;
}
/// <summary>
/// Gets the number of items.
/// </summary>
public int Count => _itemsInUse;
/// <summary>
/// Gets the underlying buffer.
/// </summary>
public T[] Buffer => _items;
/// <summary>
/// Appends a new item, automatically resizing the underlying array if necessary.
/// </summary>
/// <param name="item">The item to append.</param>
/// <returns>The index of the appended item.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)] // Just like System.Collections.Generic.List<T>
public int Append(in T item)
{
if (_itemsInUse == _items.Length)
{
GrowBuffer(_items.Length * 2);
}
var indexOfAppendedItem = _itemsInUse++;
_items[indexOfAppendedItem] = item;
return indexOfAppendedItem;
}
internal int Append(T[] source, int startIndex, int length)
{
// Expand storage if needed. Using same doubling approach as would
// be used if you inserted the items one-by-one.
var requiredCapacity = _itemsInUse + length;
if (_items.Length < requiredCapacity)
{
var candidateCapacity = Math.Max(_items.Length * 2, _minCapacity);
while (candidateCapacity < requiredCapacity)
{
candidateCapacity *= 2;
}
GrowBuffer(candidateCapacity);
}
Array.Copy(source, startIndex, _items, _itemsInUse, length);
var startIndexOfAppendedItems = _itemsInUse;
_itemsInUse += length;
return startIndexOfAppendedItems;
}
/// <summary>
/// Sets the supplied value at the specified index. The index must be within
/// range for the array.
/// </summary>
/// <param name="index">The index.</param>
/// <param name="value">The value.</param>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void Overwrite(int index, in T value)
{
if (index > _itemsInUse)
{
ThrowIndexOutOfBoundsException();
}
_items[index] = value;
}
/// <summary>
/// Removes the last item.
/// </summary>
public void RemoveLast()
{
if (_itemsInUse == 0)
{
ThrowIndexOutOfBoundsException();
}
_itemsInUse--;
_items[_itemsInUse] = default; // Release to GC
}
/// <summary>
/// Inserts the item at the specified index, moving the contents of the subsequent entries along by one.
/// </summary>
/// <param name="index">The index at which the value is to be inserted.</param>
/// <param name="value">The value to insert.</param>
public void InsertExpensive(int index, T value)
{
if (index > _itemsInUse)
{
ThrowIndexOutOfBoundsException();
}
if (_itemsInUse == _items.Length)
{
GrowBuffer(_items.Length * 2);
}
Array.Copy(_items, index, _items, index + 1, _itemsInUse - index);
_itemsInUse++;
_items[index] = value;
}
/// <summary>
/// Marks the array as empty, also shrinking the underlying storage if it was
/// not being used to near its full capacity.
/// </summary>
public void Clear()
{
ReturnBuffer();
_items = Empty;
_itemsInUse = 0;
}
protected void GrowBuffer(int desiredCapacity)
{
// When we dispose, we set the count back to zero and return the array.
//
// If someone tries to do something that would require non-zero storage then
// this is a use-after-free. Throwing here is an easy way to prevent that without
// introducing overhead to every method.
if (_disposed)
{
ThrowObjectDisposedException();
}
var newCapacity = Math.Max(desiredCapacity, _minCapacity);
Debug.Assert(newCapacity > _items.Length);
var newItems = _arrayPool.Rent(newCapacity);
Array.Copy(_items, newItems, _itemsInUse);
// Return the old buffer and start using the new buffer
ReturnBuffer();
_items = newItems;
}
private void ReturnBuffer()
{
if (!ReferenceEquals(_items, Empty))
{
// ArrayPool<>.Return with clearArray: true calls Array.Clear on the entire buffer.
// In the most common case, _itemsInUse would be much smaller than _items.Length so we'll specifically clear that subset.
Array.Clear(_items, 0, _itemsInUse);
_arrayPool.Return(_items);
}
}
public void Dispose()
{
if (!_disposed)
{
_disposed = true;
ReturnBuffer();
_items = Empty;
_itemsInUse = 0;
}
}
private static void ThrowIndexOutOfBoundsException()
{
throw new ArgumentOutOfRangeException("index");
}
private static void ThrowObjectDisposedException()
{
throw new ObjectDisposedException(objectName: null);
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Diagnostics.Contracts;
namespace System.Globalization
{
////////////////////////////////////////////////////////////////////////////
//
// Notes about TaiwanLunisolarCalendar
//
////////////////////////////////////////////////////////////////////////////
/*
** Calendar support range:
** Calendar Minimum Maximum
** ========== ========== ==========
** Gregorian 1912/02/18 2051/02/10
** TaiwanLunisolar 1912/01/01 2050/13/29
*/
[Serializable]
public class TaiwanLunisolarCalendar : EastAsianLunisolarCalendar
{
// Since
// Gregorian Year = Era Year + yearOffset
// When Gregorian Year 1912 is year 1, so that
// 1912 = 1 + yearOffset
// So yearOffset = 1911
//m_EraInfo[0] = new EraInfo(1, new DateTime(1912, 1, 1).Ticks, 1911, 1, GregorianCalendar.MaxYear - 1911);
// Initialize our era info.
internal static EraInfo[] taiwanLunisolarEraInfo = new EraInfo[] {
new EraInfo( 1, 1912, 1, 1, 1911, 1, GregorianCalendar.MaxYear - 1911) // era #, start year/month/day, yearOffset, minEraYear
};
internal GregorianCalendarHelper helper;
internal const int MIN_LUNISOLAR_YEAR = 1912;
internal const int MAX_LUNISOLAR_YEAR = 2050;
internal const int MIN_GREGORIAN_YEAR = 1912;
internal const int MIN_GREGORIAN_MONTH = 2;
internal const int MIN_GREGORIAN_DAY = 18;
internal const int MAX_GREGORIAN_YEAR = 2051;
internal const int MAX_GREGORIAN_MONTH = 2;
internal const int MAX_GREGORIAN_DAY = 10;
internal static DateTime minDate = new DateTime(MIN_GREGORIAN_YEAR, MIN_GREGORIAN_MONTH, MIN_GREGORIAN_DAY);
internal static DateTime maxDate = new DateTime((new DateTime(MAX_GREGORIAN_YEAR, MAX_GREGORIAN_MONTH, MAX_GREGORIAN_DAY, 23, 59, 59, 999)).Ticks + 9999);
public override DateTime MinSupportedDateTime
{
get
{
return (minDate);
}
}
public override DateTime MaxSupportedDateTime
{
get
{
return (maxDate);
}
}
protected override int DaysInYearBeforeMinSupportedYear
{
get
{
// 1911 from ChineseLunisolarCalendar
return 384;
}
}
private static readonly int[,] s_yinfo =
{
/*Y LM Lmon Lday DaysPerMonth D1 D2 D3 D4 D5 D6 D7 D8 D9 D10 D11 D12 D13 #Days
1912 */
{ 0 , 2 , 18 , 42192 },/* 30 29 30 29 29 30 29 29 30 30 29 30 0 354
1913 */{ 0 , 2 , 6 , 53840 },/* 30 30 29 30 29 29 30 29 29 30 29 30 0 354
1914 */{ 5 , 1 , 26 , 54568 },/* 30 30 29 30 29 30 29 30 29 29 30 29 30 384
1915 */{ 0 , 2 , 14 , 46400 },/* 30 29 30 30 29 30 29 30 29 30 29 29 0 354
1916 */{ 0 , 2 , 3 , 54944 },/* 30 30 29 30 29 30 30 29 30 29 30 29 0 355
1917 */{ 2 , 1 , 23 , 38608 },/* 30 29 29 30 29 30 30 29 30 30 29 30 29 384
1918 */{ 0 , 2 , 11 , 38320 },/* 30 29 29 30 29 30 29 30 30 29 30 30 0 355
1919 */{ 7 , 2 , 1 , 18872 },/* 29 30 29 29 30 29 29 30 30 29 30 30 30 384
1920 */{ 0 , 2 , 20 , 18800 },/* 29 30 29 29 30 29 29 30 29 30 30 30 0 354
1921 */{ 0 , 2 , 8 , 42160 },/* 30 29 30 29 29 30 29 29 30 29 30 30 0 354
1922 */{ 5 , 1 , 28 , 45656 },/* 30 29 30 30 29 29 30 29 29 30 29 30 30 384
1923 */{ 0 , 2 , 16 , 27216 },/* 29 30 30 29 30 29 30 29 29 30 29 30 0 354
1924 */{ 0 , 2 , 5 , 27968 },/* 29 30 30 29 30 30 29 30 29 30 29 29 0 354
1925 */{ 4 , 1 , 24 , 44456 },/* 30 29 30 29 30 30 29 30 30 29 30 29 30 385
1926 */{ 0 , 2 , 13 , 11104 },/* 29 29 30 29 30 29 30 30 29 30 30 29 0 354
1927 */{ 0 , 2 , 2 , 38256 },/* 30 29 29 30 29 30 29 30 29 30 30 30 0 355
1928 */{ 2 , 1 , 23 , 18808 },/* 29 30 29 29 30 29 29 30 29 30 30 30 30 384
1929 */{ 0 , 2 , 10 , 18800 },/* 29 30 29 29 30 29 29 30 29 30 30 30 0 354
1930 */{ 6 , 1 , 30 , 25776 },/* 29 30 30 29 29 30 29 29 30 29 30 30 29 383
1931 */{ 0 , 2 , 17 , 54432 },/* 30 30 29 30 29 30 29 29 30 29 30 29 0 354
1932 */{ 0 , 2 , 6 , 59984 },/* 30 30 30 29 30 29 30 29 29 30 29 30 0 355
1933 */{ 5 , 1 , 26 , 27976 },/* 29 30 30 29 30 30 29 30 29 30 29 29 30 384
1934 */{ 0 , 2 , 14 , 23248 },/* 29 30 29 30 30 29 30 29 30 30 29 30 0 355
1935 */{ 0 , 2 , 4 , 11104 },/* 29 29 30 29 30 29 30 30 29 30 30 29 0 354
1936 */{ 3 , 1 , 24 , 37744 },/* 30 29 29 30 29 29 30 30 29 30 30 30 29 384
1937 */{ 0 , 2 , 11 , 37600 },/* 30 29 29 30 29 29 30 29 30 30 30 29 0 354
1938 */{ 7 , 1 , 31 , 51560 },/* 30 30 29 29 30 29 29 30 29 30 30 29 30 384
1939 */{ 0 , 2 , 19 , 51536 },/* 30 30 29 29 30 29 29 30 29 30 29 30 0 354
1940 */{ 0 , 2 , 8 , 54432 },/* 30 30 29 30 29 30 29 29 30 29 30 29 0 354
1941 */{ 6 , 1 , 27 , 55888 },/* 30 30 29 30 30 29 30 29 29 30 29 30 29 384
1942 */{ 0 , 2 , 15 , 46416 },/* 30 29 30 30 29 30 29 30 29 30 29 30 0 355
1943 */{ 0 , 2 , 5 , 22176 },/* 29 30 29 30 29 30 30 29 30 29 30 29 0 354
1944 */{ 4 , 1 , 25 , 43736 },/* 30 29 30 29 30 29 30 29 30 30 29 30 30 385
1945 */{ 0 , 2 , 13 , 9680 },/* 29 29 30 29 29 30 29 30 30 30 29 30 0 354
1946 */{ 0 , 2 , 2 , 37584 },/* 30 29 29 30 29 29 30 29 30 30 29 30 0 354
1947 */{ 2 , 1 , 22 , 51544 },/* 30 30 29 29 30 29 29 30 29 30 29 30 30 384
1948 */{ 0 , 2 , 10 , 43344 },/* 30 29 30 29 30 29 29 30 29 30 29 30 0 354
1949 */{ 7 , 1 , 29 , 46248 },/* 30 29 30 30 29 30 29 29 30 29 30 29 30 384
1950 */{ 0 , 2 , 17 , 27808 },/* 29 30 30 29 30 30 29 29 30 29 30 29 0 354
1951 */{ 0 , 2 , 6 , 46416 },/* 30 29 30 30 29 30 29 30 29 30 29 30 0 355
1952 */{ 5 , 1 , 27 , 21928 },/* 29 30 29 30 29 30 29 30 30 29 30 29 30 384
1953 */{ 0 , 2 , 14 , 19872 },/* 29 30 29 29 30 30 29 30 30 29 30 29 0 354
1954 */{ 0 , 2 , 3 , 42416 },/* 30 29 30 29 29 30 29 30 30 29 30 30 0 355
1955 */{ 3 , 1 , 24 , 21176 },/* 29 30 29 30 29 29 30 29 30 29 30 30 30 384
1956 */{ 0 , 2 , 12 , 21168 },/* 29 30 29 30 29 29 30 29 30 29 30 30 0 354
1957 */{ 8 , 1 , 31 , 43344 },/* 30 29 30 29 30 29 29 30 29 30 29 30 29 383
1958 */{ 0 , 2 , 18 , 59728 },/* 30 30 30 29 30 29 29 30 29 30 29 30 0 355
1959 */{ 0 , 2 , 8 , 27296 },/* 29 30 30 29 30 29 30 29 30 29 30 29 0 354
1960 */{ 6 , 1 , 28 , 44368 },/* 30 29 30 29 30 30 29 30 29 30 29 30 29 384
1961 */{ 0 , 2 , 15 , 43856 },/* 30 29 30 29 30 29 30 30 29 30 29 30 0 355
1962 */{ 0 , 2 , 5 , 19296 },/* 29 30 29 29 30 29 30 30 29 30 30 29 0 354
1963 */{ 4 , 1 , 25 , 42352 },/* 30 29 30 29 29 30 29 30 29 30 30 30 29 384
1964 */{ 0 , 2 , 13 , 42352 },/* 30 29 30 29 29 30 29 30 29 30 30 30 0 355
1965 */{ 0 , 2 , 2 , 21088 },/* 29 30 29 30 29 29 30 29 29 30 30 29 0 353
1966 */{ 3 , 1 , 21 , 59696 },/* 30 30 30 29 30 29 29 30 29 29 30 30 29 384
1967 */{ 0 , 2 , 9 , 55632 },/* 30 30 29 30 30 29 29 30 29 30 29 30 0 355
1968 */{ 7 , 1 , 30 , 23208 },/* 29 30 29 30 30 29 30 29 30 29 30 29 30 384
1969 */{ 0 , 2 , 17 , 22176 },/* 29 30 29 30 29 30 30 29 30 29 30 29 0 354
1970 */{ 0 , 2 , 6 , 38608 },/* 30 29 29 30 29 30 30 29 30 30 29 30 0 355
1971 */{ 5 , 1 , 27 , 19176 },/* 29 30 29 29 30 29 30 29 30 30 30 29 30 384
1972 */{ 0 , 2 , 15 , 19152 },/* 29 30 29 29 30 29 30 29 30 30 29 30 0 354
1973 */{ 0 , 2 , 3 , 42192 },/* 30 29 30 29 29 30 29 29 30 30 29 30 0 354
1974 */{ 4 , 1 , 23 , 53864 },/* 30 30 29 30 29 29 30 29 29 30 30 29 30 384
1975 */{ 0 , 2 , 11 , 53840 },/* 30 30 29 30 29 29 30 29 29 30 29 30 0 354
1976 */{ 8 , 1 , 31 , 54568 },/* 30 30 29 30 29 30 29 30 29 29 30 29 30 384
1977 */{ 0 , 2 , 18 , 46400 },/* 30 29 30 30 29 30 29 30 29 30 29 29 0 354
1978 */{ 0 , 2 , 7 , 46752 },/* 30 29 30 30 29 30 30 29 30 29 30 29 0 355
1979 */{ 6 , 1 , 28 , 38608 },/* 30 29 29 30 29 30 30 29 30 30 29 30 29 384
1980 */{ 0 , 2 , 16 , 38320 },/* 30 29 29 30 29 30 29 30 30 29 30 30 0 355
1981 */{ 0 , 2 , 5 , 18864 },/* 29 30 29 29 30 29 29 30 30 29 30 30 0 354
1982 */{ 4 , 1 , 25 , 42168 },/* 30 29 30 29 29 30 29 29 30 29 30 30 30 384
1983 */{ 0 , 2 , 13 , 42160 },/* 30 29 30 29 29 30 29 29 30 29 30 30 0 354
1984 */{ 10 , 2 , 2 , 45656 },/* 30 29 30 30 29 29 30 29 29 30 29 30 30 384
1985 */{ 0 , 2 , 20 , 27216 },/* 29 30 30 29 30 29 30 29 29 30 29 30 0 354
1986 */{ 0 , 2 , 9 , 27968 },/* 29 30 30 29 30 30 29 30 29 30 29 29 0 354
1987 */{ 6 , 1 , 29 , 44448 },/* 30 29 30 29 30 30 29 30 30 29 30 29 29 384
1988 */{ 0 , 2 , 17 , 43872 },/* 30 29 30 29 30 29 30 30 29 30 30 29 0 355
1989 */{ 0 , 2 , 6 , 38256 },/* 30 29 29 30 29 30 29 30 29 30 30 30 0 355
1990 */{ 5 , 1 , 27 , 18808 },/* 29 30 29 29 30 29 29 30 29 30 30 30 30 384
1991 */{ 0 , 2 , 15 , 18800 },/* 29 30 29 29 30 29 29 30 29 30 30 30 0 354
1992 */{ 0 , 2 , 4 , 25776 },/* 29 30 30 29 29 30 29 29 30 29 30 30 0 354
1993 */{ 3 , 1 , 23 , 27216 },/* 29 30 30 29 30 29 30 29 29 30 29 30 29 383
1994 */{ 0 , 2 , 10 , 59984 },/* 30 30 30 29 30 29 30 29 29 30 29 30 0 355
1995 */{ 8 , 1 , 31 , 27432 },/* 29 30 30 29 30 29 30 30 29 29 30 29 30 384
1996 */{ 0 , 2 , 19 , 23232 },/* 29 30 29 30 30 29 30 29 30 30 29 29 0 354
1997 */{ 0 , 2 , 7 , 43872 },/* 30 29 30 29 30 29 30 30 29 30 30 29 0 355
1998 */{ 5 , 1 , 28 , 37736 },/* 30 29 29 30 29 29 30 30 29 30 30 29 30 384
1999 */{ 0 , 2 , 16 , 37600 },/* 30 29 29 30 29 29 30 29 30 30 30 29 0 354
2000 */{ 0 , 2 , 5 , 51552 },/* 30 30 29 29 30 29 29 30 29 30 30 29 0 354
2001 */{ 4 , 1 , 24 , 54440 },/* 30 30 29 30 29 30 29 29 30 29 30 29 30 384
2002 */{ 0 , 2 , 12 , 54432 },/* 30 30 29 30 29 30 29 29 30 29 30 29 0 354
2003 */{ 0 , 2 , 1 , 55888 },/* 30 30 29 30 30 29 30 29 29 30 29 30 0 355
2004 */{ 2 , 1 , 22 , 23208 },/* 29 30 29 30 30 29 30 29 30 29 30 29 30 384
2005 */{ 0 , 2 , 9 , 22176 },/* 29 30 29 30 29 30 30 29 30 29 30 29 0 354
2006 */{ 7 , 1 , 29 , 43736 },/* 30 29 30 29 30 29 30 29 30 30 29 30 30 385
2007 */{ 0 , 2 , 18 , 9680 },/* 29 29 30 29 29 30 29 30 30 30 29 30 0 354
2008 */{ 0 , 2 , 7 , 37584 },/* 30 29 29 30 29 29 30 29 30 30 29 30 0 354
2009 */{ 5 , 1 , 26 , 51544 },/* 30 30 29 29 30 29 29 30 29 30 29 30 30 384
2010 */{ 0 , 2 , 14 , 43344 },/* 30 29 30 29 30 29 29 30 29 30 29 30 0 354
2011 */{ 0 , 2 , 3 , 46240 },/* 30 29 30 30 29 30 29 29 30 29 30 29 0 354
2012 */{ 4 , 1 , 23 , 46416 },/* 30 29 30 30 29 30 29 30 29 30 29 30 29 384
2013 */{ 0 , 2 , 10 , 44368 },/* 30 29 30 29 30 30 29 30 29 30 29 30 0 355
2014 */{ 9 , 1 , 31 , 21928 },/* 29 30 29 30 29 30 29 30 30 29 30 29 30 384
2015 */{ 0 , 2 , 19 , 19360 },/* 29 30 29 29 30 29 30 30 30 29 30 29 0 354
2016 */{ 0 , 2 , 8 , 42416 },/* 30 29 30 29 29 30 29 30 30 29 30 30 0 355
2017 */{ 6 , 1 , 28 , 21176 },/* 29 30 29 30 29 29 30 29 30 29 30 30 30 384
2018 */{ 0 , 2 , 16 , 21168 },/* 29 30 29 30 29 29 30 29 30 29 30 30 0 354
2019 */{ 0 , 2 , 5 , 43312 },/* 30 29 30 29 30 29 29 30 29 29 30 30 0 354
2020 */{ 4 , 1 , 25 , 29864 },/* 29 30 30 30 29 30 29 29 30 29 30 29 30 384
2021 */{ 0 , 2 , 12 , 27296 },/* 29 30 30 29 30 29 30 29 30 29 30 29 0 354
2022 */{ 0 , 2 , 1 , 44368 },/* 30 29 30 29 30 30 29 30 29 30 29 30 0 355
2023 */{ 2 , 1 , 22 , 19880 },/* 29 30 29 29 30 30 29 30 30 29 30 29 30 384
2024 */{ 0 , 2 , 10 , 19296 },/* 29 30 29 29 30 29 30 30 29 30 30 29 0 354
2025 */{ 6 , 1 , 29 , 42352 },/* 30 29 30 29 29 30 29 30 29 30 30 30 29 384
2026 */{ 0 , 2 , 17 , 42208 },/* 30 29 30 29 29 30 29 29 30 30 30 29 0 354
2027 */{ 0 , 2 , 6 , 53856 },/* 30 30 29 30 29 29 30 29 29 30 30 29 0 354
2028 */{ 5 , 1 , 26 , 59696 },/* 30 30 30 29 30 29 29 30 29 29 30 30 29 384
2029 */{ 0 , 2 , 13 , 54576 },/* 30 30 29 30 29 30 29 30 29 29 30 30 0 355
2030 */{ 0 , 2 , 3 , 23200 },/* 29 30 29 30 30 29 30 29 30 29 30 29 0 354
2031 */{ 3 , 1 , 23 , 27472 },/* 29 30 30 29 30 29 30 30 29 30 29 30 29 384
2032 */{ 0 , 2 , 11 , 38608 },/* 30 29 29 30 29 30 30 29 30 30 29 30 0 355
2033 */{ 11 , 1 , 31 , 19176 },/* 29 30 29 29 30 29 30 29 30 30 30 29 30 384
2034 */{ 0 , 2 , 19 , 19152 },/* 29 30 29 29 30 29 30 29 30 30 29 30 0 354
2035 */{ 0 , 2 , 8 , 42192 },/* 30 29 30 29 29 30 29 29 30 30 29 30 0 354
2036 */{ 6 , 1 , 28 , 53848 },/* 30 30 29 30 29 29 30 29 29 30 29 30 30 384
2037 */{ 0 , 2 , 15 , 53840 },/* 30 30 29 30 29 29 30 29 29 30 29 30 0 354
2038 */{ 0 , 2 , 4 , 54560 },/* 30 30 29 30 29 30 29 30 29 29 30 29 0 354
2039 */{ 5 , 1 , 24 , 55968 },/* 30 30 29 30 30 29 30 29 30 29 30 29 29 384
2040 */{ 0 , 2 , 12 , 46496 },/* 30 29 30 30 29 30 29 30 30 29 30 29 0 355
2041 */{ 0 , 2 , 1 , 22224 },/* 29 30 29 30 29 30 30 29 30 30 29 30 0 355
2042 */{ 2 , 1 , 22 , 19160 },/* 29 30 29 29 30 29 30 29 30 30 29 30 30 384
2043 */{ 0 , 2 , 10 , 18864 },/* 29 30 29 29 30 29 29 30 30 29 30 30 0 354
2044 */{ 7 , 1 , 30 , 42168 },/* 30 29 30 29 29 30 29 29 30 29 30 30 30 384
2045 */{ 0 , 2 , 17 , 42160 },/* 30 29 30 29 29 30 29 29 30 29 30 30 0 354
2046 */{ 0 , 2 , 6 , 43600 },/* 30 29 30 29 30 29 30 29 29 30 29 30 0 354
2047 */{ 5 , 1 , 26 , 46376 },/* 30 29 30 30 29 30 29 30 29 29 30 29 30 384
2048 */{ 0 , 2 , 14 , 27936 },/* 29 30 30 29 30 30 29 30 29 29 30 29 0 354
2049 */{ 0 , 2 , 2 , 44448 },/* 30 29 30 29 30 30 29 30 30 29 30 29 0 355
2050 */{ 3 , 1 , 23 , 21936 },/* 29 30 29 30 29 30 29 30 30 29 30 30 29 384
*/};
internal override int MinCalendarYear
{
get
{
return (MIN_LUNISOLAR_YEAR);
}
}
internal override int MaxCalendarYear
{
get
{
return (MAX_LUNISOLAR_YEAR);
}
}
internal override DateTime MinDate
{
get
{
return (minDate);
}
}
internal override DateTime MaxDate
{
get
{
return (maxDate);
}
}
internal override EraInfo[] CalEraInfo
{
get
{
return (taiwanLunisolarEraInfo);
}
}
internal override int GetYearInfo(int LunarYear, int Index)
{
if ((LunarYear < MIN_LUNISOLAR_YEAR) || (LunarYear > MAX_LUNISOLAR_YEAR))
{
throw new ArgumentOutOfRangeException(
"year",
String.Format(
CultureInfo.CurrentCulture,
SR.ArgumentOutOfRange_Range,
MIN_LUNISOLAR_YEAR,
MAX_LUNISOLAR_YEAR));
}
Contract.EndContractBlock();
return s_yinfo[LunarYear - MIN_LUNISOLAR_YEAR, Index];
}
internal override int GetYear(int year, DateTime time)
{
return helper.GetYear(year, time);
}
internal override int GetGregorianYear(int year, int era)
{
return helper.GetGregorianYear(year, era);
}
public TaiwanLunisolarCalendar()
{
helper = new GregorianCalendarHelper(this, taiwanLunisolarEraInfo);
}
public override int GetEra(DateTime time)
{
return (helper.GetEra(time));
}
internal override CalendarId BaseCalendarID
{
get
{
return (CalendarId.TAIWAN);
}
}
internal override CalendarId ID
{
get
{
return (CalendarId.TAIWANLUNISOLAR);
}
}
public override int[] Eras
{
get
{
return (helper.Eras);
}
}
}
}
| |
// 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 Xunit;
namespace System.IO.Tests
{
public class File_Create_str : FileSystemTest
{
#region Utilities
public virtual FileStream Create(string path)
{
return File.Create(path);
}
#endregion
#region UniversalTests
[Fact]
public void NullPath()
{
Assert.Throws<ArgumentNullException>(() => Create(null));
}
[Fact]
public void EmptyPath()
{
Assert.Throws<ArgumentException>(() => Create(string.Empty));
}
[Fact]
public void NonExistentPath()
{
Assert.Throws<DirectoryNotFoundException>(() => Create(Path.Combine(TestDirectory, GetTestFileName(), GetTestFileName())));
}
[Fact]
public void CreateCurrentDirectory()
{
Assert.Throws<UnauthorizedAccessException>(() => Create("."));
}
[Fact]
public void ValidCreation()
{
DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath());
string testFile = Path.Combine(testDir.FullName, GetTestFileName());
using (FileStream stream = Create(testFile))
{
Assert.True(File.Exists(testFile));
Assert.Equal(0, stream.Length);
Assert.Equal(0, stream.Position);
}
}
[ConditionalFact(nameof(UsingNewNormalization))]
[PlatformSpecific(TestPlatforms.Windows)] // Valid Windows path extended prefix
public void ValidCreation_ExtendedSyntax()
{
DirectoryInfo testDir = Directory.CreateDirectory(IOInputs.ExtendedPrefix + GetTestFilePath());
Assert.StartsWith(IOInputs.ExtendedPrefix, testDir.FullName);
string testFile = Path.Combine(testDir.FullName, GetTestFileName());
using (FileStream stream = Create(testFile))
{
Assert.True(File.Exists(testFile));
Assert.Equal(0, stream.Length);
Assert.Equal(0, stream.Position);
}
}
[ConditionalFact(nameof(AreAllLongPathsAvailable))]
[PlatformSpecific(TestPlatforms.Windows)] // Valid Windows path extended prefix, long path
public void ValidCreation_LongPathExtendedSyntax()
{
DirectoryInfo testDir = Directory.CreateDirectory(IOServices.GetPath(IOInputs.ExtendedPrefix + TestDirectory, characterCount: 500));
Assert.StartsWith(IOInputs.ExtendedPrefix, testDir.FullName);
string testFile = Path.Combine(testDir.FullName, GetTestFileName());
using (FileStream stream = Create(testFile))
{
Assert.True(File.Exists(testFile));
Assert.Equal(0, stream.Length);
Assert.Equal(0, stream.Position);
}
}
[Fact]
public void CreateInParentDirectory()
{
string testFile = GetTestFileName();
using (FileStream stream = Create(Path.Combine(TestDirectory, "DoesntExists", "..", testFile)))
{
Assert.True(File.Exists(Path.Combine(TestDirectory, testFile)));
}
}
[Fact]
public void LegalSymbols()
{
DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath());
string testFile = Path.Combine(testDir.FullName, GetTestFileName() + "!@#$%^&");
using (FileStream stream = Create(testFile))
{
Assert.True(File.Exists(testFile));
}
}
[Fact]
public void InvalidDirectory()
{
DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath());
string testFile = Path.Combine(testDir.FullName, GetTestFileName(), GetTestFileName());
Assert.Throws<DirectoryNotFoundException>(() => Create(testFile));
}
[Fact]
public void FileInUse()
{
DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath());
string testFile = Path.Combine(testDir.FullName, GetTestFileName());
using (FileStream stream = Create(testFile))
{
Assert.True(File.Exists(testFile));
Assert.Throws<IOException>(() => Create(testFile));
}
}
[Fact]
public void FileAlreadyExists()
{
DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath());
string testFile = Path.Combine(testDir.FullName, GetTestFileName());
Create(testFile).Dispose();
Assert.True(File.Exists(testFile));
Create(testFile).Dispose();
Assert.True(File.Exists(testFile));
}
[Fact]
public void OverwriteReadOnly()
{
DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath());
string testFile = Path.Combine(testDir.FullName, GetTestFileName());
Create(testFile).Dispose();
Assert.True(File.Exists(testFile));
Create(testFile).Dispose();
Assert.True(File.Exists(testFile));
}
[Fact]
public void LongPathSegment()
{
DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath());
// Long path should throw PathTooLongException on Desktop and IOException
// elsewhere.
if (PlatformDetection.IsFullFramework)
{
Assert.Throws<PathTooLongException>(
() => Create(Path.Combine(testDir.FullName, new string('a', 300))));
}
else
{
AssertExtensions.ThrowsAny<IOException, DirectoryNotFoundException, PathTooLongException>(
() => Create(Path.Combine(testDir.FullName, new string('a', 300))));
}
}
#endregion
#region PlatformSpecific
[Fact]
[PlatformSpecific(CaseSensitivePlatforms)]
public void CaseSensitive()
{
DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath());
string testFile = Path.Combine(testDir.FullName, GetTestFileName());
using (File.Create(testFile + "AAAA"))
using (File.Create(testFile + "aAAa"))
{
Assert.False(File.Exists(testFile + "AaAa"));
Assert.True(File.Exists(testFile + "AAAA"));
Assert.True(File.Exists(testFile + "aAAa"));
Assert.Equal(2, Directory.GetFiles(testDir.FullName).Length);
}
Assert.Throws<DirectoryNotFoundException>(() => File.Create(testFile.ToLowerInvariant()));
}
[Fact]
[PlatformSpecific(CaseInsensitivePlatforms)]
public void CaseInsensitive()
{
DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath());
string testFile = Path.Combine(testDir.FullName, GetTestFileName());
File.Create(testFile + "AAAA").Dispose();
File.Create(testFile.ToLowerInvariant() + "aAAa").Dispose();
Assert.Equal(1, Directory.GetFiles(testDir.FullName).Length);
}
[Fact]
[PlatformSpecific(TestPlatforms.Windows)]
[SkipOnTargetFramework(~TargetFrameworkMonikers.NetFramework)]
public void WindowsWildCharacterPath_Desktop()
{
DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath());
Assert.Throws<ArgumentException>(() => Create(Path.Combine(testDir.FullName, "dls;d", "442349-0", "v443094(*)(+*$#$*", new string(Path.DirectorySeparatorChar, 3))));
Assert.Throws<ArgumentException>(() => Create(Path.Combine(testDir.FullName, "*")));
Assert.Throws<ArgumentException>(() => Create(Path.Combine(testDir.FullName, "Test*t")));
Assert.Throws<ArgumentException>(() => Create(Path.Combine(testDir.FullName, "*Tes*t")));
}
[ActiveIssue(27269)]
[Fact]
[PlatformSpecific(TestPlatforms.Windows)]
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework)]
public void WindowsWildCharacterPath_Core()
{
DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath());
Assert.ThrowsAny<IOException>(() => Create(Path.Combine(testDir.FullName, "dls;d", "442349-0", "v443094(*)(+*$#$*", new string(Path.DirectorySeparatorChar, 3))));
Assert.ThrowsAny<IOException>(() => Create(Path.Combine(testDir.FullName, "*")));
Assert.ThrowsAny<IOException>(() => Create(Path.Combine(testDir.FullName, "Test*t")));
Assert.ThrowsAny<IOException>(() => Create(Path.Combine(testDir.FullName, "*Tes*t")));
}
[Theory,
InlineData(" "),
InlineData(""),
InlineData("\0"),
InlineData(" ")]
[PlatformSpecific(TestPlatforms.Windows)]
public void WindowsEmptyPath(string path)
{
Assert.Throws<ArgumentException>(() => Create(path));
}
[Theory,
InlineData("\n"),
InlineData(">"),
InlineData("<"),
InlineData("\t")]
[PlatformSpecific(TestPlatforms.Windows)]
[SkipOnTargetFramework(~TargetFrameworkMonikers.NetFramework)]
public void WindowsInvalidPath_Desktop(string path)
{
Assert.Throws<ArgumentException>(() => Create(path));
}
[ActiveIssue(27269)]
[Theory,
InlineData("\n"),
InlineData(">"),
InlineData("<"),
InlineData("\t")]
[PlatformSpecific(TestPlatforms.Windows)]
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework)]
public void WindowsInvalidPath_Core(string path)
{
Assert.ThrowsAny<IOException>(() => Create(Path.Combine(TestDirectory, path)));
}
[Fact]
[PlatformSpecific(TestPlatforms.AnyUnix)]
public void CreateNullThrows_Unix()
{
Assert.Throws<ArgumentException>(() => Create("\0"));
}
[Theory,
InlineData(" "),
InlineData(" "),
InlineData("\n"),
InlineData(">"),
InlineData("<"),
InlineData("\t")]
[PlatformSpecific(TestPlatforms.AnyUnix)] // Valid file name with Whitespace on Unix
public void UnixWhitespacePath(string path)
{
DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath());
using (Create(Path.Combine(testDir.FullName, path)))
{
Assert.True(File.Exists(Path.Combine(testDir.FullName, path)));
}
}
#endregion
}
public class File_Create_str_i : File_Create_str
{
public override FileStream Create(string path)
{
return File.Create(path, 4096); // Default buffer size
}
public virtual FileStream Create(string path, int bufferSize)
{
return File.Create(path, bufferSize);
}
[Fact]
public void NegativeBuffer()
{
Assert.Throws<ArgumentOutOfRangeException>(() => Create(GetTestFilePath(), -1));
Assert.Throws<ArgumentOutOfRangeException>(() => Create(GetTestFilePath(), -100));
}
}
public class File_Create_str_i_fo : File_Create_str_i
{
public override FileStream Create(string path)
{
return File.Create(path, 4096, FileOptions.Asynchronous);
}
public override FileStream Create(string path, int bufferSize)
{
return File.Create(path, bufferSize, FileOptions.Asynchronous);
}
}
}
| |
/* ====================================================================
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for Additional information regarding copyright ownership.
The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==================================================================== */
namespace TestCases.SS.Formula.Functions
{
using NPOI.SS.Formula.Eval;
using NPOI.SS.UserModel;
using System;
using NUnit.Framework;
using TestCases.HSSF;
using NPOI.HSSF.UserModel;
using System.Text;
using NPOI.SS.Util;
using System.IO;
/**
* Tests INDEX() as loaded from a Test data spreadsheet.<p/>
*
* @author Josh Micich
*/
[TestFixture]
public class TestIndexFunctionFromSpreadsheet
{
private static class Result
{
public static int SOME_EVALUATIONS_FAILED = -1;
public static int ALL_EVALUATIONS_SUCCEEDED = +1;
public static int NO_EVALUATIONS_FOUND = 0;
}
/**
* This class defines constants for navigating around the Test data spreadsheet used for these Tests.
*/
private static class SS
{
/** Name of the Test spreadsheet (found in the standard Test data folder) */
public static String FILENAME = "IndexFunctionTestCaseData.xls";
public static int COLUMN_INDEX_EVALUATION = 2; // Column 'C'
public static int COLUMN_INDEX_EXPECTED_RESULT = 3; // Column 'D'
}
// Note - multiple failures are aggregated before ending.
// If one or more functions fail, a single AssertionException is thrown at the end
private int _EvaluationFailureCount;
private int _EvaluationSuccessCount;
private static void ConfirmExpectedResult(String msg, ICell expected, CellValue actual)
{
if (expected == null)
{
throw new AssertionException(msg + " - Bad Setup data expected value is null");
}
if (actual == null)
{
throw new AssertionException(msg + " - actual value was null");
}
if (expected.CellType == CellType.Error)
{
ConfirmErrorResult(msg, expected.ErrorCellValue, actual);
return;
}
if (actual.CellType == CellType.Error)
{
throw unexpectedError(msg, expected, actual.ErrorValue);
}
if (actual.CellType != expected.CellType)
{
throw wrongTypeError(msg, expected, actual);
}
switch (expected.CellType)
{
case CellType.Boolean:
Assert.AreEqual(expected.BooleanCellValue, actual.BooleanValue, msg);
break;
case CellType.Formula: // will never be used, since we will call method After formula Evaluation
throw new AssertionException("Cannot expect formula as result of formula Evaluation: " + msg);
case CellType.Numeric:
Assert.AreEqual(expected.NumericCellValue, actual.NumberValue, 0.0, msg);
break;
case CellType.String:
Assert.AreEqual(expected.RichStringCellValue.String, actual.StringValue, msg);
break;
}
}
private static AssertionException wrongTypeError(String msgPrefix, ICell expectedCell, CellValue actualValue)
{
return new AssertionException(msgPrefix + " Result type mismatch. Evaluated result was "
+ actualValue.FormatAsString()
+ " but the expected result was "
+ formatValue(expectedCell)
);
}
private static AssertionException unexpectedError(String msgPrefix, ICell expected, int actualErrorCode)
{
return new AssertionException(msgPrefix + " Error code ("
+ ErrorEval.GetText(actualErrorCode)
+ ") was Evaluated, but the expected result was "
+ formatValue(expected)
);
}
private static void ConfirmErrorResult(String msgPrefix, int expectedErrorCode, CellValue actual)
{
if (actual.CellType != CellType.Error)
{
throw new AssertionException(msgPrefix + " Expected cell error ("
+ ErrorEval.GetText(expectedErrorCode) + ") but actual value was "
+ actual.FormatAsString());
}
if (expectedErrorCode != actual.ErrorValue)
{
throw new AssertionException(msgPrefix + " Expected cell error code ("
+ ErrorEval.GetText(expectedErrorCode)
+ ") but actual error code was ("
+ ErrorEval.GetText(actual.ErrorValue)
+ ")");
}
}
private static String formatValue(ICell expecedCell)
{
switch (expecedCell.CellType)
{
case CellType.Blank: return "<blank>";
case CellType.Boolean: return expecedCell.BooleanCellValue.ToString();
case CellType.Numeric: return expecedCell.NumericCellValue.ToString();
case CellType.String: return expecedCell.RichStringCellValue.String;
}
throw new Exception("Unexpected cell type of expected value (" + expecedCell.CellType + ")");
}
[SetUp]
public void SetUp()
{
_EvaluationFailureCount = 0;
_EvaluationSuccessCount = 0;
}
[Test]
public void TestFunctionsFromTestSpreadsheet()
{
HSSFWorkbook workbook = HSSFTestDataSamples.OpenSampleWorkbook(SS.FILENAME);
ProcessTestSheet(workbook, workbook.GetSheetName(0));
// confirm results
String successMsg = "There were "
+ _EvaluationSuccessCount + " function(s) without error";
if (_EvaluationFailureCount > 0)
{
String msg = _EvaluationFailureCount + " Evaluation(s) failed. " + successMsg;
throw new AssertionException(msg);
}
#if !HIDE_UNREACHABLE_CODE
if (false)
{ // normally no output for successful Tests
Console.WriteLine(this.GetType().Name + ": " + successMsg);
}
#endif
}
private void ProcessTestSheet(HSSFWorkbook workbook, String sheetName)
{
ISheet sheet = workbook.GetSheetAt(0);
HSSFFormulaEvaluator Evaluator = new HSSFFormulaEvaluator(workbook);
int maxRows = sheet.LastRowNum + 1;
int result = Result.NO_EVALUATIONS_FOUND; // so far
for (int rowIndex = 0; rowIndex < maxRows; rowIndex++)
{
IRow r = sheet.GetRow(rowIndex);
if (r == null)
{
continue;
}
ICell c = r.GetCell(SS.COLUMN_INDEX_EVALUATION);
if (c == null || c.CellType != CellType.Formula)
{
continue;
}
ICell expectedValueCell = r.GetCell(SS.COLUMN_INDEX_EXPECTED_RESULT);
String msgPrefix = formatTestCaseDetails(sheetName, r.RowNum, c);
try
{
CellValue actualValue = Evaluator.Evaluate(c);
ConfirmExpectedResult(msgPrefix, expectedValueCell, actualValue);
_EvaluationSuccessCount++;
if (result != Result.SOME_EVALUATIONS_FAILED)
{
result = Result.ALL_EVALUATIONS_SUCCEEDED;
}
}
catch (SystemException e)
{
_EvaluationFailureCount++;
printshortStackTrace(System.Console.Error, e, msgPrefix);
result = Result.SOME_EVALUATIONS_FAILED;
}
catch (AssertionException e)
{
_EvaluationFailureCount++;
printshortStackTrace(System.Console.Error, e, msgPrefix);
result = Result.SOME_EVALUATIONS_FAILED;
}
}
}
private static String formatTestCaseDetails(String sheetName, int rowIndex, ICell c)
{
StringBuilder sb = new StringBuilder();
CellReference cr = new CellReference(sheetName, rowIndex, c.ColumnIndex, false, false);
sb.Append(cr.FormatAsString());
sb.Append(" [formula: ").Append(c.CellFormula).Append(" ]");
return sb.ToString();
}
/**
* Useful to keep output concise when expecting many failures to be reported by this Test case
*/
private static void printshortStackTrace(TextWriter ps, Exception e, String msgPrefix)
{
ps.WriteLine("Problem with " + msgPrefix);
ps.WriteLine(e.Message);
ps.WriteLine(e.StackTrace);
//StackTraceElement[] stes = e.GetStackTrace();
//int startIx = 0;
//// skip any top frames inside junit.framework.Assert
//while(startIx<stes.Length) {
// if(!stes[startIx].GetClassName().Equals(typeof(Assert).Name)) {
// break;
// }
// startIx++;
//}
//// skip bottom frames (part of junit framework)
//int endIx = startIx+1;
//while(endIx < stes.Length) {
// if(stes[endIx].GetClassName().Equals(TestCase.class.GetName())) {
// break;
// }
// endIx++;
//}
//if(startIx >= endIx) {
// // something went wrong. just print the whole stack trace
// e.printStackTrace(ps);
//}
//endIx -= 4; // skip 4 frames of reflection invocation
//ps.println(e.ToString());
//for(int i=startIx; i<endIx; i++) {
// ps.println("\tat " + stes[i].ToString());
//}
}
}
}
| |
/********************************************************************++
Copyright (c) Microsoft Corporation. All rights reserved.
--********************************************************************/
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics.CodeAnalysis;
using System.Management.Automation.Language;
using System.Management.Automation.Runspaces;
using System.Runtime.ExceptionServices;
using Microsoft.PowerShell.Commands;
namespace System.Management.Automation
{
/// <summary>
/// Defines the types of commands that MSH can execute
/// </summary>
[Flags]
public enum CommandTypes
{
/// <summary>
/// Aliases create a name that refers to other command types
/// </summary>
///
/// <remarks>
/// Aliases are only persisted within the execution of a single engine.
/// </remarks>
Alias = 0x0001,
/// <summary>
/// Script functions that are defined by a script block
/// </summary>
///
/// <remarks>
/// Functions are only persisted within the execution of a single engine.
/// </remarks>
Function = 0x0002,
/// <summary>
/// Script filters that are defined by a script block.
/// </summary>
///
/// <remarks>
/// Filters are only persisted within the execution of a single engine.
/// </remarks>
Filter = 0x0004,
/// <summary>
/// A cmdlet.
/// </summary>
Cmdlet = 0x0008,
/// <summary>
/// An MSH script (*.ps1 file)
/// </summary>
ExternalScript = 0x0010,
/// <summary>
/// Any existing application (can be console or GUI).
/// </summary>
///
/// <remarks>
/// An application can have any extension that can be executed either directly through CreateProcess
/// or indirectly through ShellExecute.
/// </remarks>
Application = 0x0020,
/// <summary>
/// A script that is built into the runspace configuration
/// </summary>
Script = 0x0040,
/// <summary>
/// A workflow
/// </summary>
Workflow = 0x0080,
/// <summary>
/// A Configuration
/// </summary>
Configuration = 0x0100,
/// <summary>
/// All possible command types.
/// </summary>
///
/// <remarks>
/// Note, a CommandInfo instance will never specify
/// All as its CommandType but All can be used when filtering the CommandTypes.
/// </remarks>
All = Alias | Function | Filter | Cmdlet | Script | ExternalScript | Application | Workflow | Configuration,
}
/// <summary>
/// The base class for the information about commands. Contains the basic information about
/// the command, like name and type.
/// </summary>
public abstract class CommandInfo : IHasSessionStateEntryVisibility
{
#region ctor
/// <summary>
/// Creates an instance of the CommandInfo class with the specified name and type
/// </summary>
///
/// <param name="name">
/// The name of the command.
/// </param>
///
/// <param name="type">
/// The type of the command.
/// </param>
///
/// <exception cref="ArgumentNullException">
/// If <paramref name="name"/> is null.
/// </exception>
///
internal CommandInfo(string name, CommandTypes type)
{
// The name can be empty for functions and filters but it
// can't be null
if (name == null)
{
throw new ArgumentNullException("name");
}
Name = name;
CommandType = type;
} // CommandInfo ctor
/// <summary>
/// Creates an instance of the CommandInfo class with the specified name and type
/// </summary>
///
/// <param name="name">
/// The name of the command.
/// </param>
///
/// <param name="type">
/// The type of the command.
/// </param>
///
/// <param name="context">
/// The execution context for the command.
/// </param>
///
/// <exception cref="ArgumentNullException">
/// If <paramref name="name"/> is null.
/// </exception>
///
internal CommandInfo(string name, CommandTypes type, ExecutionContext context)
: this(name, type)
{
this.Context = context;
} // CommandInfo ctor
/// <summary>
/// This is a copy constructor, used primarily for get-command.
/// </summary>
internal CommandInfo(CommandInfo other)
{
// Computed fields not copied:
//this._externalCommandMetadata = other._externalCommandMetadata;
//this._moduleName = other._moduleName;
//this.parameterSets = other.parameterSets;
this.Module = other.Module;
_visibility = other._visibility;
Arguments = other.Arguments;
this.Context = other.Context;
Name = other.Name;
CommandType = other.CommandType;
CopiedCommand = other;
this.DefiningLanguageMode = other.DefiningLanguageMode;
}
/// <summary>
/// This is a copy constructor, used primarily for get-command.
/// </summary>
internal CommandInfo(string name, CommandInfo other)
: this(other)
{
Name = name;
}
#endregion ctor
/// <summary>
/// Gets the name of the command.
/// </summary>
public string Name { get; private set; } = String.Empty;
// Name
/// <summary>
/// Gets the type of the command
/// </summary>
public CommandTypes CommandType { get; private set; } = CommandTypes.Application;
// CommandType
/// <summary>
/// Gets the source of the command (shown by default in Get-Command)
/// </summary>
public virtual string Source { get { return this.ModuleName; } }
/// <summary>
/// Gets the source version (shown by default in Get-Command)
/// </summary>
public virtual Version Version
{
get
{
if (_version == null)
{
if (Module != null)
{
if (Module.Version.Equals(new Version(0, 0)))
{
if (Module.Path.EndsWith(StringLiterals.PowerShellDataFileExtension, StringComparison.OrdinalIgnoreCase))
{
// Manifest module (.psd1)
Module.SetVersion(ModuleIntrinsics.GetManifestModuleVersion(Module.Path));
}
else if (Module.Path.EndsWith(StringLiterals.DependentWorkflowAssemblyExtension, StringComparison.OrdinalIgnoreCase))
{
// Binary module (.dll)
Module.SetVersion(ClrFacade.GetAssemblyName(Module.Path).Version);
}
}
_version = Module.Version;
}
}
return _version;
}
}
private Version _version;
/// <summary>
/// The execution context this command will run in.
/// </summary>
internal ExecutionContext Context
{
get { return _context; }
set
{
_context = value;
if ((value != null) && !this.DefiningLanguageMode.HasValue)
{
this.DefiningLanguageMode = value.LanguageMode;
}
}
}
private ExecutionContext _context;
/// <summary>
/// The language mode that was in effect when this alias was defined.
/// </summary>
internal PSLanguageMode? DefiningLanguageMode { get; set; }
internal virtual HelpCategory HelpCategory
{
get { return HelpCategory.None; }
}
internal CommandInfo CopiedCommand { get; set; }
/// <summary>
/// Internal interface to change the type of a CommandInfo object.
/// </summary>
/// <param name="newType"></param>
internal void SetCommandType(CommandTypes newType)
{
CommandType = newType;
}
internal const int HasWorkflowKeyWord = 0x0008;
internal const int IsCimCommand = 0x0010;
internal const int IsFile = 0x0020;
/// <summary>
/// A string representing the definition of the command.
/// </summary>
///
/// <remarks>
/// This is overridden by derived classes to return specific
/// information for the command type.
/// </remarks>
public abstract string Definition { get; }
/// <summary>
/// This is required for renaming aliases, functions, and filters
/// </summary>
///
/// <param name="newName">
/// The new name for the command.
/// </param>
///
/// <exception cref="ArgumentException">
/// If <paramref name="newName"/> is null or empty.
/// </exception>
///
internal void Rename(string newName)
{
if (String.IsNullOrEmpty(newName))
{
throw new ArgumentNullException("newName");
}
Name = newName;
}
/// <summary>
/// for diagnostic purposes
/// </summary>
/// <returns></returns>
public override string ToString()
{
return ModuleCmdletBase.AddPrefixToCommandName(Name, Prefix);
}
/// <summary>
/// Indicates if the command is to be allowed to be executed by a request
/// external to the runspace.
/// </summary>
public virtual SessionStateEntryVisibility Visibility
{
get
{
return CopiedCommand == null ? _visibility : CopiedCommand.Visibility;
}
set
{
if (CopiedCommand == null)
{
_visibility = value;
}
else
{
CopiedCommand.Visibility = value;
}
if (value == SessionStateEntryVisibility.Private && Module != null)
{
Module.ModuleHasPrivateMembers = true;
}
}
}
private SessionStateEntryVisibility _visibility = SessionStateEntryVisibility.Public;
/// <summary>
/// Return a CommandMetadata instance that is never exposed publicly.
/// </summary>
internal virtual CommandMetadata CommandMetadata
{
get
{
throw new InvalidOperationException();
}
}
/// <summary>
/// Returns the syntax of a command
/// </summary>
internal virtual string Syntax
{
get { return Definition; }
}
/// <summary>
/// The module name of this command. It will be empty for commands
/// not imported from either a module or snapin.
/// </summary>
public string ModuleName
{
get
{
string moduleName = null;
if (Module != null && !string.IsNullOrEmpty(Module.Name))
{
moduleName = Module.Name;
}
else
{
CmdletInfo cmdlet = this as CmdletInfo;
if (cmdlet != null && cmdlet.PSSnapIn != null)
{
moduleName = cmdlet.PSSnapInName;
}
}
if (moduleName == null)
return string.Empty;
return moduleName;
}
}
/// <summary>
/// The module that defines this cmdlet. This will be null for commands
/// that are not defined in the context of a module.
/// </summary>
public PSModuleInfo Module { get; internal set; }
/// <summary>
/// The remoting capabilities of this cmdlet, when exposed in a context
/// with ambient remoting.
/// </summary>
public RemotingCapability RemotingCapability
{
get
{
try
{
return ExternalCommandMetadata.RemotingCapability;
}
catch (PSNotSupportedException)
{
// Thrown on an alias that hasn't been resolved yet (i.e.: in a module that
// hasn't been loaded.) Assume the default.
return RemotingCapability.PowerShell;
}
}
}
/// <summary>
/// True if the command has dynamic parameters, false otherwise.
/// </summary>
internal virtual bool ImplementsDynamicParameters
{
get { return false; }
}
/// <summary>
/// Constructs the MergedCommandParameterMetadata, using any arguments that
/// may have been specified so that dynamic parameters can be determined, if any.
/// </summary>
/// <returns></returns>
private MergedCommandParameterMetadata GetMergedCommandParameterMetadataSafely()
{
if (_context == null)
return null;
MergedCommandParameterMetadata result;
if (_context != LocalPipeline.GetExecutionContextFromTLS())
{
// In the normal case, _context is from the thread we're on, and we won't get here.
// But, if it's not, we can't safely get the parameter metadata without running on
// on the correct thread, because that thread may be busy doing something else.
// One of the things we do here is change the current scope in execution context,
// that can mess up the runspace our CommandInfo object came from.
var runspace = (RunspaceBase)_context.CurrentRunspace;
if (!runspace.RunActionIfNoRunningPipelinesWithThreadCheck(
() => GetMergedCommandParameterMetadata(out result)))
{
_context.Events.SubscribeEvent(
source: null,
eventName: PSEngineEvent.GetCommandInfoParameterMetadata,
sourceIdentifier: PSEngineEvent.GetCommandInfoParameterMetadata,
data: null,
handlerDelegate: new PSEventReceivedEventHandler(OnGetMergedCommandParameterMetadataSafelyEventHandler),
supportEvent: true,
forwardEvent: false,
shouldQueueAndProcessInExecutionThread: true,
maxTriggerCount: 1);
var eventArgs = new GetMergedCommandParameterMetadataSafelyEventArgs();
_context.Events.GenerateEvent(
sourceIdentifier: PSEngineEvent.GetCommandInfoParameterMetadata,
sender: null,
args: new[] { eventArgs },
extraData: null,
processInCurrentThread: true,
waitForCompletionInCurrentThread: true);
if (eventArgs.Exception != null)
{
// An exception happened on a different thread, rethrow it here on the correct thread.
eventArgs.Exception.Throw();
}
return eventArgs.Result;
}
}
GetMergedCommandParameterMetadata(out result);
return result;
}
private class GetMergedCommandParameterMetadataSafelyEventArgs : EventArgs
{
public MergedCommandParameterMetadata Result;
public ExceptionDispatchInfo Exception;
}
private void OnGetMergedCommandParameterMetadataSafelyEventHandler(object sender, PSEventArgs args)
{
var eventArgs = args.SourceEventArgs as GetMergedCommandParameterMetadataSafelyEventArgs;
if (eventArgs != null)
{
try
{
// Save the result in our event args as the return value.
GetMergedCommandParameterMetadata(out eventArgs.Result);
}
catch (Exception e)
{
// Save the exception so we can throw it on the correct thread.
eventArgs.Exception = ExceptionDispatchInfo.Capture(e);
}
}
}
private void GetMergedCommandParameterMetadata(out MergedCommandParameterMetadata result)
{
// MSFT:652277 - When invoking cmdlets or advanced functions, MyInvocation.MyCommand.Parameters do not contain the dynamic parameters
// When trying to get parameter metadata for a CommandInfo that has dynamic parameters, a new CommandProcessor will be
// created out of this CommandInfo and the parameter binding algorithm will be invoked. However, when this happens via
// 'MyInvocation.MyCommand.Parameter', it's actually retrieving the parameter metadata of the same cmdlet that is currently
// running. In this case, information about the specified parameters are not kept around in 'MyInvocation.MyCommand', so
// going through the binding algorithm again won't give us the metadata about the dynamic parameters that should have been
// discovered already.
// The fix is to check if the CommandInfo is actually representing the currently running cmdlet. If so, the retrieval of parameter
// metadata actually stems from the running of the same cmdlet. In this case, we can just use the current CommandProcessor to
// retrieve all bindable parameters, which should include the dynamic parameters that have been discovered already.
CommandProcessor processor;
if (Context.CurrentCommandProcessor != null && Context.CurrentCommandProcessor.CommandInfo == this)
{
// Accessing the parameters within the invocation of the same cmdlet/advanced function.
processor = (CommandProcessor)Context.CurrentCommandProcessor;
}
else
{
IScriptCommandInfo scriptCommand = this as IScriptCommandInfo;
processor = scriptCommand != null
? new CommandProcessor(scriptCommand, _context, useLocalScope: true, fromScriptFile: false,
sessionState: scriptCommand.ScriptBlock.SessionStateInternal ?? Context.EngineSessionState)
: new CommandProcessor((CmdletInfo)this, _context) { UseLocalScope = true };
ParameterBinderController.AddArgumentsToCommandProcessor(processor, Arguments);
CommandProcessorBase oldCurrentCommandProcessor = Context.CurrentCommandProcessor;
try
{
Context.CurrentCommandProcessor = processor;
processor.SetCurrentScopeToExecutionScope();
processor.CmdletParameterBinderController.BindCommandLineParametersNoValidation(processor.arguments);
}
catch (ParameterBindingException)
{
// Ignore the binding exception if no arugment is specified
if (processor.arguments.Count > 0)
{
throw;
}
}
finally
{
Context.CurrentCommandProcessor = oldCurrentCommandProcessor;
processor.RestorePreviousScope();
}
}
result = processor.CmdletParameterBinderController.BindableParameters;
}
/// <summary>
/// Return the parameters for this command.
/// </summary>
public virtual Dictionary<string, ParameterMetadata> Parameters
{
get
{
Dictionary<string, ParameterMetadata> result = new Dictionary<string, ParameterMetadata>(StringComparer.OrdinalIgnoreCase);
if (ImplementsDynamicParameters && Context != null)
{
MergedCommandParameterMetadata merged = GetMergedCommandParameterMetadataSafely();
foreach (KeyValuePair<string, MergedCompiledCommandParameter> pair in merged.BindableParameters)
{
result.Add(pair.Key, new ParameterMetadata(pair.Value.Parameter));
}
// Don't cache this data...
return result;
}
return ExternalCommandMetadata.Parameters;
}
}
internal CommandMetadata ExternalCommandMetadata
{
get { return _externalCommandMetadata ?? (_externalCommandMetadata = new CommandMetadata(this, true)); }
set { _externalCommandMetadata = value; }
}
private CommandMetadata _externalCommandMetadata;
/// <summary>
/// Resolves a full, shortened, or aliased parameter name to the actual
/// cmdlet parameter name, using PowerShell's standard parameter resolution
/// algorithm.
/// </summary>
/// <param name="name">The name of the parameter to resolve.</param>
/// <returns>The parameter that matches this name</returns>
public ParameterMetadata ResolveParameter(string name)
{
MergedCommandParameterMetadata merged = GetMergedCommandParameterMetadataSafely();
MergedCompiledCommandParameter result = merged.GetMatchingParameter(name, true, true, null);
return this.Parameters[result.Parameter.Name];
}
/// <summary>
/// Gets the information about the parameters and parameter sets for
/// this command.
/// </summary>
public ReadOnlyCollection<CommandParameterSetInfo> ParameterSets
{
get
{
if (_parameterSets == null)
{
Collection<CommandParameterSetInfo> parameterSetInfo =
GenerateCommandParameterSetInfo();
_parameterSets = new ReadOnlyCollection<CommandParameterSetInfo>(parameterSetInfo);
}
return _parameterSets;
}
} // ParameterSets
internal ReadOnlyCollection<CommandParameterSetInfo> _parameterSets;
/// <summary>
/// A possibly incomplete or even incorrect list of types the command could return.
/// </summary>
[SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")]
public abstract ReadOnlyCollection<PSTypeName> OutputType { get; }
/// <summary>
/// Specifies whether this command was imported from a module or not.
/// This is used in Get-Command to figure out which of the commands in module session state were imported.
/// </summary>
internal bool IsImported { get; set; } = false;
/// <summary>
/// The prefix that was used when importing this command
/// </summary>
internal string Prefix { get; set; } = "";
/// <summary>
/// Create a copy of commandInfo for GetCommandCommand so that we can generate parameter
/// sets based on an argument list (so we can get the dynamic parameters.)
/// </summary>
internal virtual CommandInfo CreateGetCommandCopy(object[] argumentList)
{
throw new InvalidOperationException();
}
/// <summary>
/// Generates the parameter and parameter set info from the cmdlet metadata
/// </summary>
///
/// <returns>
/// A collection of CommandParameterSetInfo representing the cmdlet metadata.
/// </returns>
///
/// <exception cref="ArgumentException">
/// The type name is invalid or the length of the type name
/// exceeds 1024 characters.
/// </exception>
///
/// <exception cref="System.Security.SecurityException">
/// The caller does not have the required permission to load the assembly
/// or create the type.
/// </exception>
///
/// <exception cref="ParsingMetadataException">
/// If more than int.MaxValue parameter-sets are defined for the command.
/// </exception>
///
/// <exception cref="MetadataException">
/// If a parameter defines the same parameter-set name multiple times.
/// If the attributes could not be read from a property or field.
/// </exception>
///
internal Collection<CommandParameterSetInfo> GenerateCommandParameterSetInfo()
{
Collection<CommandParameterSetInfo> result;
if (IsGetCommandCopy && ImplementsDynamicParameters)
{
result = GetParameterMetadata(CommandMetadata, GetMergedCommandParameterMetadataSafely());
}
else
{
result = GetCacheableMetadata(CommandMetadata);
}
return result;
}
/// <summary>
/// Gets or sets whether this CmdletInfo instance is a copy used for get-command.
/// If true, and the cmdlet supports dynamic parameters, it means that the dynamic
/// parameter metadata will be merged into the parameter set information.
/// </summary>
internal bool IsGetCommandCopy { get; set; }
/// <summary>
/// Gets or sets the command line arguments/parameters that were specified
/// which will allow for the dynamic parameters to be retrieved and their
/// metadata merged into the parameter set information.
/// </summary>
internal object[] Arguments { get; set; }
internal static Collection<CommandParameterSetInfo> GetCacheableMetadata(CommandMetadata metadata)
{
return GetParameterMetadata(metadata, metadata.StaticCommandParameterMetadata);
}
internal static Collection<CommandParameterSetInfo> GetParameterMetadata(CommandMetadata metadata, MergedCommandParameterMetadata parameterMetadata)
{
Collection<CommandParameterSetInfo> result = new Collection<CommandParameterSetInfo>();
if (parameterMetadata != null)
{
if (parameterMetadata.ParameterSetCount == 0)
{
const string parameterSetName = ParameterAttribute.AllParameterSets;
result.Add(
new CommandParameterSetInfo(
parameterSetName,
false,
uint.MaxValue,
parameterMetadata));
}
else
{
int parameterSetCount = parameterMetadata.ParameterSetCount;
for (int index = 0; index < parameterSetCount; ++index)
{
uint currentFlagPosition = (uint)0x1 << index;
// Get the parameter set name
string parameterSetName = parameterMetadata.GetParameterSetName(currentFlagPosition);
// Is the parameter set the default?
bool isDefaultParameterSet = (currentFlagPosition & metadata.DefaultParameterSetFlag) != 0;
result.Add(
new CommandParameterSetInfo(
parameterSetName,
isDefaultParameterSet,
currentFlagPosition,
parameterMetadata));
}
}
}
return result;
} // GetParameterMetadata
} // CommandInfo
/// <summary>
/// Represents <see cref="System.Type"/>, but can be used where a real type
/// might not be available, in which case the name of the type can be used.
/// </summary>
public class PSTypeName
{
/// <summary>
/// This constructor is used when the type exists and is currently loaded.
/// </summary>
/// <param name="type">The type</param>
public PSTypeName(Type type)
{
_type = type;
if (_type != null)
{
Name = _type.FullName;
}
}
/// <summary>
/// This constructor is used when the type may not exist, or is not loaded.
/// </summary>
/// <param name="name">The name of the type</param>
public PSTypeName(string name)
{
Name = name;
_type = null;
}
/// <summary>
/// This constructor is used when the type is defined in PowerShell.
/// </summary>
/// <param name="typeDefinitionAst">The type definition from the ast.</param>
public PSTypeName(TypeDefinitionAst typeDefinitionAst)
{
if (typeDefinitionAst == null)
{
throw PSTraceSource.NewArgumentNullException("typeDefinitionAst");
}
TypeDefinitionAst = typeDefinitionAst;
Name = typeDefinitionAst.Name;
}
/// <summary>
/// This constructor creates a type from a ITypeName.
/// </summary>
public PSTypeName(ITypeName typeName)
{
if (typeName == null)
{
throw PSTraceSource.NewArgumentNullException("typeName");
}
_type = typeName.GetReflectionType();
if (_type != null)
{
Name = _type.FullName;
}
else
{
var t = typeName as TypeName;
if (t != null && t._typeDefinitionAst != null)
{
TypeDefinitionAst = t._typeDefinitionAst;
Name = TypeDefinitionAst.Name;
}
else
{
_type = null;
Name = typeName.FullName;
}
}
}
/// <summary>
/// Return the name of the type
/// </summary>
public string Name { get; }
/// <summary>
/// Return the type with metadata, or null if the type is not loaded.
/// </summary>
[SuppressMessage("Microsoft.Naming", "CA1721:PropertyNamesShouldNotMatchGetMethods")]
public Type Type
{
get
{
if (!_typeWasCalculated)
{
if (_type == null)
{
if (TypeDefinitionAst != null)
{
_type = TypeDefinitionAst.Type;
}
else
{
TypeResolver.TryResolveType(Name, out _type);
}
}
if (_type == null)
{
// We ignore the exception.
if (Name != null &&
Name.StartsWith("[", StringComparison.OrdinalIgnoreCase) &&
Name.EndsWith("]", StringComparison.OrdinalIgnoreCase))
{
string tmp = Name.Substring(1, Name.Length - 2);
TypeResolver.TryResolveType(tmp, out _type);
}
}
_typeWasCalculated = true;
}
return _type;
}
}
private Type _type;
/// <summary>
/// When a type is defined by PowerShell, the ast for that type.
/// </summary>
public TypeDefinitionAst TypeDefinitionAst { get; private set; }
private bool _typeWasCalculated;
/// <summary>
/// Returns a String that represents the current PSTypeName.
/// </summary>
/// <returns> String that represents the current PSTypeName.</returns>
public override string ToString()
{
return Name ?? string.Empty;
}
}
internal interface IScriptCommandInfo
{
ScriptBlock ScriptBlock { get; }
}
} // namespace System.Management.Automation
| |
// MvxPictureChooserTask.cs
// (c) Copyright Cirrious Ltd. http://www.cirrious.com
// MvvmCross is licensed using Microsoft Public License (Ms-PL)
// Contributions and inspirations noted in readme.md and license.txt
//
// Project Lead - Stuart Lodge, @slodge, me@slodge.com
using System;
using System.IO;
using System.Threading.Tasks;
using Android.App;
using Android.Content;
using Android.Graphics;
using Android.Provider;
using MvvmCross.Platform.Droid;
using MvvmCross.Platform.Droid.Platform;
using MvvmCross.Platform.Droid.Views;
using MvvmCross.Platform.Exceptions;
using MvvmCross.Platform;
using MvvmCross.Platform.Platform;
using Uri = Android.Net.Uri;
namespace MvvmCross.Plugins.PictureChooser.Droid
{
[Preserve(AllMembers = true)]
public class MvxPictureChooserTask
: MvxAndroidTask
, IMvxPictureChooserTask
{
private Uri _cachedUriLocation;
private RequestParameters _currentRequestParameters;
#region IMvxPictureChooserTask Members
public void ChoosePictureFromLibrary(int maxPixelDimension, int percentQuality, Action<Stream, string> pictureAvailable,
Action assumeCancelled)
{
var intent = new Intent(Intent.ActionGetContent);
intent.SetType("image/*");
ChoosePictureCommon(MvxIntentRequestCode.PickFromFile, intent, maxPixelDimension, percentQuality,
pictureAvailable, assumeCancelled);
}
public void ChoosePictureFromLibrary(int maxPixelDimension, int percentQuality, Action<Stream> pictureAvailable,
Action assumeCancelled)
{
this.ChoosePictureFromLibrary(maxPixelDimension, percentQuality, (stream, name) => pictureAvailable(stream), assumeCancelled);
}
public void TakePicture(int maxPixelDimension, int percentQuality, Action<Stream> pictureAvailable,
Action assumeCancelled)
{
var intent = new Intent(MediaStore.ActionImageCapture);
_cachedUriLocation = GetNewImageUri();
intent.PutExtra(MediaStore.ExtraOutput, _cachedUriLocation);
intent.PutExtra("outputFormat", Bitmap.CompressFormat.Jpeg.ToString());
intent.PutExtra("return-data", true);
ChoosePictureCommon(MvxIntentRequestCode.PickFromCamera, intent, maxPixelDimension, percentQuality,
(stream, name) => pictureAvailable(stream), assumeCancelled);
}
public Task<Stream> ChoosePictureFromLibrary(int maxPixelDimension, int percentQuality)
{
var task = new TaskCompletionSource<Stream>();
ChoosePictureFromLibrary(maxPixelDimension, percentQuality, task.SetResult, () => task.SetResult(null));
return task.Task;
}
public Task<Stream> TakePicture(int maxPixelDimension, int percentQuality)
{
var task = new TaskCompletionSource<Stream>();
TakePicture(maxPixelDimension, percentQuality, task.SetResult, () => task.SetResult(null));
return task.Task;
}
public void ContinueFileOpenPicker(object args)
{
}
#endregion
private Uri GetNewImageUri()
{
// Optional - specify some metadata for the picture
var contentValues = new ContentValues();
//contentValues.Put(MediaStore.Images.ImageColumnsConsts.Description, "A camera photo");
// Specify where to put the image
return
Mvx.Resolve<IMvxAndroidGlobals>()
.ApplicationContext.ContentResolver.Insert(MediaStore.Images.Media.ExternalContentUri, contentValues);
}
public void ChoosePictureCommon(MvxIntentRequestCode pickId, Intent intent, int maxPixelDimension,
int percentQuality, Action<Stream, string> pictureAvailable, Action assumeCancelled)
{
if (_currentRequestParameters != null)
throw new MvxException("Cannot request a second picture while the first request is still pending");
_currentRequestParameters = new RequestParameters(maxPixelDimension, percentQuality, pictureAvailable,
assumeCancelled);
StartActivityForResult((int) pickId, intent);
}
protected override void ProcessMvxIntentResult(MvxIntentResultEventArgs result)
{
MvxTrace.Trace("ProcessMvxIntentResult started...");
Uri uri;
switch ((MvxIntentRequestCode) result.RequestCode)
{
case MvxIntentRequestCode.PickFromFile:
uri = result.Data?.Data;
break;
case MvxIntentRequestCode.PickFromCamera:
uri = _cachedUriLocation;
break;
default:
// ignore this result - it's not for us
MvxTrace.Trace("Unexpected request received from MvxIntentResult - request was {0}",
result.RequestCode);
return;
}
ProcessPictureUri(result, uri);
}
private void ProcessPictureUri(MvxIntentResultEventArgs result, Uri uri)
{
if (_currentRequestParameters == null)
{
MvxTrace.Error("Internal error - response received but _currentRequestParameters is null");
return; // we have not handled this - so we return null
}
var responseSent = false;
try
{
// Note for furture bug-fixing/maintenance - it might be better to use var outputFileUri = data.GetParcelableArrayExtra("outputFileuri") here?
if (result.ResultCode != Result.Ok)
{
MvxTrace.Trace("Non-OK result received from MvxIntentResult - {0} - request was {1}",
result.ResultCode, result.RequestCode);
return;
}
if (string.IsNullOrEmpty(uri?.Path))
{
MvxTrace.Trace("Empty uri or file path received for MvxIntentResult");
return;
}
MvxTrace.Trace("Loading InMemoryBitmap started...");
var memoryStream = LoadInMemoryBitmap(uri);
if (memoryStream == null)
{
MvxTrace.Trace("Loading InMemoryBitmap failed...");
return;
}
MvxTrace.Trace("Loading InMemoryBitmap complete...");
responseSent = true;
MvxTrace.Trace("Sending pictureAvailable...");
_currentRequestParameters.PictureAvailable(memoryStream, System.IO.Path.GetFileNameWithoutExtension(uri.Path));
MvxTrace.Trace("pictureAvailable completed...");
return;
}
finally
{
if (!responseSent)
_currentRequestParameters.AssumeCancelled();
_currentRequestParameters = null;
}
}
private MemoryStream LoadInMemoryBitmap(Uri uri)
{
var memoryStream = new MemoryStream();
var bitmap = LoadScaledBitmap(uri);
if (bitmap == null)
return null;
using (bitmap)
{
bitmap.Compress(Bitmap.CompressFormat.Jpeg, _currentRequestParameters.PercentQuality, memoryStream);
}
memoryStream.Seek(0L, SeekOrigin.Begin);
return memoryStream;
}
private Bitmap LoadScaledBitmap(Uri uri)
{
ContentResolver contentResolver = Mvx.Resolve<IMvxAndroidGlobals>().ApplicationContext.ContentResolver;
var maxDimensionSize = GetMaximumDimension(contentResolver, uri);
var sampleSize = (int) Math.Ceiling((maxDimensionSize)/
((double) _currentRequestParameters.MaxPixelDimension));
if (sampleSize < 1)
{
// this shouldn't happen, but if it does... then trace the error and set sampleSize to 1
MvxTrace.Trace(
"Warning - sampleSize of {0} was requested - how did this happen - based on requested {1} and returned image size {2}",
sampleSize,
_currentRequestParameters.MaxPixelDimension,
maxDimensionSize);
// following from https://github.com/MvvmCross/MvvmCross/issues/565 we return null in this case
// - it suggests that Android has returned a corrupt image uri
return null;
}
var sampled = LoadResampledBitmap(contentResolver, uri, sampleSize);
try
{
var rotated = ExifRotateBitmap(contentResolver, uri, sampled);
return rotated;
}
catch (Exception pokemon)
{
Mvx.Trace("Problem seem in Exit Rotate {0}", pokemon.ToLongString());
return sampled;
}
}
private Bitmap LoadResampledBitmap(ContentResolver contentResolver, Uri uri, int sampleSize)
{
using (var inputStream = contentResolver.OpenInputStream(uri))
{
var optionsDecode = new BitmapFactory.Options {InSampleSize = sampleSize};
return BitmapFactory.DecodeStream(inputStream, null, optionsDecode);
}
}
private static int GetMaximumDimension(ContentResolver contentResolver, Uri uri)
{
using (var inputStream = contentResolver.OpenInputStream(uri))
{
var optionsJustBounds = new BitmapFactory.Options
{
InJustDecodeBounds = true
};
var metadataResult = BitmapFactory.DecodeStream(inputStream, null, optionsJustBounds);
var maxDimensionSize = Math.Max(optionsJustBounds.OutWidth, optionsJustBounds.OutHeight);
return maxDimensionSize;
}
}
private Bitmap ExifRotateBitmap(ContentResolver contentResolver, Uri uri, Bitmap bitmap)
{
if (bitmap == null)
return null;
var exif = new Android.Media.ExifInterface(GetRealPathFromUri(contentResolver, uri));
var rotation = exif.GetAttributeInt(Android.Media.ExifInterface.TagOrientation, (Int32)Android.Media.Orientation.Normal);
var rotationInDegrees = ExifToDegrees(rotation);
if (rotationInDegrees == 0)
return bitmap;
using (var matrix = new Matrix())
{
matrix.PreRotate(rotationInDegrees);
return Bitmap.CreateBitmap(bitmap, 0, 0, bitmap.Width, bitmap.Height, matrix, true);
}
}
private String GetRealPathFromUri(ContentResolver contentResolver, Uri uri)
{
var proj = new String[] { MediaStore.Images.ImageColumns.Data };
using (var cursor = contentResolver.Query(uri, proj, null, null, null))
{
var columnIndex = cursor.GetColumnIndexOrThrow(MediaStore.Images.ImageColumns.Data);
cursor.MoveToFirst();
return cursor.GetString(columnIndex);
}
}
private static Int32 ExifToDegrees(Int32 exifOrientation)
{
switch (exifOrientation)
{
case (Int32)Android.Media.Orientation.Rotate90:
return 90;
case (Int32)Android.Media.Orientation.Rotate180:
return 180;
case (Int32)Android.Media.Orientation.Rotate270:
return 270;
}
return 0;
}
#region Nested type: RequestParameters
private class RequestParameters
{
public RequestParameters(int maxPixelDimension, int percentQuality, Action<Stream, string> pictureAvailable,
Action assumeCancelled)
{
PercentQuality = percentQuality;
MaxPixelDimension = maxPixelDimension;
AssumeCancelled = assumeCancelled;
PictureAvailable = pictureAvailable;
}
public Action<Stream, string> PictureAvailable { get; private set; }
public Action AssumeCancelled { get; private set; }
public int MaxPixelDimension { get; private set; }
public int PercentQuality { get; private set; }
}
#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.Collections.Generic;
using System.Globalization;
using Xunit;
namespace System.Tests
{
public static partial class TimeSpanTests
{
private static IEnumerable<object[]> MultiplicationTestData()
{
yield return new object[] {new TimeSpan(2, 30, 0), 2.0, new TimeSpan(5, 0, 0)};
yield return new object[] {new TimeSpan(14, 2, 30, 0), 192.0, TimeSpan.FromDays(2708)};
yield return new object[] {TimeSpan.FromDays(366), Math.PI, new TimeSpan(993446995288779)};
yield return new object[] {TimeSpan.FromDays(366), -Math.E, new TimeSpan(-859585952922633)};
yield return new object[] {TimeSpan.FromDays(29.530587981), 13.0, TimeSpan.FromDays(383.897643819444)};
yield return new object[] {TimeSpan.FromDays(-29.530587981), -12.0, TimeSpan.FromDays(354.367055833333)};
yield return new object[] {TimeSpan.FromDays(-29.530587981), 0.0, TimeSpan.Zero};
yield return new object[] {TimeSpan.MaxValue, 0.5, TimeSpan.FromTicks((long)(long.MaxValue * 0.5))};
}
[Theory, MemberData(nameof(MultiplicationTestData))]
public static void Multiplication(TimeSpan timeSpan, double factor, TimeSpan expected)
{
Assert.Equal(expected, timeSpan * factor);
Assert.Equal(expected, factor * timeSpan);
}
[Fact]
public static void OverflowingMultiplication()
{
Assert.Throws<OverflowException>(() => TimeSpan.MaxValue * 1.000000001);
Assert.Throws<OverflowException>(() => -1.000000001 * TimeSpan.MaxValue);
}
[Fact]
public static void NaNMultiplication()
{
AssertExtensions.Throws<ArgumentException>("factor", () => TimeSpan.FromDays(1) * double.NaN);
AssertExtensions.Throws<ArgumentException>("factor", () => double.NaN * TimeSpan.FromDays(1));
}
[Theory, MemberData(nameof(MultiplicationTestData))]
public static void Division(TimeSpan timeSpan, double factor, TimeSpan expected)
{
Assert.Equal(factor, expected / timeSpan, 14);
double divisor = 1.0 / factor;
Assert.Equal(expected, timeSpan / divisor);
}
[Fact]
public static void DivideByZero()
{
Assert.Throws<OverflowException>(() => TimeSpan.FromDays(1) / 0);
Assert.Throws<OverflowException>(() => TimeSpan.FromDays(-1) / 0);
Assert.Throws<OverflowException>(() => TimeSpan.Zero / 0);
Assert.Equal(double.PositiveInfinity, TimeSpan.FromDays(1) / TimeSpan.Zero);
Assert.Equal(double.NegativeInfinity, TimeSpan.FromDays(-1) / TimeSpan.Zero);
Assert.True(double.IsNaN(TimeSpan.Zero / TimeSpan.Zero));
}
[Fact]
public static void NaNDivision()
{
AssertExtensions.Throws<ArgumentException>("divisor", () => TimeSpan.FromDays(1) / double.NaN);
}
[Theory, MemberData(nameof(MultiplicationTestData))]
public static void NamedMultiplication(TimeSpan timeSpan, double factor, TimeSpan expected)
{
Assert.Equal(expected, timeSpan.Multiply(factor));
}
[Fact]
public static void NamedOverflowingMultiplication()
{
Assert.Throws<OverflowException>(() => TimeSpan.MaxValue.Multiply(1.000000001));
}
[Fact]
public static void NamedNaNMultiplication()
{
AssertExtensions.Throws<ArgumentException>("factor", () => TimeSpan.FromDays(1).Multiply(double.NaN));
}
[Theory, MemberData(nameof(MultiplicationTestData))]
public static void NamedDivision(TimeSpan timeSpan, double factor, TimeSpan expected)
{
Assert.Equal(factor, expected.Divide(timeSpan), 14);
double divisor = 1.0 / factor;
Assert.Equal(expected, timeSpan.Divide(divisor));
}
[Fact]
public static void NamedDivideByZero()
{
Assert.Throws<OverflowException>(() => TimeSpan.FromDays(1).Divide(0));
Assert.Throws<OverflowException>(() => TimeSpan.FromDays(-1).Divide(0));
Assert.Throws<OverflowException>(() => TimeSpan.Zero.Divide(0));
Assert.Equal(double.PositiveInfinity, TimeSpan.FromDays(1).Divide(TimeSpan.Zero));
Assert.Equal(double.NegativeInfinity, TimeSpan.FromDays(-1).Divide(TimeSpan.Zero));
Assert.True(double.IsNaN(TimeSpan.Zero.Divide(TimeSpan.Zero)));
}
[Fact]
public static void NamedNaNDivision()
{
AssertExtensions.Throws<ArgumentException>("divisor", () => TimeSpan.FromDays(1).Divide(double.NaN));
}
[Theory]
[MemberData(nameof(Parse_Valid_TestData))]
public static void Parse_Span(string inputString, IFormatProvider provider, TimeSpan expected)
{
ReadOnlySpan<char> input = inputString.AsReadOnlySpan();
TimeSpan result;
Assert.Equal(expected, TimeSpan.Parse(input, provider));
Assert.True(TimeSpan.TryParse(input, provider, out result));
Assert.Equal(expected, result);
// Also negate
if (!char.IsWhiteSpace(input[0]))
{
input = ("-" + inputString).AsReadOnlySpan();
expected = -expected;
Assert.Equal(expected, TimeSpan.Parse(input, provider));
Assert.True(TimeSpan.TryParse(input, provider, out result));
Assert.Equal(expected, result);
}
}
[Theory]
[MemberData(nameof(Parse_Invalid_TestData))]
public static void Parse_Span_Invalid(string inputString, IFormatProvider provider, Type exceptionType)
{
if (inputString != null)
{
Assert.Throws(exceptionType, () => TimeSpan.Parse(inputString.AsReadOnlySpan(), provider));
Assert.False(TimeSpan.TryParse(inputString.AsReadOnlySpan(), provider, out TimeSpan result));
Assert.Equal(TimeSpan.Zero, result);
}
}
[Theory]
[MemberData(nameof(ParseExact_Valid_TestData))]
public static void ParseExact_Span_Valid(string inputString, string format, TimeSpan expected)
{
ReadOnlySpan<char> input = inputString.AsReadOnlySpan();
TimeSpan result;
Assert.Equal(expected, TimeSpan.ParseExact(input, format, new CultureInfo("en-US")));
Assert.Equal(expected, TimeSpan.ParseExact(input, new[] { format }, new CultureInfo("en-US")));
Assert.True(TimeSpan.TryParseExact(input, format, new CultureInfo("en-US"), out result));
Assert.Equal(expected, result);
Assert.True(TimeSpan.TryParseExact(input, new[] { format }, new CultureInfo("en-US"), out result));
Assert.Equal(expected, result);
if (format != "c" && format != "t" && format != "T" && format != "g" && format != "G")
{
// TimeSpanStyles is interpreted only for custom formats
Assert.Equal(expected.Negate(), TimeSpan.ParseExact(input, format, new CultureInfo("en-US"), TimeSpanStyles.AssumeNegative));
Assert.True(TimeSpan.TryParseExact(input, format, new CultureInfo("en-US"), TimeSpanStyles.AssumeNegative, out result));
Assert.Equal(expected.Negate(), result);
}
else
{
// Inputs that can be parsed in standard formats with ParseExact should also be parsable with Parse
Assert.Equal(expected, TimeSpan.Parse(input, CultureInfo.InvariantCulture));
Assert.True(TimeSpan.TryParse(input, CultureInfo.InvariantCulture, out result));
Assert.Equal(expected, result);
}
}
[Theory]
[MemberData(nameof(ParseExact_Invalid_TestData))]
public static void ParseExactTest_Span_Invalid(string inputString, string format, Type exceptionType)
{
if (inputString != null && format != null)
{
Assert.Throws(exceptionType, () => TimeSpan.ParseExact(inputString.AsReadOnlySpan(), format, new CultureInfo("en-US")));
TimeSpan result;
Assert.False(TimeSpan.TryParseExact(inputString.AsReadOnlySpan(), format, new CultureInfo("en-US"), out result));
Assert.Equal(TimeSpan.Zero, result);
Assert.False(TimeSpan.TryParseExact(inputString.AsReadOnlySpan(), new[] { format }, new CultureInfo("en-US"), out result));
Assert.Equal(TimeSpan.Zero, result);
}
}
[Fact]
public static void ParseExactMultiple_Span_InvalidNullEmptyFormats()
{
TimeSpan result;
AssertExtensions.Throws<ArgumentNullException>("formats", () => TimeSpan.ParseExact("12:34:56".AsReadOnlySpan(), (string[])null, null));
Assert.False(TimeSpan.TryParseExact("12:34:56".AsReadOnlySpan(), (string[])null, null, out result));
Assert.Throws<FormatException>(() => TimeSpan.ParseExact("12:34:56".AsReadOnlySpan(), new string[0], null));
Assert.False(TimeSpan.TryParseExact("12:34:56".AsReadOnlySpan(), new string[0], null, out result));
}
[Theory]
[MemberData(nameof(ToString_MemberData))]
public static void TryFormat_Valid(TimeSpan input, string format, string expected)
{
int charsWritten;
Span<char> dst;
dst = new char[expected.Length - 1];
Assert.False(input.TryFormat(dst, out charsWritten, format, CultureInfo.InvariantCulture));
Assert.Equal(0, charsWritten);
dst = new char[expected.Length];
Assert.True(input.TryFormat(dst, out charsWritten, format, CultureInfo.InvariantCulture));
Assert.Equal(expected.Length, charsWritten);
Assert.Equal(expected, new string(dst));
dst = new char[expected.Length + 1];
Assert.True(input.TryFormat(dst, out charsWritten, format, CultureInfo.InvariantCulture));
Assert.Equal(expected.Length, charsWritten);
Assert.Equal(expected, new string(dst.Slice(0, dst.Length - 1)));
Assert.Equal(0, dst[dst.Length - 1]);
}
}
}
| |
using Discord;
using Discord.WebSocket;
using NadekoBot.Common;
using NadekoBot.Common.Collections;
using NadekoBot.Core.Modules.Xp.Common;
using NadekoBot.Core.Services;
using NadekoBot.Core.Services.Database.Models;
using NadekoBot.Core.Services.Impl;
using NadekoBot.Extensions;
using NadekoBot.Modules.Xp.Common;
using Newtonsoft.Json;
using NLog;
using SixLabors.Fonts;
using SixLabors.ImageSharp;
using SixLabors.ImageSharp.Formats;
using SixLabors.ImageSharp.PixelFormats;
using SixLabors.ImageSharp.Processing;
using SixLabors.ImageSharp.Processing.Drawing;
using SixLabors.ImageSharp.Processing.Drawing.Brushes;
using SixLabors.ImageSharp.Processing.Drawing.Pens;
using SixLabors.ImageSharp.Processing.Text;
using SixLabors.ImageSharp.Processing.Transforms;
using SixLabors.Primitives;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Threading.Tasks;
using Image = SixLabors.ImageSharp.Image;
namespace NadekoBot.Modules.Xp.Services
{
public class XpService : INService, IUnloadableService
{
private enum NotifOf { Server, Global } // is it a server level-up or global level-up notification
private readonly DbService _db;
private readonly CommandHandler _cmd;
private readonly IBotConfigProvider _bc;
private readonly IImageCache _images;
private readonly Logger _log;
private readonly NadekoStrings _strings;
private readonly IDataCache _cache;
private readonly FontProvider _fonts;
private readonly IBotCredentials _creds;
private readonly ICurrencyService _cs;
public const int XP_REQUIRED_LVL_1 = 36;
private readonly ConcurrentDictionary<ulong, ConcurrentHashSet<ulong>> _excludedRoles
= new ConcurrentDictionary<ulong, ConcurrentHashSet<ulong>>();
private readonly ConcurrentDictionary<ulong, ConcurrentHashSet<ulong>> _excludedChannels
= new ConcurrentDictionary<ulong, ConcurrentHashSet<ulong>>();
private readonly ConcurrentHashSet<ulong> _excludedServers
= new ConcurrentHashSet<ulong>();
private readonly ConcurrentQueue<UserCacheItem> _addMessageXp
= new ConcurrentQueue<UserCacheItem>();
private readonly Task updateXpTask;
private readonly IHttpClientFactory _httpFactory;
private XpTemplate _template;
public XpService(DiscordSocketClient client, CommandHandler cmd, IBotConfigProvider bc,
NadekoBot bot, DbService db, NadekoStrings strings, IDataCache cache,
FontProvider fonts, IBotCredentials creds, ICurrencyService cs, IHttpClientFactory http)
{
_db = db;
_cmd = cmd;
_bc = bc;
_images = cache.LocalImages;
_log = LogManager.GetCurrentClassLogger();
_strings = strings;
_cache = cache;
_fonts = fonts;
_creds = creds;
_cs = cs;
_httpFactory = http;
InternalReloadXpTemplate();
if (client.ShardId == 0)
{
var sub = _cache.Redis.GetSubscriber();
sub.Subscribe(_creds.RedisKey() + "_reload_xp_template",
(ch, val) => InternalReloadXpTemplate());
}
//load settings
var allGuildConfigs = bot.AllGuildConfigs.Where(x => x.XpSettings != null);
_excludedChannels = allGuildConfigs
.ToDictionary(
x => x.GuildId,
x => new ConcurrentHashSet<ulong>(x.XpSettings
.ExclusionList
.Where(ex => ex.ItemType == ExcludedItemType.Channel)
.Select(ex => ex.ItemId)
.Distinct()))
.ToConcurrent();
_excludedRoles = allGuildConfigs
.ToDictionary(
x => x.GuildId,
x => new ConcurrentHashSet<ulong>(x.XpSettings
.ExclusionList
.Where(ex => ex.ItemType == ExcludedItemType.Role)
.Select(ex => ex.ItemId)
.Distinct()))
.ToConcurrent();
_excludedServers = new ConcurrentHashSet<ulong>(
allGuildConfigs.Where(x => x.XpSettings.ServerExcluded)
.Select(x => x.GuildId));
_cmd.OnMessageNoTrigger += _cmd_OnMessageNoTrigger;
updateXpTask = Task.Run(async () =>
{
while (true)
{
await Task.Delay(TimeSpan.FromSeconds(5));
try
{
var toNotify = new List<(IMessageChannel MessageChannel, IUser User, int Level, XpNotificationType NotifyType, NotifOf NotifOf)>();
var roleRewards = new Dictionary<ulong, List<XpRoleReward>>();
var curRewards = new Dictionary<ulong, List<XpCurrencyReward>>();
var toAddTo = new List<UserCacheItem>();
while (_addMessageXp.TryDequeue(out var usr))
toAddTo.Add(usr);
var group = toAddTo.GroupBy(x => (GuildId: x.Guild.Id, x.User));
if (toAddTo.Count == 0)
continue;
using (var uow = _db.UnitOfWork)
{
foreach (var item in group)
{
var xp = item.Select(x => bc.BotConfig.XpPerMessage).Sum();
//1. Mass query discord users and userxpstats and get them from local dict
//2. (better but much harder) Move everything to the database, and get old and new xp
// amounts for every user (in order to give rewards)
var usr = uow.Xp.GetOrCreateUser(item.Key.GuildId, item.Key.User.Id);
var du = uow.DiscordUsers.GetOrCreate(item.Key.User);
var globalXp = du.TotalXp;
var oldGlobalLevelData = new LevelStats(globalXp);
var newGlobalLevelData = new LevelStats(globalXp + xp);
var oldGuildLevelData = new LevelStats(usr.Xp + usr.AwardedXp);
usr.Xp += xp;
du.TotalXp += xp;
if (du.Club != null)
du.Club.Xp += xp;
var newGuildLevelData = new LevelStats(usr.Xp + usr.AwardedXp);
if (oldGlobalLevelData.Level < newGlobalLevelData.Level)
{
du.LastLevelUp = DateTime.UtcNow;
var first = item.First();
if (du.NotifyOnLevelUp != XpNotificationType.None)
toNotify.Add((first.Channel, first.User, newGlobalLevelData.Level, du.NotifyOnLevelUp, NotifOf.Global));
}
if (oldGuildLevelData.Level < newGuildLevelData.Level)
{
usr.LastLevelUp = DateTime.UtcNow;
//send level up notification
var first = item.First();
if (usr.NotifyOnLevelUp != XpNotificationType.None)
toNotify.Add((first.Channel, first.User, newGuildLevelData.Level, usr.NotifyOnLevelUp, NotifOf.Server));
//give role
if (!roleRewards.TryGetValue(usr.GuildId, out var rrews))
{
rrews = uow.GuildConfigs.XpSettingsFor(usr.GuildId).RoleRewards.ToList();
roleRewards.Add(usr.GuildId, rrews);
}
if (!curRewards.TryGetValue(usr.GuildId, out var crews))
{
crews = uow.GuildConfigs.XpSettingsFor(usr.GuildId).CurrencyRewards.ToList();
curRewards.Add(usr.GuildId, crews);
}
var rrew = rrews.FirstOrDefault(x => x.Level == newGuildLevelData.Level);
if (rrew != null)
{
var role = first.User.Guild.GetRole(rrew.RoleId);
if (role != null)
{
var __ = first.User.AddRoleAsync(role);
}
}
//get currency reward for this level
var crew = crews.FirstOrDefault(x => x.Level == newGuildLevelData.Level);
if (crew != null)
{
//give the user the reward if it exists
await _cs.AddAsync(item.Key.User.Id, "Level-up Reward", crew.Amount);
}
}
}
uow.Complete();
}
await Task.WhenAll(toNotify.Select(async x =>
{
if (x.NotifOf == NotifOf.Server)
{
if (x.NotifyType == XpNotificationType.Dm)
{
var chan = await x.User.GetOrCreateDMChannelAsync();
if (chan != null)
await chan.SendConfirmAsync(_strings.GetText("level_up_dm",
(x.MessageChannel as ITextChannel)?.GuildId,
"xp",
x.User.Mention, Format.Bold(x.Level.ToString()),
Format.Bold((x.MessageChannel as ITextChannel)?.Guild.ToString() ?? "-")));
}
else // channel
{
await x.MessageChannel.SendConfirmAsync(_strings.GetText("level_up_channel",
(x.MessageChannel as ITextChannel)?.GuildId,
"xp",
x.User.Mention, Format.Bold(x.Level.ToString())));
}
}
else
{
IMessageChannel chan;
if (x.NotifyType == XpNotificationType.Dm)
{
chan = await x.User.GetOrCreateDMChannelAsync();
}
else // channel
{
chan = x.MessageChannel;
}
await chan.SendConfirmAsync(_strings.GetText("level_up_global",
(x.MessageChannel as ITextChannel)?.GuildId,
"xp",
x.User.Mention, Format.Bold(x.Level.ToString())));
}
}));
}
catch (Exception ex)
{
_log.Warn(ex);
}
}
});
}
private void InternalReloadXpTemplate()
{
try
{
var settings = new JsonSerializerSettings
{
ContractResolver = new RequireObjectPropertiesContractResolver()
};
_template = JsonConvert.DeserializeObject<XpTemplate>(
File.ReadAllText("./data/xp_template.json"), settings);
}
catch (Exception ex)
{
_log.Warn(ex);
_log.Error("Xp template is invalid. Loaded default values.");
_template = new XpTemplate();
File.WriteAllText("./data/xp_template_backup.json",
JsonConvert.SerializeObject(_template, Formatting.Indented));
}
}
public void ReloadXpTemplate()
{
var sub = _cache.Redis.GetSubscriber();
sub.Publish(_creds.RedisKey() + "_reload_xp_template", "");
}
public void SetCurrencyReward(ulong guildId, int level, int amount)
{
using (var uow = _db.UnitOfWork)
{
var settings = uow.GuildConfigs.XpSettingsFor(guildId);
if (amount <= 0)
{
var toRemove = settings.CurrencyRewards.FirstOrDefault(x => x.Level == level);
if (toRemove != null)
{
uow._context.Remove(toRemove);
settings.CurrencyRewards.Remove(toRemove);
}
}
else
{
var rew = settings.CurrencyRewards.FirstOrDefault(x => x.Level == level);
if (rew != null)
rew.Amount = amount;
else
settings.CurrencyRewards.Add(new XpCurrencyReward()
{
Level = level,
Amount = amount,
});
}
uow.Complete();
}
}
public IEnumerable<XpCurrencyReward> GetCurrencyRewards(ulong id)
{
using (var uow = _db.UnitOfWork)
{
return uow.GuildConfigs.XpSettingsFor(id)
.CurrencyRewards
.ToArray();
}
}
public IEnumerable<XpRoleReward> GetRoleRewards(ulong id)
{
using (var uow = _db.UnitOfWork)
{
return uow.GuildConfigs.XpSettingsFor(id)
.RoleRewards
.ToArray();
}
}
public void SetRoleReward(ulong guildId, int level, ulong? roleId)
{
using (var uow = _db.UnitOfWork)
{
var settings = uow.GuildConfigs.XpSettingsFor(guildId);
if (roleId == null)
{
var toRemove = settings.RoleRewards.FirstOrDefault(x => x.Level == level);
if (toRemove != null)
{
uow._context.Remove(toRemove);
settings.RoleRewards.Remove(toRemove);
}
}
else
{
var rew = settings.RoleRewards.FirstOrDefault(x => x.Level == level);
if (rew != null)
rew.RoleId = roleId.Value;
else
settings.RoleRewards.Add(new XpRoleReward()
{
Level = level,
RoleId = roleId.Value,
});
}
uow.Complete();
}
}
public UserXpStats[] GetUserXps(ulong guildId, int page)
{
using (var uow = _db.UnitOfWork)
{
return uow.Xp.GetUsersFor(guildId, page);
}
}
public DiscordUser[] GetUserXps(int page)
{
using (var uow = _db.UnitOfWork)
{
return uow.DiscordUsers.GetUsersXpLeaderboardFor(page);
}
}
public async Task ChangeNotificationType(ulong userId, ulong guildId, XpNotificationType type)
{
using (var uow = _db.UnitOfWork)
{
var user = uow.Xp.GetOrCreateUser(guildId, userId);
user.NotifyOnLevelUp = type;
await uow.CompleteAsync();
}
}
public async Task ChangeNotificationType(IUser user, XpNotificationType type)
{
using (var uow = _db.UnitOfWork)
{
var du = uow.DiscordUsers.GetOrCreate(user);
du.NotifyOnLevelUp = type;
await uow.CompleteAsync();
}
}
private Task _cmd_OnMessageNoTrigger(IUserMessage arg)
{
if (!(arg.Author is SocketGuildUser user) || user.IsBot)
return Task.CompletedTask;
var _ = Task.Run(() =>
{
if (_excludedChannels.TryGetValue(user.Guild.Id, out var chans) &&
chans.Contains(arg.Channel.Id))
return;
if (_excludedServers.Contains(user.Guild.Id))
return;
if (_excludedRoles.TryGetValue(user.Guild.Id, out var roles) &&
user.Roles.Any(x => roles.Contains(x.Id)))
return;
if (!arg.Content.Contains(' ') && arg.Content.Length < 5)
return;
if (!SetUserRewarded(user.Id))
return;
_addMessageXp.Enqueue(new UserCacheItem { Guild = user.Guild, Channel = arg.Channel, User = user });
});
return Task.CompletedTask;
}
public void AddXp(ulong userId, ulong guildId, int amount)
{
using (var uow = _db.UnitOfWork)
{
var usr = uow.Xp.GetOrCreateUser(guildId, userId);
usr.AwardedXp += amount;
uow.Complete();
}
}
public bool IsServerExcluded(ulong id)
{
return _excludedServers.Contains(id);
}
public IEnumerable<ulong> GetExcludedRoles(ulong id)
{
if (_excludedRoles.TryGetValue(id, out var val))
return val.ToArray();
return Enumerable.Empty<ulong>();
}
public IEnumerable<ulong> GetExcludedChannels(ulong id)
{
if (_excludedChannels.TryGetValue(id, out var val))
return val.ToArray();
return Enumerable.Empty<ulong>();
}
private bool SetUserRewarded(ulong userId)
{
var r = _cache.Redis.GetDatabase();
var key = $"{_creds.RedisKey()}_user_xp_gain_{userId}";
return r.StringSet(key,
true,
TimeSpan.FromMinutes(_bc.BotConfig.XpMinutesTimeout),
StackExchange.Redis.When.NotExists);
}
public async Task<FullUserStats> GetUserStatsAsync(IGuildUser user)
{
DiscordUser du;
UserXpStats stats = null;
int totalXp;
int globalRank;
int guildRank;
using (var uow = _db.UnitOfWork)
{
du = uow.DiscordUsers.GetOrCreate(user);
totalXp = du.TotalXp;
globalRank = uow.DiscordUsers.GetUserGlobalRank(user.Id);
guildRank = uow.Xp.GetUserGuildRanking(user.Id, user.GuildId);
stats = uow.Xp.GetOrCreateUser(user.GuildId, user.Id);
await uow.CompleteAsync();
}
return new FullUserStats(du,
stats,
new LevelStats(totalXp),
new LevelStats(stats.Xp + stats.AwardedXp),
globalRank,
guildRank);
}
public static (int Level, int LevelXp, int LevelRequiredXp) GetLevelData(UserXpStats stats)
{
var baseXp = XpService.XP_REQUIRED_LVL_1;
var required = baseXp;
var totalXp = 0;
var lvl = 1;
while (true)
{
required = (int)(baseXp + baseXp / 4.0 * (lvl - 1));
if (required + totalXp > stats.Xp)
break;
totalXp += required;
lvl++;
}
return (lvl - 1, stats.Xp - totalXp, required);
}
public bool ToggleExcludeServer(ulong id)
{
using (var uow = _db.UnitOfWork)
{
var xpSetting = uow.GuildConfigs.XpSettingsFor(id);
if (_excludedServers.Add(id))
{
xpSetting.ServerExcluded = true;
uow.Complete();
return true;
}
_excludedServers.TryRemove(id);
xpSetting.ServerExcluded = false;
uow.Complete();
return false;
}
}
public bool ToggleExcludeRole(ulong guildId, ulong rId)
{
var roles = _excludedRoles.GetOrAdd(guildId, _ => new ConcurrentHashSet<ulong>());
using (var uow = _db.UnitOfWork)
{
var xpSetting = uow.GuildConfigs.XpSettingsFor(guildId);
var excludeObj = new ExcludedItem
{
ItemId = rId,
ItemType = ExcludedItemType.Role,
};
if (roles.Add(rId))
{
if (xpSetting.ExclusionList.Add(excludeObj))
{
uow.Complete();
}
return true;
}
else
{
roles.TryRemove(rId);
var toDelete = xpSetting.ExclusionList.FirstOrDefault(x => x.Equals(excludeObj));
if (toDelete != null)
{
uow._context.Remove(toDelete);
uow.Complete();
}
return false;
}
}
}
public bool ToggleExcludeChannel(ulong guildId, ulong chId)
{
var channels = _excludedChannels.GetOrAdd(guildId, _ => new ConcurrentHashSet<ulong>());
using (var uow = _db.UnitOfWork)
{
var xpSetting = uow.GuildConfigs.XpSettingsFor(guildId);
var excludeObj = new ExcludedItem
{
ItemId = chId,
ItemType = ExcludedItemType.Channel,
};
if (channels.Add(chId))
{
if (xpSetting.ExclusionList.Add(excludeObj))
{
uow.Complete();
}
return true;
}
else
{
channels.TryRemove(chId);
if (xpSetting.ExclusionList.Remove(excludeObj))
{
uow.Complete();
}
return false;
}
}
}
public async Task<(Stream Image, IImageFormat Format)> GenerateXpImageAsync(IGuildUser user)
{
var stats = await GetUserStatsAsync(user);
return await GenerateXpImageAsync(stats);
}
public Task<(Stream Image, IImageFormat Format)> GenerateXpImageAsync(FullUserStats stats) => Task.Run(async () =>
{
using (var img = Image.Load(_images.XpBackground, out var imageFormat))
{
if (_template.User.Name.Show)
{
var username = stats.User.ToString();
var usernameFont = _fonts.NotoSans
.CreateFont(username.Length <= 6
? _template.User.Name.FontSize
: _template.User.Name.FontSize - username.Length, FontStyle.Bold);
img.Mutate(x =>
{
x.DrawText("@" + username, usernameFont,
_template.User.Name.Color,
new PointF(_template.User.Name.Pos.X, _template.User.Name.Pos.Y));
});
}
if (_template.User.GlobalLevel.Show)
{
img.Mutate(x =>
{
x.DrawText(stats.Global.Level.ToString(),
_fonts.NotoSans.CreateFont(_template.User.GlobalLevel.FontSize, FontStyle.Bold),
_template.User.GlobalLevel.Color,
new PointF(_template.User.GlobalLevel.Pos.X, _template.User.GlobalLevel.Pos.Y)); //level
});
}
if (_template.User.GuildLevel.Show)
{
img.Mutate(x =>
{
x.DrawText(stats.Guild.Level.ToString(),
_fonts.NotoSans.CreateFont(_template.User.GuildLevel.FontSize, FontStyle.Bold),
_template.User.GuildLevel.Color,
new PointF(_template.User.GuildLevel.Pos.X, _template.User.GuildLevel.Pos.Y));
});
}
//club name
if (_template.Club.Name.Show)
{
var clubName = stats.User.Club?.ToString() ?? "-";
var clubFont = _fonts.NotoSans
.CreateFont(clubName.Length <= 8
? _template.Club.Name.FontSize
: _template.Club.Name.FontSize - (clubName.Length / 2), FontStyle.Bold);
img.Mutate(x => x.DrawText(clubName, clubFont,
_template.Club.Name.Color,
new PointF(_template.Club.Name.Pos.X - clubName.Length * 10, _template.Club.Name.Pos.Y)));
}
var pen = new Pen<Rgba32>(Rgba32.Black, 1);
var global = stats.Global;
var guild = stats.Guild;
//xp bar
if (_template.User.Xp.Bar.Show)
{
var xpPercent = (global.LevelXp / (float)global.RequiredXp);
DrawXpBar(xpPercent, _template.User.Xp.Bar.Global, img);
xpPercent = (guild.LevelXp / (float)guild.RequiredXp);
DrawXpBar(xpPercent, _template.User.Xp.Bar.Guild, img);
}
if (_template.User.Xp.Global.Show)
{
img.Mutate(x => x.DrawText($"{global.LevelXp}/{global.RequiredXp}",
_fonts.NotoSans.CreateFont(_template.User.Xp.Global.FontSize, FontStyle.Bold),
Brushes.Solid(_template.User.Xp.Global.Color),
pen,
new PointF(_template.User.Xp.Global.Pos.X, _template.User.Xp.Global.Pos.Y)));
}
if (_template.User.Xp.Guild.Show)
{
img.Mutate(x => x.DrawText($"{guild.LevelXp}/{guild.RequiredXp}",
_fonts.NotoSans.CreateFont(_template.User.Xp.Guild.FontSize, FontStyle.Bold),
Brushes.Solid(_template.User.Xp.Guild.Color),
pen,
new PointF(_template.User.Xp.Guild.Pos.X, _template.User.Xp.Guild.Pos.Y)));
}
if (stats.FullGuildStats.AwardedXp != 0 && _template.User.Xp.Awarded.Show)
{
var sign = stats.FullGuildStats.AwardedXp > 0
? "+ "
: "";
var awX = _template.User.Xp.Awarded.Pos.X - (Math.Max(0, (stats.FullGuildStats.AwardedXp.ToString().Length - 2)) * 5);
var awY = _template.User.Xp.Awarded.Pos.Y;
img.Mutate(x => x.DrawText($"({sign}{stats.FullGuildStats.AwardedXp})",
_fonts.NotoSans.CreateFont(_template.User.Xp.Awarded.FontSize, FontStyle.Bold),
Brushes.Solid(_template.User.Xp.Awarded.Color),
pen,
new PointF(awX, awY)));
}
//ranking
if (_template.User.GlobalRank.Show)
{
img.Mutate(x => x.DrawText(stats.GlobalRanking.ToString(),
_fonts.RankFontFamily.CreateFont(_template.User.GlobalRank.FontSize, FontStyle.Bold),
_template.User.GlobalRank.Color,
new PointF(_template.User.GlobalRank.Pos.X, _template.User.GlobalRank.Pos.Y)));
}
if (_template.User.GuildRank.Show)
{
img.Mutate(x => x.DrawText(stats.GuildRanking.ToString(),
_fonts.RankFontFamily.CreateFont(_template.User.GuildRank.FontSize, FontStyle.Bold),
_template.User.GuildRank.Color,
new PointF(_template.User.GuildRank.Pos.X, _template.User.GuildRank.Pos.Y)));
}
//time on this level
string GetTimeSpent(DateTime time, string format)
{
var offset = DateTime.UtcNow - time;
return string.Format(format, offset.Days, offset.Hours, offset.Minutes);
}
if (_template.User.TimeOnLevel.Global.Show)
{
img.Mutate(x => x.DrawText(GetTimeSpent(stats.User.LastLevelUp, _template.User.TimeOnLevel.Format),
_fonts.NotoSans.CreateFont(_template.User.TimeOnLevel.Global.FontSize, FontStyle.Bold),
_template.User.TimeOnLevel.Global.Color,
new PointF(_template.User.TimeOnLevel.Global.Pos.X, _template.User.TimeOnLevel.Global.Pos.Y)));
}
if (_template.User.TimeOnLevel.Guild.Show)
{
img.Mutate(x => x.DrawText(GetTimeSpent(stats.FullGuildStats.LastLevelUp, _template.User.TimeOnLevel.Format),
_fonts.NotoSans.CreateFont(_template.User.TimeOnLevel.Guild.FontSize, FontStyle.Bold),
_template.User.TimeOnLevel.Guild.Color,
new PointF(_template.User.TimeOnLevel.Guild.Pos.X, _template.User.TimeOnLevel.Guild.Pos.Y)));
}
//avatar
if (stats.User.AvatarId != null && _template.User.Icon.Show)
{
try
{
var avatarUrl = stats.User.RealAvatarUrl(128);
var (succ, data) = await _cache.TryGetImageDataAsync(avatarUrl);
if (!succ)
{
using (var http = _httpFactory.CreateClient())
{
var avatarData = await http.GetByteArrayAsync(avatarUrl);
using (var tempDraw = Image.Load(avatarData))
{
tempDraw.Mutate(x => x.Resize(_template.User.Icon.Size.X, _template.User.Icon.Size.Y));
tempDraw.ApplyRoundedCorners(Math.Max(_template.User.Icon.Size.X, _template.User.Icon.Size.Y) / 2);
using (var stream = tempDraw.ToStream())
{
data = stream.ToArray();
}
}
}
await _cache.SetImageDataAsync(avatarUrl, data);
}
using (var toDraw = Image.Load(data))
{
if (toDraw.Size() != new Size(_template.User.Icon.Size.X, _template.User.Icon.Size.Y))
{
toDraw.Mutate(x => x.Resize(_template.User.Icon.Size.X, _template.User.Icon.Size.Y));
}
img.Mutate(x => x.DrawImage(GraphicsOptions.Default,
toDraw,
new Point(_template.User.Icon.Pos.X, _template.User.Icon.Pos.Y)));
}
}
catch (Exception ex)
{
_log.Warn(ex);
}
}
//club image
if (_template.Club.Icon.Show)
{
await DrawClubImage(img, stats);
}
img.Mutate(x => x.Resize(_template.OutputSize.X, _template.OutputSize.Y));
return ((Stream)img.ToStream(imageFormat), imageFormat);
}
});
void DrawXpBar(float percent, XpBar info, Image<Rgba32> img)
{
var x1 = info.PointA.X;
var y1 = info.PointA.Y;
var x2 = info.PointB.X;
var y2 = info.PointB.Y;
var length = info.Length * percent;
float x3 = 0, x4 = 0, y3 = 0, y4 = 0;
if (info.Direction == XpTemplateDirection.Down)
{
x3 = x1;
x4 = x2;
y3 = y1 + length;
y4 = y2 + length;
}
else if (info.Direction == XpTemplateDirection.Up)
{
x3 = x1;
x4 = x2;
y3 = y1 - length;
y4 = y2 - length;
}
else if (info.Direction == XpTemplateDirection.Left)
{
x3 = x1 - length;
x4 = x2 - length;
y3 = y1;
y4 = y2;
}
else
{
x3 = x1 + length;
x4 = x2 + length;
y3 = y1;
y4 = y2;
}
img.Mutate(x => x.FillPolygon(info.Color,
new[] {
new PointF(x1, y1),
new PointF(x3, y3),
new PointF(x4, y4),
new PointF(x2, y2),
}));
}
private async Task DrawClubImage(Image<Rgba32> img, FullUserStats stats)
{
if (!string.IsNullOrWhiteSpace(stats.User.Club?.ImageUrl))
{
try
{
var imgUrl = new Uri(stats.User.Club.ImageUrl);
var (succ, data) = await _cache.TryGetImageDataAsync(imgUrl);
if (!succ)
{
using (var http = _httpFactory.CreateClient())
using (var temp = await http.GetAsync(imgUrl, HttpCompletionOption.ResponseHeadersRead))
{
if (!temp.IsImage() || temp.GetImageSize() > 11)
return;
var imgData = await temp.Content.ReadAsByteArrayAsync();
using (var tempDraw = Image.Load(imgData))
{
tempDraw.Mutate(x => x.Resize(_template.Club.Icon.Size.X, _template.Club.Icon.Size.Y));
tempDraw.ApplyRoundedCorners(Math.Max(_template.Club.Icon.Size.X, _template.Club.Icon.Size.Y) / 2.0f);
using (var tds = tempDraw.ToStream())
{
data = tds.ToArray();
}
}
}
await _cache.SetImageDataAsync(imgUrl, data);
}
using (var toDraw = Image.Load(data))
{
if (toDraw.Size() != new Size(_template.Club.Icon.Size.X, _template.Club.Icon.Size.Y))
{
toDraw.Mutate(x => x.Resize(_template.Club.Icon.Size.X, _template.Club.Icon.Size.Y));
}
img.Mutate(x => x.DrawImage(GraphicsOptions.Default,
toDraw,
new Point(_template.Club.Icon.Pos.X, _template.Club.Icon.Pos.Y)));
}
}
catch (Exception ex)
{
_log.Warn(ex);
}
}
}
public Task Unload()
{
_cmd.OnMessageNoTrigger -= _cmd_OnMessageNoTrigger;
return Task.CompletedTask;
}
public void XpReset(ulong guildId, ulong userId)
{
using (var uow = _db.UnitOfWork)
{
uow.Xp.ResetGuildUserXp(userId, guildId);
uow.Complete();
}
}
public void XpReset(ulong guildId)
{
using (var uow = _db.UnitOfWork)
{
uow.Xp.ResetGuildXp(guildId);
uow.Complete();
}
}
}
}
| |
//! \file ImageFC.cs
//! \date 2018 Nov 17
//! \brief Mink compressed bitmap format.
//
// Copyright (C) 2018-2019 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.ComponentModel.Composition;
using System.IO;
using System.Windows.Media;
using GameRes.Utility;
namespace GameRes.Formats.Mink
{
internal class FcMetaData : ImageMetaData
{
public byte Flag;
}
[Export(typeof(ImageFormat))]
public class FcFormat : ImageFormat
{
public override string Tag { get { return "BMP/FC"; } }
public override string Description { get { return "Mink compressed bitmap format"; } }
public override uint Signature { get { return 0; } }
public FcFormat ()
{
Signatures = new uint[] { 0x01184346, 0x00184346, 0x00204346, 0 };
}
public override ImageMetaData ReadMetaData (IBinaryStream file)
{
var header = file.ReadHeader (8);
if (!header.AsciiEqual ("FC"))
return null;
int bpp = header[2];
if (bpp != 24 && bpp != 32)
return null;
byte flag = header[3];
if (flag != 0 && flag != 1)
return null;
return new FcMetaData {
Width = header.ToUInt16 (4),
Height = header.ToUInt16 (6),
BPP = bpp,
Flag = flag,
};
}
public override ImageData Read (IBinaryStream file, ImageMetaData info)
{
var reader = new FcReader (file, (FcMetaData)info);
return reader.Unpack();
}
public override void Write (Stream file, ImageData image)
{
throw new System.NotImplementedException ("FcFormat.Write not implemented");
}
}
internal class FcReader
{
IBinaryStream m_input;
FcMetaData m_info;
public FcReader (IBinaryStream input, FcMetaData info)
{
m_input = input;
m_info = info;
}
public ImageData Unpack ()
{
m_input.Position = 8;
var output = new uint[m_info.iWidth * m_info.iHeight];
UnpackRgb (output);
if (32 == m_info.BPP)
UnpackAlpha (output);
if (m_info.Flag != 0)
RestoreRgb (output);
PixelFormat format = 32 == m_info.BPP ? PixelFormats.Bgra32 : PixelFormats.Bgr32;
return ImageData.CreateFlipped (m_info, format, null, output, m_info.iWidth * 4);
}
void UnpackRgb (uint[] output)
{
int dst = 0;
m_bits = 0x80000000;
uint ref_pixel = m_info.Flag != 0 ? 0x808080u : 0u;
uint pixel = ref_pixel;
while (dst < output.Length)
{
if (GetNextBit() == 0)
{
if (GetNextBit() != 0)
{
int offset = m_info.iWidth + GetNextBit();
pixel = output[dst - offset + 1];
}
else
{
pixel = output[dst - 1];
}
uint v = GetVarInt();
v = (v >> 1) ^ (uint)-(v & 1);
pixel = Binary.RotR (pixel, 8) + (v << 24);
v = GetVarInt();
v = (v >> 1) ^ (uint)-(v & 1);
pixel = Binary.RotR (pixel, 8) + (v << 24);
v = GetVarInt();
v = (v >> 1) ^ (uint)-(v & 1);
pixel = Binary.RotR (pixel, 8) + (v << 24);
pixel >>= 8;
output[dst++] = pixel;
}
else if (GetNextBit() == 0)
{
if (GetNextBit() == 0)
{
pixel = output[dst - m_info.iWidth - 1];
uint v = GetVarInt();
v = (v >> 1) ^ (uint)-(v & 1);
pixel = Binary.RotR (pixel, 8) + (v << 24);
v = GetVarInt();
v = (v >> 1) ^ (uint)-(v & 1);
pixel = Binary.RotR (pixel, 8) + (v << 24);
v = GetVarInt();
v = (v >> 1) ^ (uint)-(v & 1);
pixel = Binary.RotR (pixel, 8) + (v << 24);
pixel >>= 8;
output[dst++] = pixel;
}
else
{
pixel = ref_pixel;
uint v = GetVarInt();
v = (v >> 1) ^ (uint)-(v & 1);
pixel ^= v & 0xFF;
v = GetVarInt();
v = (v >> 1) ^ (uint)-(v & 1);
pixel ^= (v & 0xFF) << 8;
v = GetVarInt();
v = (v >> 1) ^ (uint)-(v & 1);
pixel ^= (v & 0xFF) << 16;
output[dst++] = pixel;
}
}
else if (GetNextBit() != 0)
{
int offset = m_info.iWidth;
if (GetNextBit() != 0)
{
offset += GetNextBit();
}
else
{
offset -= 1;
}
pixel = output[dst - offset];
output[dst++] = pixel;
}
else if (GetNextBit() == 0)
{
pixel = GetBits (24);
output[dst++] = pixel;
}
else
{
int count = Math.Min ((int)GetVarInt(), output.Length - dst);
while (count --> 0)
{
output[dst++] = pixel;
}
}
}
}
void UnpackAlpha (uint[] output)
{
int dst = 0;
while (dst < output.Length)
{
uint val = GetBits (8) << 24;
uint count = GetVarInt() + 1;
while (count != 0)
{
output[dst++] |= val;
--count;
}
}
}
void RestoreRgb (uint[] output)
{
int stride = m_info.iWidth;
int dst = stride;
while (dst < output.Length)
{
uint prev = output[dst-stride];
uint pixel = output[dst];
output[dst] = ((pixel + prev - 0x80) & 0xFF)
| (((pixel >> 8) + (prev >> 8) - 0x80) & 0xFF) << 8
| (((pixel >> 16) + (prev >> 16) - 0x80) & 0xFF) << 16
| pixel & 0xFF000000;
++dst;
}
}
uint GetBits (int count)
{
uint val = m_bits >> (32 - count);
m_bits <<= count;
if (0 == m_bits)
{
m_bits = ReadUInt32();
int shift = BitScanForward (val);
uint ebx = m_bits ^ 0x80000000;
m_bits = (m_bits << 1 | 1) << shift;
val ^= ebx >> (shift ^ 0x1F);
}
return val;
}
uint m_bits;
int GetNextBit ()
{
uint bit = m_bits >> 31;
m_bits <<= 1;
if (0 == m_bits)
{
m_bits = ReadUInt32();
bit = m_bits >> 31;
m_bits = m_bits << 1 | 1;
}
return (int)bit;
}
uint GetVarInt ()
{
int count = 0;
do
{
++count;
}
while (GetNextBit() != 0);
uint num = 1;
while (count --> 0)
{
num = num << 1 | (uint)GetNextBit();
}
return num - 2;
}
byte[] m_dword_buffer = new byte[4];
uint ReadUInt32 ()
{
int last = m_input.Read (m_dword_buffer, 0, 4);
while (last < m_dword_buffer.Length)
m_dword_buffer[last++] = 0;
return BigEndian.ToUInt32 (m_dword_buffer, 0);
}
static int BitScanForward (uint val)
{
int count = 0;
for (uint mask = 1; mask != 0; mask <<= 1)
{
if ((val & mask) != 0)
break;
++count;
}
return count;
}
}
}
| |
// Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
using gax = Google.Api.Gax;
using gaxgrpc = Google.Api.Gax.Grpc;
using gaxgrpccore = Google.Api.Gax.Grpc.GrpcCore;
using proto = Google.Protobuf;
using grpccore = Grpc.Core;
using grpcinter = Grpc.Core.Interceptors;
using sys = System;
using scg = System.Collections.Generic;
using sco = System.Collections.ObjectModel;
using st = System.Threading;
using stt = System.Threading.Tasks;
namespace Google.Cloud.ServiceControl.V1
{
/// <summary>Settings for <see cref="QuotaControllerClient"/> instances.</summary>
public sealed partial class QuotaControllerSettings : gaxgrpc::ServiceSettingsBase
{
/// <summary>Get a new instance of the default <see cref="QuotaControllerSettings"/>.</summary>
/// <returns>A new instance of the default <see cref="QuotaControllerSettings"/>.</returns>
public static QuotaControllerSettings GetDefault() => new QuotaControllerSettings();
/// <summary>Constructs a new <see cref="QuotaControllerSettings"/> object with default settings.</summary>
public QuotaControllerSettings()
{
}
private QuotaControllerSettings(QuotaControllerSettings existing) : base(existing)
{
gax::GaxPreconditions.CheckNotNull(existing, nameof(existing));
AllocateQuotaSettings = existing.AllocateQuotaSettings;
OnCopy(existing);
}
partial void OnCopy(QuotaControllerSettings existing);
/// <summary>
/// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to
/// <c>QuotaControllerClient.AllocateQuota</c> and <c>QuotaControllerClient.AllocateQuotaAsync</c>.
/// </summary>
/// <remarks>
/// <list type="bullet">
/// <item><description>This call will not be retried.</description></item>
/// <item><description>No timeout is applied.</description></item>
/// </list>
/// </remarks>
public gaxgrpc::CallSettings AllocateQuotaSettings { get; set; } = gaxgrpc::CallSettings.FromExpiration(gax::Expiration.None);
/// <summary>Creates a deep clone of this object, with all the same property values.</summary>
/// <returns>A deep clone of this <see cref="QuotaControllerSettings"/> object.</returns>
public QuotaControllerSettings Clone() => new QuotaControllerSettings(this);
}
/// <summary>
/// Builder class for <see cref="QuotaControllerClient"/> to provide simple configuration of credentials, endpoint
/// etc.
/// </summary>
public sealed partial class QuotaControllerClientBuilder : gaxgrpc::ClientBuilderBase<QuotaControllerClient>
{
/// <summary>The settings to use for RPCs, or <c>null</c> for the default settings.</summary>
public QuotaControllerSettings Settings { get; set; }
/// <summary>Creates a new builder with default settings.</summary>
public QuotaControllerClientBuilder()
{
UseJwtAccessWithScopes = QuotaControllerClient.UseJwtAccessWithScopes;
}
partial void InterceptBuild(ref QuotaControllerClient client);
partial void InterceptBuildAsync(st::CancellationToken cancellationToken, ref stt::Task<QuotaControllerClient> task);
/// <summary>Builds the resulting client.</summary>
public override QuotaControllerClient Build()
{
QuotaControllerClient client = null;
InterceptBuild(ref client);
return client ?? BuildImpl();
}
/// <summary>Builds the resulting client asynchronously.</summary>
public override stt::Task<QuotaControllerClient> BuildAsync(st::CancellationToken cancellationToken = default)
{
stt::Task<QuotaControllerClient> task = null;
InterceptBuildAsync(cancellationToken, ref task);
return task ?? BuildAsyncImpl(cancellationToken);
}
private QuotaControllerClient BuildImpl()
{
Validate();
grpccore::CallInvoker callInvoker = CreateCallInvoker();
return QuotaControllerClient.Create(callInvoker, Settings);
}
private async stt::Task<QuotaControllerClient> BuildAsyncImpl(st::CancellationToken cancellationToken)
{
Validate();
grpccore::CallInvoker callInvoker = await CreateCallInvokerAsync(cancellationToken).ConfigureAwait(false);
return QuotaControllerClient.Create(callInvoker, Settings);
}
/// <summary>Returns the endpoint for this builder type, used if no endpoint is otherwise specified.</summary>
protected override string GetDefaultEndpoint() => QuotaControllerClient.DefaultEndpoint;
/// <summary>
/// Returns the default scopes for this builder type, used if no scopes are otherwise specified.
/// </summary>
protected override scg::IReadOnlyList<string> GetDefaultScopes() => QuotaControllerClient.DefaultScopes;
/// <summary>Returns the channel pool to use when no other options are specified.</summary>
protected override gaxgrpc::ChannelPool GetChannelPool() => QuotaControllerClient.ChannelPool;
/// <summary>Returns the default <see cref="gaxgrpc::GrpcAdapter"/>to use if not otherwise specified.</summary>
protected override gaxgrpc::GrpcAdapter DefaultGrpcAdapter => gaxgrpccore::GrpcCoreAdapter.Instance;
}
/// <summary>QuotaController client wrapper, for convenient use.</summary>
/// <remarks>
/// [Google Quota Control API](/service-control/overview)
///
/// Allows clients to allocate and release quota against a [managed
/// service](https://cloud.google.com/service-management/reference/rpc/google.api/servicemanagement.v1#google.api.servicemanagement.v1.ManagedService).
/// </remarks>
public abstract partial class QuotaControllerClient
{
/// <summary>
/// The default endpoint for the QuotaController service, which is a host of "servicecontrol.googleapis.com" and
/// a port of 443.
/// </summary>
public static string DefaultEndpoint { get; } = "servicecontrol.googleapis.com:443";
/// <summary>The default QuotaController scopes.</summary>
/// <remarks>
/// The default QuotaController scopes are:
/// <list type="bullet">
/// <item><description>https://www.googleapis.com/auth/cloud-platform</description></item>
/// <item><description>https://www.googleapis.com/auth/servicecontrol</description></item>
/// </list>
/// </remarks>
public static scg::IReadOnlyList<string> DefaultScopes { get; } = new sco::ReadOnlyCollection<string>(new string[]
{
"https://www.googleapis.com/auth/cloud-platform",
"https://www.googleapis.com/auth/servicecontrol",
});
internal static gaxgrpc::ChannelPool ChannelPool { get; } = new gaxgrpc::ChannelPool(DefaultScopes, UseJwtAccessWithScopes);
internal static bool UseJwtAccessWithScopes
{
get
{
bool useJwtAccessWithScopes = true;
MaybeUseJwtAccessWithScopes(ref useJwtAccessWithScopes);
return useJwtAccessWithScopes;
}
}
static partial void MaybeUseJwtAccessWithScopes(ref bool useJwtAccessWithScopes);
/// <summary>
/// Asynchronously creates a <see cref="QuotaControllerClient"/> using the default credentials, endpoint and
/// settings. To specify custom credentials or other settings, use <see cref="QuotaControllerClientBuilder"/>.
/// </summary>
/// <param name="cancellationToken">
/// The <see cref="st::CancellationToken"/> to use while creating the client.
/// </param>
/// <returns>The task representing the created <see cref="QuotaControllerClient"/>.</returns>
public static stt::Task<QuotaControllerClient> CreateAsync(st::CancellationToken cancellationToken = default) =>
new QuotaControllerClientBuilder().BuildAsync(cancellationToken);
/// <summary>
/// Synchronously creates a <see cref="QuotaControllerClient"/> using the default credentials, endpoint and
/// settings. To specify custom credentials or other settings, use <see cref="QuotaControllerClientBuilder"/>.
/// </summary>
/// <returns>The created <see cref="QuotaControllerClient"/>.</returns>
public static QuotaControllerClient Create() => new QuotaControllerClientBuilder().Build();
/// <summary>
/// Creates a <see cref="QuotaControllerClient"/> which uses the specified call invoker for remote operations.
/// </summary>
/// <param name="callInvoker">
/// The <see cref="grpccore::CallInvoker"/> for remote operations. Must not be null.
/// </param>
/// <param name="settings">Optional <see cref="QuotaControllerSettings"/>.</param>
/// <returns>The created <see cref="QuotaControllerClient"/>.</returns>
internal static QuotaControllerClient Create(grpccore::CallInvoker callInvoker, QuotaControllerSettings settings = null)
{
gax::GaxPreconditions.CheckNotNull(callInvoker, nameof(callInvoker));
grpcinter::Interceptor interceptor = settings?.Interceptor;
if (interceptor != null)
{
callInvoker = grpcinter::CallInvokerExtensions.Intercept(callInvoker, interceptor);
}
QuotaController.QuotaControllerClient grpcClient = new QuotaController.QuotaControllerClient(callInvoker);
return new QuotaControllerClientImpl(grpcClient, settings);
}
/// <summary>
/// Shuts down any channels automatically created by <see cref="Create()"/> and
/// <see cref="CreateAsync(st::CancellationToken)"/>. Channels which weren't automatically created are not
/// affected.
/// </summary>
/// <remarks>
/// After calling this method, further calls to <see cref="Create()"/> and
/// <see cref="CreateAsync(st::CancellationToken)"/> will create new channels, which could in turn be shut down
/// by another call to this method.
/// </remarks>
/// <returns>A task representing the asynchronous shutdown operation.</returns>
public static stt::Task ShutdownDefaultChannelsAsync() => ChannelPool.ShutdownChannelsAsync();
/// <summary>The underlying gRPC QuotaController client</summary>
public virtual QuotaController.QuotaControllerClient GrpcClient => throw new sys::NotImplementedException();
/// <summary>
/// Attempts to allocate quota for the specified consumer. It should be called
/// before the operation is executed.
///
/// This method requires the `servicemanagement.services.quota`
/// permission on the specified service. For more information, see
/// [Cloud IAM](https://cloud.google.com/iam).
///
/// **NOTE:** The client **must** fail-open on server errors `INTERNAL`,
/// `UNKNOWN`, `DEADLINE_EXCEEDED`, and `UNAVAILABLE`. To ensure system
/// reliability, the server may inject these errors to prohibit any hard
/// dependency on the quota functionality.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual AllocateQuotaResponse AllocateQuota(AllocateQuotaRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Attempts to allocate quota for the specified consumer. It should be called
/// before the operation is executed.
///
/// This method requires the `servicemanagement.services.quota`
/// permission on the specified service. For more information, see
/// [Cloud IAM](https://cloud.google.com/iam).
///
/// **NOTE:** The client **must** fail-open on server errors `INTERNAL`,
/// `UNKNOWN`, `DEADLINE_EXCEEDED`, and `UNAVAILABLE`. To ensure system
/// reliability, the server may inject these errors to prohibit any hard
/// dependency on the quota functionality.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<AllocateQuotaResponse> AllocateQuotaAsync(AllocateQuotaRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Attempts to allocate quota for the specified consumer. It should be called
/// before the operation is executed.
///
/// This method requires the `servicemanagement.services.quota`
/// permission on the specified service. For more information, see
/// [Cloud IAM](https://cloud.google.com/iam).
///
/// **NOTE:** The client **must** fail-open on server errors `INTERNAL`,
/// `UNKNOWN`, `DEADLINE_EXCEEDED`, and `UNAVAILABLE`. To ensure system
/// reliability, the server may inject these errors to prohibit any hard
/// dependency on the quota functionality.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<AllocateQuotaResponse> AllocateQuotaAsync(AllocateQuotaRequest request, st::CancellationToken cancellationToken) =>
AllocateQuotaAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
}
/// <summary>QuotaController client wrapper implementation, for convenient use.</summary>
/// <remarks>
/// [Google Quota Control API](/service-control/overview)
///
/// Allows clients to allocate and release quota against a [managed
/// service](https://cloud.google.com/service-management/reference/rpc/google.api/servicemanagement.v1#google.api.servicemanagement.v1.ManagedService).
/// </remarks>
public sealed partial class QuotaControllerClientImpl : QuotaControllerClient
{
private readonly gaxgrpc::ApiCall<AllocateQuotaRequest, AllocateQuotaResponse> _callAllocateQuota;
/// <summary>
/// Constructs a client wrapper for the QuotaController service, with the specified gRPC client and settings.
/// </summary>
/// <param name="grpcClient">The underlying gRPC client.</param>
/// <param name="settings">The base <see cref="QuotaControllerSettings"/> used within this client.</param>
public QuotaControllerClientImpl(QuotaController.QuotaControllerClient grpcClient, QuotaControllerSettings settings)
{
GrpcClient = grpcClient;
QuotaControllerSettings effectiveSettings = settings ?? QuotaControllerSettings.GetDefault();
gaxgrpc::ClientHelper clientHelper = new gaxgrpc::ClientHelper(effectiveSettings);
_callAllocateQuota = clientHelper.BuildApiCall<AllocateQuotaRequest, AllocateQuotaResponse>(grpcClient.AllocateQuotaAsync, grpcClient.AllocateQuota, effectiveSettings.AllocateQuotaSettings).WithGoogleRequestParam("service_name", request => request.ServiceName);
Modify_ApiCall(ref _callAllocateQuota);
Modify_AllocateQuotaApiCall(ref _callAllocateQuota);
OnConstruction(grpcClient, effectiveSettings, clientHelper);
}
partial void Modify_ApiCall<TRequest, TResponse>(ref gaxgrpc::ApiCall<TRequest, TResponse> call) where TRequest : class, proto::IMessage<TRequest> where TResponse : class, proto::IMessage<TResponse>;
partial void Modify_AllocateQuotaApiCall(ref gaxgrpc::ApiCall<AllocateQuotaRequest, AllocateQuotaResponse> call);
partial void OnConstruction(QuotaController.QuotaControllerClient grpcClient, QuotaControllerSettings effectiveSettings, gaxgrpc::ClientHelper clientHelper);
/// <summary>The underlying gRPC QuotaController client</summary>
public override QuotaController.QuotaControllerClient GrpcClient { get; }
partial void Modify_AllocateQuotaRequest(ref AllocateQuotaRequest request, ref gaxgrpc::CallSettings settings);
/// <summary>
/// Attempts to allocate quota for the specified consumer. It should be called
/// before the operation is executed.
///
/// This method requires the `servicemanagement.services.quota`
/// permission on the specified service. For more information, see
/// [Cloud IAM](https://cloud.google.com/iam).
///
/// **NOTE:** The client **must** fail-open on server errors `INTERNAL`,
/// `UNKNOWN`, `DEADLINE_EXCEEDED`, and `UNAVAILABLE`. To ensure system
/// reliability, the server may inject these errors to prohibit any hard
/// dependency on the quota functionality.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public override AllocateQuotaResponse AllocateQuota(AllocateQuotaRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_AllocateQuotaRequest(ref request, ref callSettings);
return _callAllocateQuota.Sync(request, callSettings);
}
/// <summary>
/// Attempts to allocate quota for the specified consumer. It should be called
/// before the operation is executed.
///
/// This method requires the `servicemanagement.services.quota`
/// permission on the specified service. For more information, see
/// [Cloud IAM](https://cloud.google.com/iam).
///
/// **NOTE:** The client **must** fail-open on server errors `INTERNAL`,
/// `UNKNOWN`, `DEADLINE_EXCEEDED`, and `UNAVAILABLE`. To ensure system
/// reliability, the server may inject these errors to prohibit any hard
/// dependency on the quota functionality.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public override stt::Task<AllocateQuotaResponse> AllocateQuotaAsync(AllocateQuotaRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_AllocateQuotaRequest(ref request, ref callSettings);
return _callAllocateQuota.Async(request, callSettings);
}
}
}
| |
// 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 Xunit;
namespace System.Linq.Parallel.Tests
{
public static class ToDictionaryTests
{
[Theory]
[InlineData(0)]
[InlineData(1)]
[InlineData(2)]
[InlineData(16)]
public static void ToDictionary(int count)
{
IntegerRangeSet seen = new IntegerRangeSet(0, count);
Assert.All(UnorderedSources.Default(count).ToDictionary(x => x * 2),
p => { seen.Add(p.Key / 2); Assert.Equal(p.Key, p.Value * 2); });
seen.AssertComplete();
}
[Fact]
[OuterLoop]
public static void ToDictionary_Longrunning()
{
ToDictionary(Sources.OuterLoopCount);
}
[Theory]
[InlineData(0)]
[InlineData(1)]
[InlineData(2)]
[InlineData(16)]
public static void ToDictionary_ElementSelector(int count)
{
IntegerRangeSet seen = new IntegerRangeSet(0, count);
Assert.All(UnorderedSources.Default(count).ToDictionary(x => x, y => y * 2),
p => { seen.Add(p.Key); Assert.Equal(p.Key * 2, p.Value); });
seen.AssertComplete();
}
[Fact]
[OuterLoop]
public static void ToDictionary_ElementSelector_Longrunning()
{
ToDictionary_ElementSelector(Sources.OuterLoopCount);
}
[Theory]
[InlineData(0)]
[InlineData(1)]
[InlineData(2)]
[InlineData(16)]
public static void ToDictionary_CustomComparator(int count)
{
IntegerRangeSet seen = new IntegerRangeSet(0, count);
Assert.All(UnorderedSources.Default(count).ToDictionary(x => x * 2, new ModularCongruenceComparer(count * 2)),
p => { seen.Add(p.Key / 2); Assert.Equal(p.Key, p.Value * 2); });
seen.AssertComplete();
}
[Fact]
[OuterLoop]
public static void ToDictionary_CustomComparator_Longrunning()
{
ToDictionary_CustomComparator(Sources.OuterLoopCount);
}
[Theory]
[InlineData(0)]
[InlineData(1)]
[InlineData(2)]
[InlineData(16)]
public static void ToDictionary_ElementSelector_CustomComparator(int count)
{
IntegerRangeSet seen = new IntegerRangeSet(0, count);
Assert.All(UnorderedSources.Default(count).ToDictionary(x => x, y => y * 2, new ModularCongruenceComparer(count)),
p => { seen.Add(p.Key); Assert.Equal(p.Key * 2, p.Value); });
seen.AssertComplete();
}
[Fact]
[OuterLoop]
public static void ToDictionary_ElementSelector_CustomComparator_Longrunning()
{
ToDictionary_ElementSelector_CustomComparator(Sources.OuterLoopCount);
}
[Theory]
[InlineData(0)]
[InlineData(1)]
[InlineData(2)]
[InlineData(16)]
public static void ToDictionary_UniqueKeys_CustomComparator(int count)
{
if (count > 2)
{
ArgumentException e = AssertThrows.Wrapped<ArgumentException>(() => UnorderedSources.Default(count).ToDictionary(x => x, new ModularCongruenceComparer(2)));
}
else if (count == 1 || count == 2)
{
IntegerRangeSet seen = new IntegerRangeSet(0, count);
foreach (KeyValuePair<int, int> entry in UnorderedSources.Default(count).ToDictionary(x => x, new ModularCongruenceComparer(2)))
{
seen.Add(entry.Key);
Assert.Equal(entry.Key, entry.Value);
}
seen.AssertComplete();
}
else
{
Assert.Empty(UnorderedSources.Default(count).ToDictionary(x => x, new ModularCongruenceComparer(2)));
}
}
[Fact]
[OuterLoop]
public static void ToDictionary_UniqueKeys_CustomComparator_Longrunning()
{
ToDictionary_UniqueKeys_CustomComparator(Sources.OuterLoopCount);
}
[Theory]
[InlineData(0)]
[InlineData(1)]
[InlineData(2)]
[InlineData(16)]
public static void ToDictionary_ElementSelector_UniqueKeys_CustomComparator(int count)
{
if (count > 2)
{
AssertThrows.Wrapped<ArgumentException>(() => UnorderedSources.Default(count).ToDictionary(x => x, y => y, new ModularCongruenceComparer(2)));
}
else if (count == 1 || count == 2)
{
IntegerRangeSet seen = new IntegerRangeSet(0, count);
foreach (KeyValuePair<int, int> entry in UnorderedSources.Default(count).ToDictionary(x => x, y => y, new ModularCongruenceComparer(2)))
{
seen.Add(entry.Key);
Assert.Equal(entry.Key, entry.Value);
}
seen.AssertComplete();
}
else
{
Assert.Empty(UnorderedSources.Default(count).ToDictionary(x => x, y => y, new ModularCongruenceComparer(2)));
}
}
[Fact]
[OuterLoop]
public static void ToDictionary_ElementSelector_UniqueKeys_CustomComparator_Longrunning()
{
ToDictionary_ElementSelector_UniqueKeys_CustomComparator(Sources.OuterLoopCount);
}
[Fact]
public static void ToDictionary_DuplicateKeys()
{
AssertThrows.Wrapped<ArgumentException>(() => ParallelEnumerable.Repeat(0, 2).ToDictionary(x => x));
}
[Fact]
public static void ToDictionary_DuplicateKeys_ElementSelector()
{
AssertThrows.Wrapped<ArgumentException>(() => ParallelEnumerable.Repeat(0, 2).ToDictionary(x => x, y => y));
}
[Fact]
public static void ToDictionary_DuplicateKeys_CustomComparator()
{
AssertThrows.Wrapped<ArgumentException>(() => ParallelEnumerable.Repeat(0, 2).ToDictionary(x => x, new ModularCongruenceComparer(2)));
}
[Fact]
public static void ToDictionary_DuplicateKeys_ElementSelector_CustomComparator()
{
AssertThrows.Wrapped<ArgumentException>(() => ParallelEnumerable.Repeat(0, 2).ToDictionary(x => x, y => y, new ModularCongruenceComparer(2)));
}
[Fact]
public static void ToDictionary_OperationCanceledException()
{
AssertThrows.EventuallyCanceled((source, canceler) => source.ToDictionary(x => x, new CancelingEqualityComparer<int>(canceler)));
AssertThrows.EventuallyCanceled((source, canceler) => source.ToDictionary(x => x, y => y, new CancelingEqualityComparer<int>(canceler)));
}
[Fact]
public static void ToDictionary_AggregateException_Wraps_OperationCanceledException()
{
AssertThrows.OtherTokenCanceled((source, canceler) => source.ToDictionary(x => x, new CancelingEqualityComparer<int>(canceler)));
AssertThrows.OtherTokenCanceled((source, canceler) => source.ToDictionary(x => x, y => y, new CancelingEqualityComparer<int>(canceler)));
AssertThrows.SameTokenNotCanceled((source, canceler) => source.ToDictionary(x => x, new CancelingEqualityComparer<int>(canceler)));
AssertThrows.SameTokenNotCanceled((source, canceler) => source.ToDictionary(x => x, y => y, new CancelingEqualityComparer<int>(canceler)));
}
[Fact]
public static void ToDictionary_OperationCanceledException_PreCanceled()
{
AssertThrows.AlreadyCanceled(source => source.ToDictionary(x => x));
AssertThrows.AlreadyCanceled(source => source.ToDictionary(x => x, EqualityComparer<int>.Default));
AssertThrows.AlreadyCanceled(source => source.ToDictionary(x => x, y => y));
AssertThrows.AlreadyCanceled(source => source.ToDictionary(x => x, y => y, EqualityComparer<int>.Default));
}
[Theory]
[MemberData(nameof(UnorderedSources.Ranges), new[] { 1 }, MemberType = typeof(UnorderedSources))]
public static void ToDictionary_AggregateException(Labeled<ParallelQuery<int>> labeled, int count)
{
_ = count;
AssertThrows.Wrapped<DeliberateTestException>(() => labeled.Item.ToDictionary((Func<int, int>)(x => { throw new DeliberateTestException(); })));
AssertThrows.Wrapped<DeliberateTestException>(() => labeled.Item.ToDictionary((Func<int, int>)(x => { throw new DeliberateTestException(); }), y => y));
AssertThrows.Wrapped<DeliberateTestException>(() => labeled.Item.ToDictionary(x => x, (Func<int, int>)(y => { throw new DeliberateTestException(); })));
AssertThrows.Wrapped<DeliberateTestException>(() => labeled.Item.ToDictionary((Func<int, int>)(x => { throw new DeliberateTestException(); }), EqualityComparer<int>.Default));
AssertThrows.Wrapped<DeliberateTestException>(() => labeled.Item.ToDictionary((Func<int, int>)(x => { throw new DeliberateTestException(); }), y => y, EqualityComparer<int>.Default));
AssertThrows.Wrapped<DeliberateTestException>(() => labeled.Item.ToDictionary(x => x, (Func<int, int>)(y => { throw new DeliberateTestException(); }), EqualityComparer<int>.Default));
AssertThrows.Wrapped<DeliberateTestException>(() => labeled.Item.ToDictionary(x => x, new FailingEqualityComparer<int>()));
AssertThrows.Wrapped<DeliberateTestException>(() => labeled.Item.ToDictionary(x => x, y => y, new FailingEqualityComparer<int>()));
}
[Fact]
public static void ToDictionary_ArgumentNullException()
{
AssertExtensions.Throws<ArgumentNullException>("source", () => ((ParallelQuery<int>)null).ToDictionary(x => x));
AssertExtensions.Throws<ArgumentNullException>("source", () => ((ParallelQuery<int>)null).ToDictionary(x => x, EqualityComparer<int>.Default));
AssertExtensions.Throws<ArgumentNullException>("source", () => ((ParallelQuery<int>)null).ToDictionary(x => x, y => y));
AssertExtensions.Throws<ArgumentNullException>("source", () => ((ParallelQuery<int>)null).ToDictionary(x => x, y => y, EqualityComparer<int>.Default));
AssertExtensions.Throws<ArgumentNullException>("keySelector", () => ParallelEnumerable.Empty<int>().ToDictionary((Func<int, int>)null));
AssertExtensions.Throws<ArgumentNullException>("keySelector", () => ParallelEnumerable.Empty<int>().ToDictionary((Func<int, int>)null, EqualityComparer<int>.Default));
AssertExtensions.Throws<ArgumentNullException>("keySelector", () => ParallelEnumerable.Empty<int>().ToDictionary((Func<int, int>)null, y => y));
AssertExtensions.Throws<ArgumentNullException>("keySelector", () => ParallelEnumerable.Empty<int>().ToDictionary((Func<int, int>)null, y => y, EqualityComparer<int>.Default));
AssertExtensions.Throws<ArgumentNullException>("elementSelector", () => ParallelEnumerable.Empty<int>().ToDictionary(x => x, (Func<int, int>)null));
AssertExtensions.Throws<ArgumentNullException>("elementSelector", () => ParallelEnumerable.Empty<int>().ToDictionary(x => x, (Func<int, int>)null, EqualityComparer<int>.Default));
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;
using gView.Framework.UI;
using gView.Framework.Data;
using gView.Framework.FDB;
using gView.Framework.Carto;
using gView.Framework.Geometry;
using gView.Framework.system;
using gView.Framework.IO;
using gView.Framework.Globalisation;
using gView.Framework.LinAlg;
using System.Threading;
using gView.Framework.Editor.Core;
namespace gView.Plugins.Editor
{
[gView.Framework.system.RegisterPlugIn("FE2AE24C-73F8-4da3-BBC7-45C2FCD3FE75")]
public class EditorMenu : ITool, IToolItem
{
ToolStripMenuItem _startEditing = new ToolStripMenuItem();
ToolStripMenuItem _stopEditing = new ToolStripMenuItem();
ToolStripMenuItem _saveEdits = new ToolStripMenuItem();
#region ITool Members
public string Name
{
get { return "Editor Menu"; }
}
public bool Enabled
{
get { return true; }
}
public string ToolTip
{
get { return ""; }
}
public ToolType toolType
{
get { return ToolType.command; }
}
public object Image
{
get { return null; }
}
public void OnCreate(object hook)
{
}
public void OnEvent(object MapEvent)
{
}
#endregion
#region IToolItem Members
public System.Windows.Forms.ToolStripItem ToolItem
{
get
{
ToolStripDropDownButton button = new ToolStripDropDownButton();
button.Text = "Editor";
_startEditing.Text = "Start Editing";
_stopEditing.Text = "Stop Editing";
_saveEdits.Text = "Save Edits";
button.DropDownItems.Add(_startEditing);
button.DropDownItems.Add(_stopEditing);
button.DropDownItems.Add(new ToolStripSeparator());
button.DropDownItems.Add(_saveEdits);
return button;
}
}
#endregion
}
[gView.Framework.system.RegisterPlugIn("19396559-C13C-486c-B5F7-73DD5B12D5A8")]
public class TaskText : ITool, IToolItem
{
#region ITool Members
public string Name
{
get { return "Editor Task"; }
}
public bool Enabled
{
get { return true; }
}
public string ToolTip
{
get { return ""; }
}
public ToolType toolType
{
get { return ToolType.command; }
}
public object Image
{
get { return null; }
}
public void OnCreate(object hook)
{
}
public void OnEvent(object MapEvent)
{
}
#endregion
#region IToolItem Members
public ToolStripItem ToolItem
{
get
{
return new ToolStripLabel(LocalizedResources.GetResString("String.Task", "Task"));
}
}
#endregion
}
[gView.Framework.system.RegisterPlugIn("9B7D5E0E-88A5-40e2-977B-8A2E21875221")]
public class TaskCombo : ITool, IToolItem, IPersistable, IToolItemLabel
{
private IMapDocument _doc = null;
private Module _module = null;
private ToolStripComboBox _combo = null;
public TaskCombo()
{
_combo = new ToolStripComboBox();
_combo.DropDownStyle = ComboBoxStyle.DropDownList;
_combo.SelectedIndexChanged += new EventHandler(combo_SelectedIndexChanged);
}
#region ITool Members
public string Name
{
get { return "Editor Task Combobox"; }
}
public bool Enabled
{
get { return true; }
}
public string ToolTip
{
get { return ""; }
}
public ToolType toolType
{
get { return ToolType.command; }
}
public object Image
{
get { return null; }
}
public void OnCreate(object hook)
{
if (hook is IMapDocument)
{
_doc = (IMapDocument)hook;
if (_doc.Application is IMapApplication)
_module = ((IMapApplication)_doc.Application).IMapApplicationModule(Globals.ModuleGuid) as Module;
if (_module != null)
{
_module.OnChangeSelectedFeature += new Module.OnChangeSelectedFeatureEventHandler(_module_OnChangeSelectedFeature);
}
}
}
public void OnEvent(object MapEvent)
{
}
#endregion
#region IToolItem Members
public ToolStripItem ToolItem
{
get
{
return _combo;
}
}
#endregion
void combo_SelectedIndexChanged(object sender, EventArgs e)
{
if (_module == null || !(_combo.SelectedItem is ItemClass)) return;
_module.ActiveEditTask = ((ItemClass)_combo.SelectedItem).Task;
if (_doc != null && _doc.Application is IGUIApplication)
((IGUIApplication)_doc.Application).ValidateUI();
}
void _module_OnChangeSelectedFeature(Module sender, IFeature feature)
{
if (sender == null) return;
Module.EditTask aktive = sender.ActiveEditTask;
_combo.Items.Clear();
if (sender.SelectedEditLayer == null) return;
if (Bit.Has(sender.SelectedEditLayer.AllowedStatements, EditStatements.INSERT))
_combo.Items.Add(new ItemClass(Module.EditTask.CreateNewFeature));
if (Bit.Has(sender.SelectedEditLayer.AllowedStatements, EditStatements.UPDATE) ||
Bit.Has(sender.SelectedEditLayer.AllowedStatements, EditStatements.DELETE))
_combo.Items.Add(new ItemClass(Module.EditTask.ModifyFeature));
foreach (ItemClass item in _combo.Items)
{
if (item.Task == aktive)
_combo.SelectedItem = item;
}
if (_combo.SelectedIndex == -1 && _combo.Items.Count > 0)
_combo.SelectedIndex = 0;
}
#region ItemClasses
private class ItemClass
{
private Module.EditTask _task;
private string _text = String.Empty;
public ItemClass(Module.EditTask task)
{
_task = task;
switch (_task)
{
case Module.EditTask.CreateNewFeature:
_text = LocalizedResources.GetResString("String.CreateNewFeatures", "Create New Features");
break;
case Module.EditTask.ModifyFeature:
_text = LocalizedResources.GetResString("String.ModifyFeatures", "Modify Features");
break;
}
}
public Module.EditTask Task
{
get { return _task; }
}
public override string ToString()
{
return _text;
}
}
#endregion
#region IPersistable Member
public void Load(IPersistStream stream)
{
try
{
_combo.SelectedIndex = (int)stream.Load("selectedIndex", 0);
}
catch { }
}
public void Save(IPersistStream stream)
{
stream.Save("selectedIndex", _combo.SelectedIndex);
}
#endregion
#region IToolItemLabel Member
public string Label
{
get { return LocalizedResources.GetResString("String.Task", "Task"); }
}
public ToolItemLabelPosition LabelPosition
{
get { return ToolItemLabelPosition.top; }
}
#endregion
}
[gView.Framework.system.RegisterPlugIn("784148EB-04EA-413d-B11A-1A0F9A7EA4A0")]
public class TargetText : ITool, IToolItem
{
#region ITool Member
public string Name
{
get { return "Editor.Target"; }
}
public bool Enabled
{
get { return true; }
}
public string ToolTip
{
get { return String.Empty; }
}
public ToolType toolType
{
get { return ToolType.command; }
}
public object Image
{
get { return null; }
}
public void OnCreate(object hook)
{
}
public void OnEvent(object MapEvent)
{
}
#endregion
#region IToolItem Member
public ToolStripItem ToolItem
{
get
{
return new ToolStripLabel(LocalizedResources.GetResString("String.Edit", "Edit"));
}
}
#endregion
}
[gView.Framework.system.RegisterPlugIn("3C8A7ABC-B535-43d8-8F2D-B220B298CB17")]
public class TargetCombo : ITool, IToolItem, IPersistable, IToolItemLabel
{
private IMapDocument _doc = null;
private ToolStripComboBox _combo;
private Module _module = null;
public TargetCombo()
{
_combo = new ToolStripComboBox();
((ToolStripComboBox)_combo).DropDownStyle = ComboBoxStyle.DropDownList;
((ToolStripComboBox)_combo).Width = 300;
}
#region ITool Member
public string Name
{
get { return "Editor.TargetCombo"; }
}
public bool Enabled
{
get { return true; }
}
public string ToolTip
{
get { return String.Empty; }
}
public ToolType toolType
{
get { return ToolType.command; }
}
public object Image
{
get { return null; }
}
public void OnCreate(object hook)
{
if (hook is IMapDocument)
{
_doc = (IMapDocument)hook;
_doc.AfterSetFocusMap += new AfterSetFocusMapEvent(_doc_AfterSetFocusMap);
if (_doc.Application is IMapApplication)
{
_module = ((IMapApplication)_doc.Application).IMapApplicationModule(Globals.ModuleGuid) as Module;
if (_module != null)
{
_module.OnEditLayerCollectionChanged += new OnEditLayerCollectionChangedEventHandler(_module_OnEditLayerCollectionChanged);
}
}
_combo.SelectedIndexChanged += new EventHandler(combo_SelectedIndexChanged);
FillCombo();
}
}
public void OnEvent(object MapEvent)
{
}
#endregion
#region IToolItem Member
public ToolStripItem ToolItem
{
get
{
return _combo as ToolStripComboBox;
}
}
#endregion
#region MapDocument events
void _doc_AfterSetFocusMap(gView.Framework.Carto.IMap map)
{
FillCombo();
}
#endregion
#region Module Events
void _module_OnEditLayerCollectionChanged(object sender)
{
FillCombo();
}
#endregion
#region Helper
private delegate void FillComboCallback();
public void FillCombo()
{
//return;
if (_combo == null || _combo.Owner == null) return;
if (_combo.Owner.InvokeRequired)
{
FillComboCallback d = new FillComboCallback(FillCombo);
_combo.Owner.BeginInvoke(d);
return;
}
string selectedName = (_combo.SelectedItem is FeatureClassesItem) ? _combo.SelectedItem.ToString() : "";
_combo.SelectedIndexChanged -= new EventHandler(combo_SelectedIndexChanged);
_combo.Items.Clear();
if (_doc == null || _doc.FocusMap == null || _doc.FocusMap.TOC == null ||
_module == null || _module.EditLayers == null)
{
return;
}
IMap map = _doc.FocusMap;
foreach (IEditLayer editLayer in _module.EditLayers)
{
if (editLayer == null ||
editLayer.FeatureLayer == null ||
editLayer.FeatureLayer.FeatureClass == null ||
editLayer.AllowedStatements == EditStatements.NONE) continue;
if (map[editLayer.FeatureLayer] == null) continue;
// Besser layer als layer.Class verwendenden, weil Class von mehrerenen Layern
// verwendet werden kann zB bei gesplitteten Layern...
//ITOCElement tocElement = map.TOC.GetTOCElement(editLayer.FeatureLayer.FeatureClass);
ITOCElement tocElement = map.TOC.GetTOCElement(editLayer.FeatureLayer);
if (tocElement == null) continue;
_combo.Items.Add(new FeatureClassesItem(
editLayer,
tocElement.Name));
if (tocElement.Name == selectedName)
_combo.SelectedIndex = _combo.Items.Count - 1;
}
_combo.SelectedIndexChanged += new EventHandler(combo_SelectedIndexChanged);
if (_persistedSelIndex >= -0 && _persistedSelIndex < _combo.Items.Count)
_combo.SelectedIndex = _persistedSelIndex;
if (_combo.SelectedIndex == -1 && _combo.Items.Count > 0)
_combo.SelectedIndex = 0;
_persistedSelIndex = -1;
if (_combo.SelectedIndex == -1 && _module != null)
_module.SelectedEditLayer = null;
using (System.Drawing.Bitmap bm = new System.Drawing.Bitmap(1, 1))
{
using (System.Drawing.Graphics gr = System.Drawing.Graphics.FromImage(bm))
{
_combo.DropDownWidth = _combo.Size.Width;
foreach (object obj in _combo.Items)
{
System.Drawing.SizeF size = gr.MeasureString(obj.ToString(), _combo.Font);
if (size.Width + 20 > _combo.DropDownWidth)
_combo.DropDownWidth = (int)size.Width + 20;
}
}
}
}
#endregion
#region ItemClasses
private class FeatureClassesItem
{
private string _name;
private IEditLayer _eLayer;
public FeatureClassesItem(IEditLayer eLayer, string name)
{
_eLayer = eLayer;
_name = name;
}
public IEditLayer EditLayer
{
get { return _eLayer; }
}
public override string ToString()
{
return _name;
}
}
#endregion
void combo_SelectedIndexChanged(object sender, EventArgs e)
{
if (_module != null)
{
if (_combo.SelectedItem is FeatureClassesItem)
{
FeatureClassesItem item = (FeatureClassesItem)_combo.SelectedItem;
_module.SelectedEditLayer = item.EditLayer;
}
else
{
_module.SelectedEditLayer = null;
}
}
}
#region IPersistable Member
private int _persistedSelIndex = -1;
public void Load(IPersistStream stream)
{
_persistedSelIndex = (int)stream.Load("selectedIndex", 0);
if (_persistedSelIndex < _combo.Items.Count)
_combo.SelectedIndex = _persistedSelIndex;
}
public void Save(IPersistStream stream)
{
stream.Save("selectedIndex", _combo.SelectedIndex);
}
#endregion
#region IToolItemLabel Member
public string Label
{
get { return LocalizedResources.GetResString("String.Edit", "Edit"); }
}
public ToolItemLabelPosition LabelPosition
{
get { return ToolItemLabelPosition.top; }
}
#endregion
}
//public class TargetComboWpf : TargetCombo
//{
// public TargetComboWpf()
// {
// _combo = new System.Windows.Controls.ComboBox();
// }
//}
[gView.Framework.system.RegisterPlugIn("91392106-2C28-429c-8100-1E4E927D521C")]
public class EditTool : gView.Framework.Snapping.Core.SnapTool, ITool, IToolWindow, IToolMouseActions, IToolKeyActions, IToolContextMenu
{
private IMapDocument _doc = null;
private Module _module = null;
private ContextMenuStrip _addVertexMenu, _removeVertexMenu, _currentMenu = null;
public EditTool()
{
_addVertexMenu = new ContextMenuStrip();
ToolStripMenuItem addvertex = new ToolStripMenuItem(
Globalisation.GetResString("AddVertex"));
addvertex.Click += new EventHandler(addvertex_Click);
_addVertexMenu.Items.Add(addvertex);
_removeVertexMenu = new ContextMenuStrip();
ToolStripMenuItem removevertex = new ToolStripMenuItem(
Globalisation.GetResString("RemoveVertex"));
removevertex.Click += new EventHandler(removevertex_Click);
_removeVertexMenu.Items.Add(removevertex);
}
#region ITool Members
public string Name
{
get { return "Editor.ModifyFeature"; }
}
public bool Enabled
{
get
{
if (_module == null) return false;
switch (_module.ActiveEditTask)
{
case Module.EditTask.None:
return false;
case Module.EditTask.CreateNewFeature:
if (_module.Sketch != null)
return true;
break;
case Module.EditTask.ModifyFeature:
return true;
}
return false;
}
}
public string ToolTip
{
get { return LocalizedResources.GetResString("Tools.Editor.ModifyFeature", "Modify Feature/Sketch"); }
}
public ToolType toolType
{
get { return ToolType.userdefined; }
}
public object Image
{
get
{
return global::gView.Plugins.Editor.Properties.Resources.edit_modify;
}
}
override public void OnCreate(object hook)
{
base.OnCreate(hook);
if (hook is IMapDocument)
{
_doc = (IMapDocument)hook;
if (_doc.Application is IMapApplication)
{
_module = ((IMapApplication)_doc.Application).IMapApplicationModule(Globals.ModuleGuid) as Module;
//_module.OnChangeEditTask += new Module.OnChangeEditTaskEventHandler(Module_OnChangeEditTask);
}
}
}
public void OnEvent(object MapEvent)
{
}
#endregion
#region IToolWindow Member
public IDockableWindow ToolWindow
{
get
{
if (_module != null)
return _module.AttributeEditorWindow;
return null;
}
}
#endregion
#region IToolMouseActions Member
double _oX = 0, _oY = 0;
bool _mousePressed = false;
HitPositions _hit = null;
public void MouseDown(gView.Framework.Carto.IDisplay display, MouseEventArgs e, IPoint world)
{
if (_module == null || _doc == null || _doc.FocusMap == null || !(_doc.Application is IMapApplication)) return;
if (e.Button != MouseButtons.Left) return;
_mousePressed = true;
switch (_module.ActiveEditTask)
{
case Module.EditTask.None:
case Module.EditTask.CreateNewFeature:
return;
}
_oX = world.X;
_oY = world.Y;
//if (_hit == null)
//{
// RemoveSketch();
//}
if (/*_module.Sketch == null*/_hit == null)
{
#region Query Feature
if (_module.SelectedEditLayer == null ||
_module.SelectedEditLayer.FeatureLayer == null ||
_module.SelectedEditLayer.FeatureLayer.FeatureClass == null) return;
IFeatureClass fc = _module.SelectedEditLayer.FeatureLayer.FeatureClass;
double tolerance = 5.0;
double tol = tolerance * _doc.FocusMap.Display.mapScale / (96 / 0.0254); // [m]
if (_doc.FocusMap.Display.SpatialReference != null &&
_doc.FocusMap.Display.SpatialReference.SpatialParameters.IsGeographic)
{
tol = (180.0 * tol / Math.PI) / 6370000.0;
}
IEnvelope envelope = new Envelope(_oX - tol / 2.0, _oY - tol / 2.0, _oX + tol / 2.0, _oY + tol / 2.0);
SpatialFilter filter = new SpatialFilter();
filter.Geometry = envelope;
if (_doc.FocusMap.Display.SpatialReference != null)
{
filter.FilterSpatialReference = _doc.FocusMap.Display.SpatialReference.Clone() as ISpatialReference;
filter.FeatureSpatialReference = _doc.FocusMap.Display.SpatialReference.Clone() as ISpatialReference;
}
filter.SubFields = "*";
IFeature feature = null;
using (IFeatureCursor cursor = fc.GetFeatures(filter))
{
if (cursor == null) return;
feature = cursor.NextFeature;
if (feature != null)
{
if (_module.Feature == null || _module.Feature.OID != feature.OID)
{
RemoveSketch();
_module.Feature = feature;
return;
}
}
}
#endregion
}
}
public void MouseUp(gView.Framework.Carto.IDisplay display, MouseEventArgs e, IPoint world)
{
_mousePressed = false;
if (_hit != null && _doc.Application is IMapApplication)
{
((IMapApplication)_doc.Application).RefreshActiveMap(DrawPhase.Graphics);
}
}
public void MouseClick(gView.Framework.Carto.IDisplay display, MouseEventArgs e, IPoint world)
{
}
public void MouseDoubleClick(gView.Framework.Carto.IDisplay display, MouseEventArgs e, IPoint world)
{
}
public void MouseMove(gView.Framework.Carto.IDisplay display, MouseEventArgs e, IPoint world)
{
if (_module == null || _doc == null || _doc.FocusMap == null) return;
double x1 = world.X, y1 = world.Y;
_displayPoint = new Point(x1, y1);
if (!_mousePressed && _module.Sketch != null)
{
_currentMenu = null;
_hit = _module.Sketch.HitTest(_doc.FocusMap.Display, _displayPoint);
if (_hit != null)
{
if(_doc.Application is IGUIApplication)
((IGUIApplication)_doc.Application).SetCursor(_hit.Cursor as Cursor);
if (_hit.Cursor == gView.Plugins.Editor.EditSketch.HitPosition.VertexCursor)
{
_currentMenu = _removeVertexMenu;
}
else if (_hit.HitID == -1)
{
_currentMenu = _addVertexMenu;
}
}
else
{
if (_doc.Application is IGUIApplication)
((IGUIApplication)_doc.Application).SetCursor(Cursors.Default);
}
}
else if (_mousePressed && _hit != null)
{
if (_module.Sketch != null)
_module.Sketch.Design(display, _hit, world.X, world.Y);
_module.RedrawhSketch();
}
}
public void MouseWheel(gView.Framework.Carto.IDisplay display, MouseEventArgs e, IPoint world)
{
}
#endregion
#region IToolKeyActions Member
public void KeyDown(gView.Framework.Carto.IDisplay display, KeyEventArgs e)
{
}
public void KeyPress(gView.Framework.Carto.IDisplay display, KeyPressEventArgs e)
{
}
public void KeyUp(gView.Framework.Carto.IDisplay display, KeyEventArgs e)
{
}
#endregion
#region Helper
private void RemoveSketch()
{
if (_module == null || _doc == null || _doc.FocusMap == null || _doc.FocusMap.Display == null || _doc.FocusMap.Display.GraphicsContainer == null) return;
_module.Feature = null;
}
#endregion
public override void Snap(ref double X, ref double Y)
{
if (_hit != null && _mousePressed)
base.Snap(ref X, ref Y);
}
public override bool ShowSnapMarker
{
get
{
if (_hit != null && _mousePressed)
return true;
return false;
}
}
#region IToolContextMenu Member
public ContextMenuStrip ContextMenu
{
get { return _currentMenu; }
}
#endregion
void removevertex_Click(object sender, EventArgs e)
{
if (_doc == null || _doc.FocusMap == null ||
_hit == null || _module.Sketch == null ||
!_hit.Cursor.Equals(gView.Plugins.Editor.EditSketch.HitPosition.VertexCursor)) return;
_module.Sketch.RemoveVertex(_doc.FocusMap.Display, _hit.HitID);
if (_doc.Application is IMapApplication)
((IMapApplication)_doc.Application).RefreshActiveMap(DrawPhase.Graphics);
}
private IPoint _displayPoint = null;
void addvertex_Click(object sender, EventArgs e)
{
if (_doc == null || _doc.FocusMap == null ||
_hit == null || _module.Sketch == null ||
_displayPoint == null) return;
_module.Sketch.AddVertex(_doc.FocusMap.Display,
new Point(_displayPoint.X, _displayPoint.Y));
if (_doc.Application is IMapApplication)
((IMapApplication)_doc.Application).RefreshActiveMap(DrawPhase.Graphics);
}
}
[gView.Framework.system.RegisterPlugIn("3B64107F-00C8-4f4a-B781-163FE9DA2D4B")]
public class EditPenTool : gView.Framework.Snapping.Core.SnapTool, ITool, IToolMouseActions, IToolMouseActions2, IToolKeyActions, IToolContextMenu
{
protected IMapDocument _doc = null;
internal Module _module = null;
private bool _finished = false;
private ParentPenToolMenuItem _penToolItem;
private System.Drawing.Image _image;
public EditPenTool()
{
_image = global::gView.Plugins.Editor.Properties.Resources.edit_blue;
_penToolItem = new ParentPenToolMenuItem();
_penToolItem.SelectedPenToolChanged += new ParentPenToolMenuItem.SelectedPenToolChangedEventHandler(penToolItem_SelectedPenToolChanged);
}
#region ITool Members
virtual public string Name
{
get { return "Editor.NewFeature"; }
}
virtual public bool Enabled
{
get
{
if (_module == null) return false;
switch (_module.ActiveEditTask)
{
case Module.EditTask.None:
return false;
case Module.EditTask.CreateNewFeature:
return true;
case Module.EditTask.ModifyFeature:
if (_module.Feature != null &&
_module.Feature.OID > 0) return true;
break;
}
return false;
}
}
virtual public string ToolTip
{
get { return LocalizedResources.GetResString("Tools.Editor.NewFeature", "New Feature/Vertex"); }
}
virtual public ToolType toolType
{
get { return ToolType.click; }
}
virtual public object Image
{
get
{
return global::gView.Plugins.Editor.Properties.Resources.edit_blue;
}
}
override public void OnCreate(object hook)
{
base.OnCreate(hook);
if (hook is IMapDocument)
{
_doc = (IMapDocument)hook;
if (_doc.Application is IMapApplication)
{
_module = ((IMapApplication)_doc.Application).IMapApplicationModule(Globals.ModuleGuid) as Module;
if (_module != null)
_module.OnChangeSelectedFeature += new Module.OnChangeSelectedFeatureEventHandler(Module_OnChangeSelectedFeature);
((IMapApplication)_doc.Application).ActiveMapToolChanged += new ActiveMapToolChangedEvent(EditNew_ActiveMapToolChanged);
_penToolItem.OnCreate(_module);
}
}
}
virtual public void OnEvent(object MapEvent)
{
}
#endregion
#region IToolMouseActions Member
private bool _mousePressed = false;
protected double _X, _Y;
virtual public void MouseDown(IDisplay display, MouseEventArgs e, IPoint world)
{
if (_doc == null || _doc.FocusMap == null || _doc.FocusMap.Display == null || _module == null || _module.FeatureClass == null) return;
if (e.Button != MouseButtons.Left) return;
_mousePressed = true;
if (_module.Feature == null ||
_module.Sketch == null)
{
_module.CreateStandardFeature();
_finished = false;
}
if (_finished || _module.Sketch == null) return;
CalcXY(e.X, e.Y, world);
if (!double.IsNaN(_X) && !double.IsNaN(_Y))
{
_module.Sketch.AddPoint(new Point(_X, _Y));
if (_doc.Application is IMapApplication)
{
((IMapApplication)_doc.Application).RefreshActiveMap(DrawPhase.Graphics);
Thread.Sleep(200);
}
}
_penToolItem.PerformClick();
}
virtual public void MouseUp(IDisplay display, MouseEventArgs e, IPoint world)
{
if (!_mousePressed) return;
_mousePressed = false;
}
virtual public void MouseClick(IDisplay display, MouseEventArgs e, IPoint world)
{
}
virtual public void MouseDoubleClick(IDisplay display, MouseEventArgs e, IPoint world)
{
}
virtual public void MouseMove(IDisplay display, MouseEventArgs e, IPoint world)
{
if (_doc == null || _doc.FocusMap == null || _doc.FocusMap.Display == null || _module == null) return;
if (_finished) return;
CalcXY(e.X, e.Y, world);
DrawMover();
}
virtual public void MouseWheel(IDisplay display, MouseEventArgs e, IPoint world)
{
}
#endregion
#region IToolMouseActions2 Member
public void BeforeShowContext(IDisplay display, MouseEventArgs e, IPoint world)
{
if (_penToolItem != null &&
_module != null &&
_module.MapDocument != null &&
_module.MapDocument.FocusMap != null &&
_module.MapDocument.FocusMap.Display != null)
{
double x = e.X, y = e.Y;
_module.MapDocument.FocusMap.Display.Image2World(ref x, ref y);
_penToolItem.ContextVertex = _penToolItem.CalcPoint(e.X, e.Y, world);
_penToolItem.MouseWorldPoint = new Point(x, y);
_penToolItem.ContextPoint = world;
}
}
#endregion
#region IToolKeyActions Member
virtual public void KeyDown(IDisplay display, KeyEventArgs e)
{
if (e.KeyCode == Keys.F2)
{
//_finished = true;
if (_doc.Application is IMapApplication)
{
((IMapApplication)_doc.Application).RefreshActiveMap(DrawPhase.Graphics);
((IMapApplication)_doc.Application).ActiveTool = ((IMapApplication)_doc.Application).Tool(new Guid("91392106-2C28-429c-8100-1E4E927D521C"));
}
}
}
virtual public void KeyPress(IDisplay display, KeyPressEventArgs e)
{
}
virtual public void KeyUp(IDisplay display, KeyEventArgs e)
{
}
#endregion
#region Events Handler
void Module_OnChangeSelectedFeature(Module sender, IFeature feature)
{
if (_module == null || _doc == null || _doc.FocusMap == null || _doc.FocusMap.Display == null || _doc.FocusMap.Display.GraphicsContainer == null) return;
if (_doc.Application is IMapApplication &&
((IMapApplication)_doc.Application).ActiveTool == this)
{
}
}
void EditNew_ActiveMapToolChanged(ITool OldTool, ITool NewTool)
{
//if (OldTool != this && NewTool == this && _module != null &&
// _doc!=null && _doc.Application is IMapApplication)
//{
// TargetCombo combo = ((IMapApplication)_doc.Application).Tool(new Guid("3C8A7ABC-B535-43d8-8F2D-B220B298CB17")) as TargetCombo;
// List<IFeatureClass> fcs = combo.SelectedFeatureclasses;
// if (fcs == null || fcs.Count != 1)
// {
// _module.SetFeatureClassAndFeature(null, null);
// }
// else
// {
// _module.SetFeatureClassAndFeature(fcs[0], CreateFeature());
// }
//}
if (OldTool == this && NewTool != this)
{
if (_doc != null && _doc.Application is IMapApplication)
((IMapApplication)_doc.Application).RefreshActiveMap(DrawPhase.Graphics);
}
}
#endregion
#region HelperClasses
private class EditPartNumberMenuItem : ToolStripMenuItem
{
private EditSketch _sketch;
private int _partNr;
public EditPartNumberMenuItem(EditSketch sketch, int partNr, string text)
{
_sketch = sketch;
_partNr = partNr;
base.Text = text;
base.Click += new EventHandler(EditPartNumberMenuItem_Click);
if (sketch.ActivePartNumber == partNr)
base.Checked = true;
}
void EditPartNumberMenuItem_Click(object sender, EventArgs e)
{
if (_sketch != null)
_sketch.ActivePartNumber = _partNr;
}
}
#endregion
#region IToolContextMenu Member
virtual public ContextMenuStrip ContextMenu
{
get
{
ContextMenuStrip strip = new ContextMenuStrip();
if (_module != null && _module.Sketch != null && _module.Sketch.PartCount != 0)
{
ToolStripMenuItem editPartItem = new ToolStripMenuItem(
Globalisation.GetResString("EditPart"));
for (int i = 0; i < _module.Sketch.PartCount; i++)
{
editPartItem.DropDownItems.Add(new EditPartNumberMenuItem(
_module.Sketch, i, (i + 1).ToString()));
}
editPartItem.DropDownItems.Add(new EditPartNumberMenuItem(
_module.Sketch, _module.Sketch.PartCount,
Globalisation.GetResString("New")));
strip.Items.Add(editPartItem);
if (_module.Sketch.Part.PointCount > 2)
{
ToolStripMenuItem closePart = new ToolStripMenuItem(
Globalisation.GetResString("ClosePart"));
closePart.Click += new EventHandler(closePart_Click);
strip.Items.Add(closePart);
}
}
bool first = true;
foreach (ToolStripItem item in _penToolItem.MenuItems)
{
if (first && strip.Items.Count != 0)
{
strip.Items.Add(new ToolStripSeparator());
}
strip.Items.Add(item);
first = false;
}
return strip;
}
}
#endregion
virtual protected void CalcXY(int mouseX, int mouseY, IPoint world)
{
//_X = world.X;
//_Y = world.Y;
IPoint point = _penToolItem.CalcPoint(mouseX, mouseY, world);
if (point != null)
{
_X = point.X;
_Y = point.Y;
}
else
{
_X = _Y = double.NaN;
}
}
protected void DrawMover()
{
if (_penToolItem.DrawMover)
{
if (!double.IsNaN(_X) && !double.IsNaN(_Y))
_module.Mover = new Point(_X, _Y);
}
}
void penToolItem_SelectedPenToolChanged(object sender, IPenTool penTool)
{
if (_doc == null || !(_doc.Application is IMapApplication) ||
((IMapApplication)_doc.Application).StatusBar == null) return;
if (penTool != null && penTool.Image is System.Drawing.Image)
{
_image = (System.Drawing.Image)penTool.Image;
}
else
{
_image = global::gView.Plugins.Editor.Properties.Resources.edit_blue;
}
((IMapApplication)_doc.Application).StatusBar.Image = _image;
}
void closePart_Click(object sender, EventArgs e)
{
if (_module != null && _module.Sketch != null)
_module.Sketch.ClosePart();
if (_doc != null && _doc.Application is IMapApplication)
{
((IMapApplication)_doc.Application).RefreshActiveMap(DrawPhase.Graphics);
Thread.Sleep(200);
}
}
}
[gView.Framework.system.RegisterPlugIn("4F4A6AA1-89A6-498c-819A-0E52EF9AEA61")]
public class EditOrthoPenTool : EditPenTool
{
#region ITool
public override string Name
{
get
{
return "Edit.Ortho.PenTool";
}
}
public override object Image
{
get
{
return global::gView.Plugins.Editor.Properties.Resources.ortho;
}
}
#endregion
protected override void CalcXY(int mouseX, int mouseY, IPoint world)
{
if (_module == null) return;
EditSketch sketch = _module.Sketch;
IPointCollection part = (sketch != null) ? sketch.Part : null;
if (sketch == null || part == null || part.PointCount < 2)
{
base.CalcXY(mouseX, mouseY, world);
}
else
{
IPoint p1 = part[part.PointCount - 2];
IPoint p2 = part[part.PointCount - 1];
double dx = p2.X - p1.X;
double dy = p2.Y - p1.Y;
double alpha = Math.Atan2(dy, dx);
IPoint resP1 = null;
IPoint resP2 = null;
Point r = new Point(Math.Sin(alpha), -Math.Cos(alpha));
Point r_ = new Point(-r.Y, r.X);
#region Ortho
LinearEquation2 linarg = new LinearEquation2(
world.X - p2.X,
world.Y - p2.Y,
r.X, r_.X,
r.Y, r_.Y);
if (linarg.Solve())
{
double t1 = linarg.Var1;
double t2 = linarg.Var2;
resP1 = new Point(p2.X + r.X * t1, p2.Y + r.Y * t1);
}
#endregion
#region Otrho 2
r = new Point(Math.Cos(alpha), Math.Sin(alpha));
r_ = new Point(-r.Y, r.X);
linarg = new LinearEquation2(
world.X - p2.X,
world.Y - p2.Y,
r.X, r_.X,
r.Y, r_.Y);
if (linarg.Solve())
{
double t1 = linarg.Var1;
double t2 = linarg.Var2;
resP2 = new Point(p2.X + r.X * t1, p2.Y + r.Y * t1);
}
#endregion
if (resP1 != null || resP2 != null)
{
if (gView.Framework.SpatialAlgorithms.Algorithm.PointDistance(world, resP1) <=
gView.Framework.SpatialAlgorithms.Algorithm.PointDistance(world, resP2))
{
_X = resP1.X; _Y = resP1.Y;
}
else
{
_X = resP2.X; _Y = resP2.Y;
}
}
else if (resP1 != null)
{
_X = resP1.X; _Y = resP1.Y;
}
else
{
_X = resP2.X; _Y = resP2.Y;
}
}
}
}
[gView.Framework.system.RegisterPlugIn("B576D3F9-F7C9-46d5-8A8C-16B3974F1BD7")]
public class EditAttributes : ITool
{
private IMapDocument _doc = null;
private Module _module = null;
#region ITool Member
public string Name
{
get { return "Editor.Attributes"; }
}
public bool Enabled
{
get
{
if (_module != null && _module.Feature != null)
return true;
return false;
}
}
public string ToolTip
{
get { return LocalizedResources.GetResString("Tools.Editor.Attributes", "Attribute Editor"); }
}
public ToolType toolType
{
get { return ToolType.command; }
}
public object Image
{
get { return global::gView.Plugins.Editor.Properties.Resources.application_form_edit; }
}
public void OnCreate(object hook)
{
if (hook is IMapDocument)
{
_doc = (IMapDocument)hook;
if (_doc.Application is IMapApplication)
_module = ((IMapApplication)_doc.Application).IMapApplicationModule(Globals.ModuleGuid) as Module;
}
}
public void OnEvent(object MapEvent)
{
if (_module != null && _module.AttributeEditorWindow != null &&
_doc != null && _doc.Application is IMapApplication)
{
bool found = false;
foreach (IDockableWindow win in ((IMapApplication)_doc.Application).DockableWindows)
{
if (win == _module.AttributeEditorWindow)
{
found = true;
break;
}
}
if (!found)
((IMapApplication)_doc.Application).AddDockableWindow(_module.AttributeEditorWindow, "");
((IMapApplication)_doc.Application).ShowDockableWindow(_module.AttributeEditorWindow);
}
}
#endregion
}
[gView.Framework.system.RegisterPlugIn("96099E8C-163E-46ec-BA33-41696BFAE4D5")]
public class StoreFeature : ITool
{
private IMapDocument _doc = null;
private Module _module = null;
#region ITool Member
public string Name
{
get { return "Editor.Store"; }
}
public bool Enabled
{
get
{
if (_module == null ||
_module.SelectedEditLayer == null ||
_module.Feature == null)
return false;
if (_module.Feature.OID > 0 &&
!Bit.Has(_module.SelectedEditLayer.AllowedStatements, EditStatements.UPDATE))
return false;
if (_module.Feature.OID <= 0 &&
!Bit.Has(_module.SelectedEditLayer.AllowedStatements, EditStatements.INSERT))
return false;
return true;
}
}
public string ToolTip
{
get { return LocalizedResources.GetResString("Tools.Editor.Store", "Store Feature"); }
}
public ToolType toolType
{
get { return ToolType.command; }
}
public object Image
{
get { return global::gView.Plugins.Editor.Properties.Resources.database_save; }
}
public void OnCreate(object hook)
{
if (hook is IMapDocument)
{
_doc = (IMapDocument)hook;
if (_doc.Application is IMapApplication)
_module = ((IMapApplication)_doc.Application).IMapApplicationModule(Globals.ModuleGuid) as Module;
}
}
public void OnEvent(object MapEvent)
{
if (_module == null || _module.FeatureClass == null || _module.Feature == null)
return;
bool ret = false;
if (_module.Feature.OID > 0)
ret = _module.PerformUpdateFeature(_module.FeatureClass, _module.Feature);
else
ret = _module.PerformInsertFeature(_module.FeatureClass, _module.Feature);
if (!ret)
{
if (!String.IsNullOrEmpty(_module.LastMessage))
MessageBox.Show(_module.LastMessage, "Message");
}
else
{
_module.Feature = null;
((IMapApplication)_doc.Application).RefreshActiveMap(DrawPhase.All);
}
}
#endregion
}
[gView.Framework.system.RegisterPlugIn("AC4620D4-3DE4-49ea-A902-0B267BA46BBF")]
public class DeleteFeature : ITool
{
private IMapDocument _doc = null;
private Module _module = null;
#region ITool Member
public string Name
{
get { return "Editor.Delete"; }
}
public bool Enabled
{
get
{
if (_module == null || _module.SelectedEditLayer == null ||
_module.Feature == null ||
_module.Feature.OID <= 0 ||
!Bit.Has(_module.SelectedEditLayer.AllowedStatements, EditStatements.DELETE))
return false;
return true;
}
}
public string ToolTip
{
get { return LocalizedResources.GetResString("Tools.Editor.Delete", "Delete Feature"); }
}
public ToolType toolType
{
get { return ToolType.command; }
}
public object Image
{
get { return global::gView.Plugins.Editor.Properties.Resources.database_delete; }
}
public void OnCreate(object hook)
{
if (hook is IMapDocument)
{
_doc = (IMapDocument)hook;
if (_doc.Application is IMapApplication)
_module = ((IMapApplication)_doc.Application).IMapApplicationModule(Globals.ModuleGuid) as Module;
}
}
public void OnEvent(object MapEvent)
{
if (_module == null || _module.FeatureClass == null || _module.Feature == null)
return;
bool ret = false;
if (_module.Feature.OID > 0)
{
ret = _module.PerformDeleteFeature(_module.FeatureClass, _module.Feature);
}
else
{
ret = true;
}
if (!ret)
{
if (!String.IsNullOrEmpty(_module.LastMessage))
MessageBox.Show(_module.LastMessage, "Message");
}
else
{
_module.Feature = null;
((IMapApplication)_doc.Application).RefreshActiveMap(DrawPhase.All);
}
}
#endregion
}
[gView.Framework.system.RegisterPlugIn("11DEE52F-F241-406e-BB40-9F247532E43D")]
public class DeleteSelectedFeatures : ITool
{
private IMapDocument _doc = null;
private Module _module = null;
#region ITool Member
public string Name
{
get { return "Editor.DeleteSelected"; }
}
public bool Enabled
{
get
{
if (_doc == null || _doc.FocusMap == null || _doc.FocusMap.TOC == null ||
_module == null || _module.SelectedEditLayer == null ||
_module.SelectedEditLayer.FeatureLayer == null)
return false;
IFeatureSelection fSel = _module.SelectedEditLayer.FeatureLayer as IFeatureSelection;
if (fSel == null || fSel.SelectionSet == null)
return false;
return fSel.SelectionSet.Count > 0;
}
}
public string ToolTip
{
get { return LocalizedResources.GetResString("Tools.Editor.DeleteSelected", "Delete Selected Feature"); }
}
public ToolType toolType
{
get { return ToolType.command; }
}
public object Image
{
get { return global::gView.Plugins.Editor.Properties.Resources.database_delete_selected; }
}
public void OnCreate(object hook)
{
if (hook is IMapDocument)
{
_doc = (IMapDocument)hook;
if (_doc.Application is IMapApplication)
_module = ((IMapApplication)_doc.Application).IMapApplicationModule(Globals.ModuleGuid) as Module;
}
}
public void OnEvent(object MapEvent)
{
if (_doc == null || _doc.FocusMap == null || _doc.FocusMap.TOC == null ||
_module == null || _module.SelectedEditLayer == null ||
_module.SelectedEditLayer.FeatureLayer == null)
return;
IFeatureClass fClass = _module.SelectedEditLayer.FeatureLayer.FeatureClass;
if (fClass == null)
return;
IFeatureSelection fSel = _module.SelectedEditLayer.FeatureLayer as IFeatureSelection;
if (fSel == null || fSel.SelectionSet == null)
return;
ISelectionSet selectionSet = fSel.SelectionSet;
if (selectionSet.Count == 0)
return;
IQueryFilter filter = null;
//List<int> IDs=new List<int>(); // Sollte nicht null sein...
if (selectionSet is ISpatialIndexedIDSelectionSet)
{
List<int> IDs = ((ISpatialIndexedIDSelectionSet)selectionSet).IDs;
filter = new RowIDFilter(fClass.IDFieldName, IDs);
}
else if (selectionSet is IIDSelectionSet)
{
List<int> IDs = ((IIDSelectionSet)selectionSet).IDs;
filter = new RowIDFilter(fClass.IDFieldName, IDs);
}
else if (selectionSet is ISpatialIndexedGlobalIDSelectionSet)
{
List<long> IDs = ((ISpatialIndexedGlobalIDSelectionSet)selectionSet).IDs;
filter = new GlobalRowIDFilter(fClass.IDFieldName, IDs);
}
else if (selectionSet is IGlobalIDSelectionSet)
{
List<long> IDs = ((IGlobalIDSelectionSet)selectionSet).IDs;
filter = new GlobalRowIDFilter(fClass.IDFieldName, IDs);
}
else if (selectionSet is IQueryFilteredSelectionSet)
{
filter = ((IQueryFilteredSelectionSet)selectionSet).QueryFilter.Clone() as IQueryFilter;
}
if (filter == null)
return;
List<IFeature> features = new List<IFeature>();
using (IFeatureCursor fCursor = fClass.GetFeatures(filter))
{
IFeature feature;
while ((feature = fCursor.NextFeature) != null)
{
features.Add(feature);
}
}
if (features.Count != selectionSet.Count)
{
MessageBox.Show("Queried features are not the same than in selectionset!");
return;
}
if (MessageBox.Show("Delete " + features.Count + " selected features from " + _module.SelectedEditLayer.FeatureLayer.Title + "?", "Warning", MessageBoxButtons.YesNo) == DialogResult.Yes)
{
foreach (IFeature feature in features)
{
bool ret = _module.PerformDeleteFeature(fClass, feature);
if (!ret)
{
if (!String.IsNullOrEmpty(_module.LastMessage))
MessageBox.Show(_module.LastMessage, "Message");
}
}
}
if (_doc.Application is IMapApplication)
((IMapApplication)_doc.Application).RefreshActiveMap(DrawPhase.All);
}
#endregion
}
[gView.Framework.system.RegisterPlugIn("FD340DE3-0BC1-4b3e-99D2-E8DCD55A46F2")]
public class DeleteSketch : ITool
{
private IMapDocument _doc = null;
private Module _module = null;
#region ITool Member
public string Name
{
get { return "Editor.DeleteSktech"; }
}
public bool Enabled
{
get
{
if (_module == null || _module.FeatureClass == null || _module.Feature == null ||
_module.Sketch == null)
return false;
return true;
}
}
public string ToolTip
{
get { return LocalizedResources.GetResString("Tools.Editor.DeleteSktech", "Remove Sketch"); }
}
public ToolType toolType
{
get { return ToolType.command; }
}
public object Image
{
get { return global::gView.Plugins.Editor.Properties.Resources.cross; }
}
public void OnCreate(object hook)
{
if (hook is IMapDocument)
{
_doc = (IMapDocument)hook;
if (_doc.Application is IMapApplication)
_module = ((IMapApplication)_doc.Application).IMapApplicationModule(Globals.ModuleGuid) as Module;
}
}
public void OnEvent(object MapEvent)
{
if (_module == null || _module.Sketch == null)
return;
_module.Feature = null;
//((IMapApplication)_doc.Application).RefreshActiveMap(DrawPhase.Graphics);
}
#endregion
}
}
| |
//-----------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//-----------------------------------------------------------------------------
namespace System.Activities
{
using System;
using System.Activities.Runtime;
using System.ComponentModel;
using System.Diagnostics;
using System.Runtime.Serialization;
using System.Runtime;
using System.Collections.Specialized;
[DataContract]
[DebuggerDisplay("{Value}")]
public abstract class Location
{
TemporaryResolutionData temporaryResolutionData;
protected Location()
{
}
public abstract Type LocationType
{
get;
}
public object Value
{
get
{
return this.ValueCore;
}
set
{
this.ValueCore = value;
}
}
[DataMember(EmitDefaultValue = false, Name = "temporaryResolutionData")]
internal TemporaryResolutionData SerializedTemporaryResolutionData
{
get { return this.temporaryResolutionData; }
set { this.temporaryResolutionData = value; }
}
internal virtual bool CanBeMapped
{
get
{
return false;
}
}
// When we are resolving an expression that resolves to a
// reference to a location we need some way of notifying the
// LocationEnvironment that it should extract the inner location
// and throw away the outer one. OutArgument and InOutArgument
// create these TemporaryResolutionLocations if their expression
// resolution goes async and LocationEnvironment gets rid of them
// in CollapseTemporaryResolutionLocations().
internal LocationEnvironment TemporaryResolutionEnvironment
{
get
{
return this.temporaryResolutionData.TemporaryResolutionEnvironment;
}
}
internal bool BufferGetsOnCollapse
{
get
{
return this.temporaryResolutionData.BufferGetsOnCollapse;
}
}
protected abstract object ValueCore
{
get;
set;
}
internal void SetTemporaryResolutionData(LocationEnvironment resolutionEnvironment, bool bufferGetsOnCollapse)
{
this.temporaryResolutionData = new TemporaryResolutionData
{
TemporaryResolutionEnvironment = resolutionEnvironment,
BufferGetsOnCollapse = bufferGetsOnCollapse
};
}
internal virtual Location CreateReference(bool bufferGets)
{
if (this.CanBeMapped || bufferGets)
{
return new ReferenceLocation(this, bufferGets);
}
return this;
}
internal virtual object CreateDefaultValue()
{
Fx.Assert("We should only call this on Location<T>");
return null;
}
[DataContract]
internal struct TemporaryResolutionData
{
[DataMember(EmitDefaultValue = false)]
public LocationEnvironment TemporaryResolutionEnvironment
{
get;
set;
}
[DataMember(EmitDefaultValue = false)]
public bool BufferGetsOnCollapse
{
get;
set;
}
}
[DataContract]
internal class ReferenceLocation : Location
{
Location innerLocation;
bool bufferGets;
object bufferedValue;
public ReferenceLocation(Location innerLocation, bool bufferGets)
{
this.innerLocation = innerLocation;
this.bufferGets = bufferGets;
}
public override Type LocationType
{
get
{
return this.innerLocation.LocationType;
}
}
protected override object ValueCore
{
get
{
if (this.bufferGets)
{
return this.bufferedValue;
}
else
{
return this.innerLocation.Value;
}
}
set
{
this.innerLocation.Value = value;
this.bufferedValue = value;
}
}
[DataMember(Name = "innerLocation")]
internal Location SerializedInnerLocation
{
get { return this.innerLocation; }
set { this.innerLocation = value; }
}
[DataMember(EmitDefaultValue = false, Name = "bufferGets")]
internal bool SerializedBufferGets
{
get { return this.bufferGets; }
set { this.bufferGets = value; }
}
[DataMember(EmitDefaultValue = false, Name = "bufferedValue")]
internal object SerializedBufferedValue
{
get { return this.bufferedValue; }
set { this.bufferedValue = value; }
}
public override string ToString()
{
if (bufferGets)
{
return base.ToString();
}
else
{
return this.innerLocation.ToString();
}
}
}
}
[DataContract]
public class Location<T> : Location
{
T value;
public Location()
: base()
{
}
public override Type LocationType
{
get
{
return typeof(T);
}
}
public virtual new T Value
{
get
{
return this.value;
}
set
{
this.value = value;
}
}
internal T TypedValue
{
get
{
return this.Value;
}
set
{
this.Value = value;
}
}
protected override sealed object ValueCore
{
get
{
return this.Value;
}
set
{
this.Value = TypeHelper.Convert<T>(value);
}
}
[DataMember(EmitDefaultValue = false, Name = "value")]
internal T SerializedValue
{
get { return this.value; }
set { this.value = value; }
}
internal override Location CreateReference(bool bufferGets)
{
if (this.CanBeMapped || bufferGets)
{
return new ReferenceLocation(this, bufferGets);
}
return this;
}
internal override object CreateDefaultValue()
{
Fx.Assert(typeof(T).GetGenericTypeDefinition() == typeof(Location<>), "We should only be calling this with location subclasses.");
return Activator.CreateInstance<T>();
}
public override string ToString()
{
return this.value != null ? this.value.ToString() : "<null>";
}
[DataContract]
internal new class ReferenceLocation : Location<T>
{
Location<T> innerLocation;
bool bufferGets;
public ReferenceLocation(Location<T> innerLocation, bool bufferGets)
{
this.innerLocation = innerLocation;
this.bufferGets = bufferGets;
}
public override T Value
{
get
{
if (this.bufferGets)
{
return this.value;
}
else
{
return this.innerLocation.Value;
}
}
set
{
this.innerLocation.Value = value;
if (this.bufferGets)
{
this.value = value;
}
}
}
[DataMember(Name = "innerLocation")]
internal Location<T> SerializedInnerLocation
{
get { return this.innerLocation; }
set { this.innerLocation = value; }
}
[DataMember(EmitDefaultValue = false, Name = "bufferGets")]
internal bool SerializedBufferGets
{
get { return this.bufferGets; }
set { this.bufferGets = value; }
}
public override string ToString()
{
if (this.bufferGets)
{
return base.ToString();
}
else
{
return this.innerLocation.ToString();
}
}
}
}
}
| |
//*********************************************************
//
// Copyright (c) Microsoft. All rights reserved.
// This code is licensed under the MIT License (MIT).
// THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
// ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
// IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
// PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
//
//*********************************************************
using SDKTemplate.Helpers;
using SDKTemplate.Logging;
using System;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Windows.Media.Core;
using Windows.Media.Playback;
using Windows.Media.Streaming.Adaptive;
using Windows.UI.Core;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Navigation;
using Windows.Web.Http;
namespace SDKTemplate
{
/// See the README.md for discussion of this scenario.
public sealed partial class Scenario4_Tuning : Page
{
CancellationTokenSource ctsForInboundBitsPerSecondUiRefresh = new CancellationTokenSource();
private AdaptiveMediaSource adaptiveMediaSource;
private BitrateHelper bitrateHelper;
public Scenario4_Tuning()
{
this.InitializeComponent();
iconInboundBitsPerSecond.Symbol = (Symbol)0xE88A;
}
protected override void OnNavigatedFrom(NavigationEventArgs e)
{
ctsForInboundBitsPerSecondUiRefresh.Cancel(); // Cancel timer
adaptiveMediaSource = null; // release app instance of AdaptiveMediaSource
// Release handles on various media objects to ensure a quick clean-up
ContentSelectorControl.MediaPlaybackItem = null;
var mediaPlayer = mediaPlayerElement.MediaPlayer;
if (mediaPlayer != null)
{
mediaPlayerLogger?.Dispose();
mediaPlayerLogger = null;
UnregisterHandlers(mediaPlayer);
mediaPlayerElement.SetMediaPlayer(null);
mediaPlayer.Dispose();
}
}
private void UnregisterHandlers(MediaPlayer mediaPlayer)
{
AdaptiveMediaSource adaptiveMediaSource = null;
MediaPlaybackItem mpItem = mediaPlayer.Source as MediaPlaybackItem;
if (mpItem != null)
{
adaptiveMediaSource = mpItem.Source.AdaptiveMediaSource;
}
MediaSource source = mediaPlayer.Source as MediaSource;
if (source != null)
{
adaptiveMediaSource = source.AdaptiveMediaSource;
}
mediaPlaybackItemLogger?.Dispose();
mediaPlaybackItemLogger = null;
mediaSourceLogger?.Dispose();
mediaSourceLogger = null;
adaptiveMediaSourceLogger?.Dispose();
adaptiveMediaSourceLogger = null;
UnregisterForAdaptiveMediaSourceEvents(adaptiveMediaSource);
}
private void Page_OnLoaded(object sender, RoutedEventArgs e)
{
var mediaPlayer = new MediaPlayer();
// We use a helper class that logs all the events for the MediaPlayer:
mediaPlayerLogger = new MediaPlayerLogger(LoggerControl, mediaPlayer);
// Ensure we have PlayReady support, if the user enters a DASH/PR Uri in the text box:
var prHelper = new PlayReadyHelper(LoggerControl);
prHelper.SetUpProtectionManager(mediaPlayer);
mediaPlayerElement.SetMediaPlayer(mediaPlayer);
ContentSelectorControl.Initialize(
mediaPlayer,
MainPage.ContentManagementSystemStub.Where(m => !m.Aes),
null,
LoggerControl,
LoadSourceFromUriAsync);
// There is no InboundBitsPerSecondChanged event, so we start a polling thread to update UI.
PollForInboundBitsPerSecond(ctsForInboundBitsPerSecondUiRefresh);
}
private async void PollForInboundBitsPerSecond(CancellationTokenSource cts)
{
ulong InboundBitsPerSecondLast = 0;
var refreshRate = TimeSpan.FromSeconds(2);
while (!cts.IsCancellationRequested)
{
if (adaptiveMediaSource != null)
{
if (InboundBitsPerSecondLast != adaptiveMediaSource.InboundBitsPerSecond)
{
InboundBitsPerSecondLast = adaptiveMediaSource.InboundBitsPerSecond;
InboundBitsPerSecondText.Text = InboundBitsPerSecondLast.ToString();
}
}
await Task.Delay(refreshRate);
}
}
#region Content Loading
private async Task<MediaPlaybackItem> LoadSourceFromUriAsync(Uri uri, HttpClient httpClient = null)
{
UnregisterHandlers(mediaPlayerElement.MediaPlayer);
AdaptiveMediaSourceCreationResult result = null;
if (httpClient != null)
{
result = await AdaptiveMediaSource.CreateFromUriAsync(uri, httpClient);
}
else
{
result = await AdaptiveMediaSource.CreateFromUriAsync(uri);
}
MediaSource source;
if (result.Status == AdaptiveMediaSourceCreationStatus.Success)
{
adaptiveMediaSource = result.MediaSource;
// We use a helper class that logs all the events for the AdaptiveMediaSource:
adaptiveMediaSourceLogger = new AdaptiveMediaSourceLogger(LoggerControl, adaptiveMediaSource);
// In addition to logging, we use the callbacks to update some UI elements in this scenario:
RegisterForAdaptiveMediaSourceEvents(adaptiveMediaSource);
// At this point, we have read the manifest of the media source, and all bitrates are known.
bitrateHelper = new BitrateHelper(adaptiveMediaSource.AvailableBitrates);
InitializeBitrateLists(adaptiveMediaSource);
await UpdatePlaybackBitrateAsync(adaptiveMediaSource.CurrentPlaybackBitrate);
await UpdateDownloadBitrateAsync(adaptiveMediaSource.CurrentDownloadBitrate);
source = MediaSource.CreateFromAdaptiveMediaSource(adaptiveMediaSource);
}
else
{
Log($"Error creating the AdaptiveMediaSource. Status: {result.Status}, ExtendedError.Message: {result.ExtendedError.Message}, ExtendedError.HResult: {result.ExtendedError.HResult.ToString("X8")}");
return null;
}
// We use a helper class that logs all the events for the MediaSource:
mediaSourceLogger = new MediaSourceLogger(LoggerControl, source);
// Save the original Uri.
source.CustomProperties["uri"] = uri.ToString();
// You're likely to put a content tracking id into the CustomProperties.
source.CustomProperties["contentId"] = Guid.NewGuid().ToString();
var mpItem = new MediaPlaybackItem(source);
// We use a helper class that logs all the events for the MediaPlaybackItem:
mediaPlaybackItemLogger = new MediaPlaybackItemLogger(LoggerControl, mpItem);
HideDescriptionOnSmallScreen();
return mpItem;
}
private async void HideDescriptionOnSmallScreen()
{
// On small screens, hide the description text to make room for the video.
await this.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
{
DescriptionText.Visibility = (ActualHeight < 500) ? Visibility.Collapsed : Visibility.Visible;
});
}
#endregion
#region Adaptive Bitrate control
private void InitializeBitrateLists(AdaptiveMediaSource aMS)
{
var sortedBitrates = aMS.AvailableBitrates.OrderByDescending(br => br).Select(br => new BitrateItem(br)).ToArray();
InitialBitrateList.ItemsSource = sortedBitrates;
var selected = sortedBitrates.First(item => item.Bitrate == aMS.InitialBitrate);
InitialBitrateList.SelectedItem = sortedBitrates.FirstOrDefault(item => item.Bitrate == aMS.InitialBitrate);
var nullableSortedBitrates = (new BitrateItem[] { new BitrateItem(null) }).Concat(sortedBitrates).ToArray();
DesiredMaxBitrateList.ItemsSource = DesiredMinBitrateList.ItemsSource = nullableSortedBitrates;
DesiredMaxBitrateList.SelectedItem = nullableSortedBitrates.First(item => item.Bitrate == aMS.DesiredMaxBitrate);
DesiredMinBitrateList.SelectedItem = nullableSortedBitrates.First(item => item.Bitrate == aMS.DesiredMinBitrate);
}
// An argument exception will be thrown if the following constraint is not met:
// DesiredMinBitrate <= InitialBitrate <= DesiredMaxBitrate
private bool IsValidBitrateCombination(uint? desiredMinBitrate, uint? desiredMaxBitrate, uint initialBitrate)
{
// The ">" operator returns false if either operand is null. We take advantage of this
// by testing in this manner. Do NOT "optimize" this by reversing the sense of the test
// to "return desiredMinBitrate <= initialBitrate && initialBitrate <= desiredMaxBitrate;"
if (desiredMinBitrate > initialBitrate || initialBitrate > desiredMaxBitrate)
{
return false;
}
return true;
}
private void InitialBitrateList_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
var selection = (e.AddedItems.Count > 0) ? (BitrateItem)e.AddedItems[0] : null;
if (selection != null && adaptiveMediaSource.InitialBitrate != selection.Bitrate)
{
if (IsValidBitrateCombination(adaptiveMediaSource.DesiredMinBitrate, adaptiveMediaSource.DesiredMaxBitrate, selection.Bitrate.Value))
{
adaptiveMediaSource.InitialBitrate = selection.Bitrate.Value;
}
else
{
InitialBitrateList.SelectedItem = e.RemovedItems[0];
}
}
}
private void DesiredMinBitrateList_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
var selection = (e.AddedItems.Count > 0) ? (BitrateItem)e.AddedItems[0] : null;
if (selection != null && adaptiveMediaSource.DesiredMinBitrate != selection.Bitrate)
{
if (IsValidBitrateCombination(selection.Bitrate, adaptiveMediaSource.DesiredMaxBitrate, adaptiveMediaSource.InitialBitrate))
{
adaptiveMediaSource.DesiredMinBitrate = selection.Bitrate;
}
else
{
DesiredMinBitrateList.SelectedItem = e.RemovedItems[0];
}
}
}
private void DesiredMaxBitrateList_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
var selection = (e.AddedItems.Count > 0) ? (BitrateItem)e.AddedItems[0] : null;
if (selection != null && adaptiveMediaSource.DesiredMaxBitrate != selection.Bitrate)
{
if (IsValidBitrateCombination(adaptiveMediaSource.DesiredMinBitrate, selection.Bitrate, adaptiveMediaSource.InitialBitrate))
{
adaptiveMediaSource.DesiredMaxBitrate = selection.Bitrate;
}
else
{
DesiredMaxBitrateList.SelectedItem = e.RemovedItems[0];
}
}
}
private void SetBitrateDowngradeTriggerRatio_Click()
{
double ratio;
if (double.TryParse(BitrateDowngradeTriggerRatioText.Text, out ratio))
{
adaptiveMediaSource.AdvancedSettings.BitrateDowngradeTriggerRatio = ratio;
}
}
private void SetDesiredBitrateHeadroomRatio_Click()
{
double ratio;
if (double.TryParse(BitrateDowngradeTriggerRatioText.Text, out ratio))
{
adaptiveMediaSource.AdvancedSettings.DesiredBitrateHeadroomRatio = ratio;
}
}
#endregion
#region AdaptiveMediaSource Event Handlers
private void RegisterForAdaptiveMediaSourceEvents(AdaptiveMediaSource adaptiveMediaSource)
{
adaptiveMediaSource.DownloadBitrateChanged += DownloadBitrateChanged;
adaptiveMediaSource.PlaybackBitrateChanged += PlaybackBitrateChanged;
}
private void UnregisterForAdaptiveMediaSourceEvents(AdaptiveMediaSource adaptiveMediaSource)
{
if (adaptiveMediaSource != null)
{
adaptiveMediaSource.DownloadBitrateChanged -= DownloadBitrateChanged;
adaptiveMediaSource.PlaybackBitrateChanged -= PlaybackBitrateChanged;
}
}
private async void DownloadBitrateChanged(AdaptiveMediaSource sender, AdaptiveMediaSourceDownloadBitrateChangedEventArgs args)
{
uint downloadBitrate = args.NewValue;
await UpdateDownloadBitrateAsync(downloadBitrate);
}
private async Task UpdateDownloadBitrateAsync(uint downloadBitrate)
{
await this.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, new DispatchedHandler(() =>
{
iconDownloadBitrate.Symbol = bitrateHelper.GetBitrateSymbol(downloadBitrate);
txtDownloadBitrate.Text = downloadBitrate.ToString();
}));
}
private async void PlaybackBitrateChanged(AdaptiveMediaSource sender, AdaptiveMediaSourcePlaybackBitrateChangedEventArgs args)
{
uint playbackBitrate = args.NewValue;
await UpdatePlaybackBitrateAsync(playbackBitrate);
}
private async Task UpdatePlaybackBitrateAsync(uint playbackBitrate)
{
await this.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, new DispatchedHandler(() =>
{
iconPlaybackBitrate.Symbol = bitrateHelper.GetBitrateSymbol(playbackBitrate);
txtPlaybackBitrate.Text = playbackBitrate.ToString();
}));
}
#endregion
#region Utilities
private void Log(string message)
{
LoggerControl.Log(message);
}
MediaPlayerLogger mediaPlayerLogger;
MediaSourceLogger mediaSourceLogger;
MediaPlaybackItemLogger mediaPlaybackItemLogger;
AdaptiveMediaSourceLogger adaptiveMediaSourceLogger;
#endregion
}
/// <summary>
/// Item which provides a nicer display name for "null" bitrate.
/// </summary>
class BitrateItem
{
public uint? Bitrate { get; private set; }
public BitrateItem(uint? bitrate)
{
Bitrate = bitrate;
}
public override string ToString()
{
return (Bitrate == null) ? "Not set" : Bitrate.ToString();
}
}
}
| |
// 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.Text;
using System.Diagnostics;
using System.Globalization;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using Internal.Cryptography;
using Internal.Cryptography.Pal.Native;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
namespace Internal.Cryptography.Pal
{
/// <summary>
/// A singleton class that encapsulates the native implementation of various X509 services. (Implementing this as a singleton makes it
/// easier to split the class into abstract and implementation classes if desired.)
/// </summary>
internal sealed partial class X509Pal : IX509Pal
{
public byte[] EncodeX509KeyUsageExtension(X509KeyUsageFlags keyUsages)
{
unsafe
{
ushort keyUsagesAsShort = (ushort)keyUsages;
CRYPT_BIT_BLOB blob = new CRYPT_BIT_BLOB()
{
cbData = 2,
pbData = (byte*)&keyUsagesAsShort,
cUnusedBits = 0,
};
return Interop.crypt32.EncodeObject(CryptDecodeObjectStructType.X509_KEY_USAGE, &blob);
}
}
public void DecodeX509KeyUsageExtension(byte[] encoded, out X509KeyUsageFlags keyUsages)
{
unsafe
{
uint keyUsagesAsUint = 0;
encoded.DecodeObject(
CryptDecodeObjectStructType.X509_KEY_USAGE,
delegate (void* pvDecoded)
{
CRYPT_BIT_BLOB* pBlob = (CRYPT_BIT_BLOB*)pvDecoded;
keyUsagesAsUint = 0;
if (pBlob->pbData != null)
{
keyUsagesAsUint = *(uint*)(pBlob->pbData);
}
}
);
keyUsages = (X509KeyUsageFlags)keyUsagesAsUint;
}
}
public bool SupportsLegacyBasicConstraintsExtension
{
get { return true; }
}
public byte[] EncodeX509BasicConstraints2Extension(bool certificateAuthority, bool hasPathLengthConstraint, int pathLengthConstraint)
{
unsafe
{
CERT_BASIC_CONSTRAINTS2_INFO constraintsInfo = new CERT_BASIC_CONSTRAINTS2_INFO()
{
fCA = certificateAuthority ? 1 : 0,
fPathLenConstraint = hasPathLengthConstraint ? 1 : 0,
dwPathLenConstraint = pathLengthConstraint,
};
return Interop.crypt32.EncodeObject(Oids.BasicConstraints2, &constraintsInfo);
}
}
public void DecodeX509BasicConstraintsExtension(byte[] encoded, out bool certificateAuthority, out bool hasPathLengthConstraint, out int pathLengthConstraint)
{
unsafe
{
bool localCertificateAuthority = false;
bool localHasPathLengthConstraint = false;
int localPathLengthConstraint = 0;
encoded.DecodeObject(
CryptDecodeObjectStructType.X509_BASIC_CONSTRAINTS,
delegate (void* pvDecoded)
{
CERT_BASIC_CONSTRAINTS_INFO* pBasicConstraints = (CERT_BASIC_CONSTRAINTS_INFO*)pvDecoded;
localCertificateAuthority = (pBasicConstraints->SubjectType.pbData[0] & CERT_BASIC_CONSTRAINTS_INFO.CERT_CA_SUBJECT_FLAG) != 0;
localHasPathLengthConstraint = pBasicConstraints->fPathLenConstraint != 0;
localPathLengthConstraint = pBasicConstraints->dwPathLenConstraint;
}
);
certificateAuthority = localCertificateAuthority;
hasPathLengthConstraint = localHasPathLengthConstraint;
pathLengthConstraint = localPathLengthConstraint;
}
}
public void DecodeX509BasicConstraints2Extension(byte[] encoded, out bool certificateAuthority, out bool hasPathLengthConstraint, out int pathLengthConstraint)
{
unsafe
{
bool localCertificateAuthority = false;
bool localHasPathLengthConstraint = false;
int localPathLengthConstraint = 0;
encoded.DecodeObject(
CryptDecodeObjectStructType.X509_BASIC_CONSTRAINTS2,
delegate (void* pvDecoded)
{
CERT_BASIC_CONSTRAINTS2_INFO* pBasicConstraints2 = (CERT_BASIC_CONSTRAINTS2_INFO*)pvDecoded;
localCertificateAuthority = pBasicConstraints2->fCA != 0;
localHasPathLengthConstraint = pBasicConstraints2->fPathLenConstraint != 0;
localPathLengthConstraint = pBasicConstraints2->dwPathLenConstraint;
}
);
certificateAuthority = localCertificateAuthority;
hasPathLengthConstraint = localHasPathLengthConstraint;
pathLengthConstraint = localPathLengthConstraint;
}
}
public byte[] EncodeX509EnhancedKeyUsageExtension(OidCollection usages)
{
int numUsages;
using (SafeHandle usagesSafeHandle = usages.ToLpstrArray(out numUsages))
{
unsafe
{
CERT_ENHKEY_USAGE enhKeyUsage = new CERT_ENHKEY_USAGE()
{
cUsageIdentifier = numUsages,
rgpszUsageIdentifier = (IntPtr*)(usagesSafeHandle.DangerousGetHandle()),
};
return Interop.crypt32.EncodeObject(Oids.EnhancedKeyUsage, &enhKeyUsage);
}
}
}
public void DecodeX509EnhancedKeyUsageExtension(byte[] encoded, out OidCollection usages)
{
OidCollection localUsages = new OidCollection();
unsafe
{
encoded.DecodeObject(
CryptDecodeObjectStructType.X509_ENHANCED_KEY_USAGE,
delegate (void* pvDecoded)
{
CERT_ENHKEY_USAGE* pEnhKeyUsage = (CERT_ENHKEY_USAGE*)pvDecoded;
int count = pEnhKeyUsage->cUsageIdentifier;
for (int i = 0; i < count; i++)
{
IntPtr oidValuePointer = pEnhKeyUsage->rgpszUsageIdentifier[i];
string oidValue = Marshal.PtrToStringAnsi(oidValuePointer);
Oid oid = new Oid(oidValue);
localUsages.Add(oid);
}
}
);
}
usages = localUsages;
}
public byte[] EncodeX509SubjectKeyIdentifierExtension(byte[] subjectKeyIdentifier)
{
unsafe
{
fixed (byte* pSubkectKeyIdentifier = subjectKeyIdentifier)
{
CRYPTOAPI_BLOB blob = new CRYPTOAPI_BLOB(subjectKeyIdentifier.Length, pSubkectKeyIdentifier);
return Interop.crypt32.EncodeObject(Oids.SubjectKeyIdentifier, &blob);
}
}
}
public void DecodeX509SubjectKeyIdentifierExtension(byte[] encoded, out byte[] subjectKeyIdentifier)
{
unsafe
{
byte[] localSubjectKeyIdentifier = null;
encoded.DecodeObject(
Oids.SubjectKeyIdentifier,
delegate (void* pvDecoded)
{
CRYPTOAPI_BLOB* pBlob = (CRYPTOAPI_BLOB*)pvDecoded;
localSubjectKeyIdentifier = pBlob->ToByteArray();
}
);
subjectKeyIdentifier = localSubjectKeyIdentifier;
}
}
public byte[] ComputeCapiSha1OfPublicKey(PublicKey key)
{
unsafe
{
fixed (byte* pszOidValue = key.Oid.ValueAsAscii())
{
byte[] encodedParameters = key.EncodedParameters.RawData;
fixed (byte* pEncodedParameters = encodedParameters)
{
byte[] encodedKeyValue = key.EncodedKeyValue.RawData;
fixed (byte* pEncodedKeyValue = encodedKeyValue)
{
CERT_PUBLIC_KEY_INFO publicKeyInfo = new CERT_PUBLIC_KEY_INFO()
{
Algorithm = new CRYPT_ALGORITHM_IDENTIFIER()
{
pszObjId = new IntPtr(pszOidValue),
Parameters = new CRYPTOAPI_BLOB(encodedParameters.Length, pEncodedParameters),
},
PublicKey = new CRYPT_BIT_BLOB()
{
cbData = encodedKeyValue.Length,
pbData = pEncodedKeyValue,
cUnusedBits = 0,
},
};
int cb = 20;
byte[] buffer = new byte[cb];
if (!Interop.crypt32.CryptHashPublicKeyInfo(IntPtr.Zero, AlgId.CALG_SHA1, 0, CertEncodingType.All, ref publicKeyInfo, buffer, ref cb))
throw Marshal.GetHRForLastWin32Error().ToCryptographicException();;
if (cb < buffer.Length)
{
byte[] newBuffer = new byte[cb];
Buffer.BlockCopy(buffer, 0, newBuffer, 0, cb);
buffer = newBuffer;
}
return buffer;
}
}
}
}
}
}
}
| |
/*
* Location Intelligence APIs
*
* Incorporate our extensive geodata into everyday applications, business processes and workflows.
*
* OpenAPI spec version: 8.5.0
*
* Generated by: https://github.com/swagger-api/swagger-codegen.git
*
* 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.Linq;
using System.IO;
using System.Text;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Runtime.Serialization;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
namespace pb.locationIntelligence.Model
{
/// <summary>
/// ContactPerson
/// </summary>
[DataContract]
public partial class ContactPerson : IEquatable<ContactPerson>
{
/// <summary>
/// Initializes a new instance of the <see cref="ContactPerson" /> class.
/// </summary>
/// <param name="Title">Title.</param>
/// <param name="FullName">FullName.</param>
/// <param name="Prefix">Prefix.</param>
/// <param name="FirstName">FirstName.</param>
/// <param name="LastName">LastName.</param>
/// <param name="Phone">Phone.</param>
/// <param name="Fax">Fax.</param>
/// <param name="Email">Email.</param>
/// <param name="Comments">Comments.</param>
/// <param name="AdditionalDetails">AdditionalDetails.</param>
public ContactPerson(string Title = null, string FullName = null, string Prefix = null, string FirstName = null, string LastName = null, string Phone = null, string Fax = null, string Email = null, string Comments = null, string AdditionalDetails = null)
{
this.Title = Title;
this.FullName = FullName;
this.Prefix = Prefix;
this.FirstName = FirstName;
this.LastName = LastName;
this.Phone = Phone;
this.Fax = Fax;
this.Email = Email;
this.Comments = Comments;
this.AdditionalDetails = AdditionalDetails;
}
/// <summary>
/// Gets or Sets Title
/// </summary>
[DataMember(Name="title", EmitDefaultValue=false)]
public string Title { get; set; }
/// <summary>
/// Gets or Sets FullName
/// </summary>
[DataMember(Name="fullName", EmitDefaultValue=false)]
public string FullName { get; set; }
/// <summary>
/// Gets or Sets Prefix
/// </summary>
[DataMember(Name="prefix", EmitDefaultValue=false)]
public string Prefix { get; set; }
/// <summary>
/// Gets or Sets FirstName
/// </summary>
[DataMember(Name="firstName", EmitDefaultValue=false)]
public string FirstName { get; set; }
/// <summary>
/// Gets or Sets LastName
/// </summary>
[DataMember(Name="lastName", EmitDefaultValue=false)]
public string LastName { get; set; }
/// <summary>
/// Gets or Sets Phone
/// </summary>
[DataMember(Name="phone", EmitDefaultValue=false)]
public string Phone { get; set; }
/// <summary>
/// Gets or Sets Fax
/// </summary>
[DataMember(Name="fax", EmitDefaultValue=false)]
public string Fax { get; set; }
/// <summary>
/// Gets or Sets Email
/// </summary>
[DataMember(Name="email", EmitDefaultValue=false)]
public string Email { get; set; }
/// <summary>
/// Gets or Sets Comments
/// </summary>
[DataMember(Name="comments", EmitDefaultValue=false)]
public string Comments { get; set; }
/// <summary>
/// Gets or Sets AdditionalDetails
/// </summary>
[DataMember(Name="additionalDetails", EmitDefaultValue=false)]
public string AdditionalDetails { get; set; }
/// <summary>
/// Returns the string presentation of the object
/// </summary>
/// <returns>String presentation of the object</returns>
public override string ToString()
{
var sb = new StringBuilder();
sb.Append("class ContactPerson {\n");
sb.Append(" Title: ").Append(Title).Append("\n");
sb.Append(" FullName: ").Append(FullName).Append("\n");
sb.Append(" Prefix: ").Append(Prefix).Append("\n");
sb.Append(" FirstName: ").Append(FirstName).Append("\n");
sb.Append(" LastName: ").Append(LastName).Append("\n");
sb.Append(" Phone: ").Append(Phone).Append("\n");
sb.Append(" Fax: ").Append(Fax).Append("\n");
sb.Append(" Email: ").Append(Email).Append("\n");
sb.Append(" Comments: ").Append(Comments).Append("\n");
sb.Append(" AdditionalDetails: ").Append(AdditionalDetails).Append("\n");
sb.Append("}\n");
return sb.ToString();
}
/// <summary>
/// Returns the JSON string presentation of the object
/// </summary>
/// <returns>JSON string presentation of the object</returns>
public string ToJson()
{
return JsonConvert.SerializeObject(this, Formatting.Indented);
}
/// <summary>
/// Returns true if objects are equal
/// </summary>
/// <param name="obj">Object to be compared</param>
/// <returns>Boolean</returns>
public override bool Equals(object obj)
{
// credit: http://stackoverflow.com/a/10454552/677735
return this.Equals(obj as ContactPerson);
}
/// <summary>
/// Returns true if ContactPerson instances are equal
/// </summary>
/// <param name="other">Instance of ContactPerson to be compared</param>
/// <returns>Boolean</returns>
public bool Equals(ContactPerson other)
{
// credit: http://stackoverflow.com/a/10454552/677735
if (other == null)
return false;
return
(
this.Title == other.Title ||
this.Title != null &&
this.Title.Equals(other.Title)
) &&
(
this.FullName == other.FullName ||
this.FullName != null &&
this.FullName.Equals(other.FullName)
) &&
(
this.Prefix == other.Prefix ||
this.Prefix != null &&
this.Prefix.Equals(other.Prefix)
) &&
(
this.FirstName == other.FirstName ||
this.FirstName != null &&
this.FirstName.Equals(other.FirstName)
) &&
(
this.LastName == other.LastName ||
this.LastName != null &&
this.LastName.Equals(other.LastName)
) &&
(
this.Phone == other.Phone ||
this.Phone != null &&
this.Phone.Equals(other.Phone)
) &&
(
this.Fax == other.Fax ||
this.Fax != null &&
this.Fax.Equals(other.Fax)
) &&
(
this.Email == other.Email ||
this.Email != null &&
this.Email.Equals(other.Email)
) &&
(
this.Comments == other.Comments ||
this.Comments != null &&
this.Comments.Equals(other.Comments)
) &&
(
this.AdditionalDetails == other.AdditionalDetails ||
this.AdditionalDetails != null &&
this.AdditionalDetails.Equals(other.AdditionalDetails)
);
}
/// <summary>
/// Gets the hash code
/// </summary>
/// <returns>Hash code</returns>
public override int GetHashCode()
{
// credit: http://stackoverflow.com/a/263416/677735
unchecked // Overflow is fine, just wrap
{
int hash = 41;
// Suitable nullity checks etc, of course :)
if (this.Title != null)
hash = hash * 59 + this.Title.GetHashCode();
if (this.FullName != null)
hash = hash * 59 + this.FullName.GetHashCode();
if (this.Prefix != null)
hash = hash * 59 + this.Prefix.GetHashCode();
if (this.FirstName != null)
hash = hash * 59 + this.FirstName.GetHashCode();
if (this.LastName != null)
hash = hash * 59 + this.LastName.GetHashCode();
if (this.Phone != null)
hash = hash * 59 + this.Phone.GetHashCode();
if (this.Fax != null)
hash = hash * 59 + this.Fax.GetHashCode();
if (this.Email != null)
hash = hash * 59 + this.Email.GetHashCode();
if (this.Comments != null)
hash = hash * 59 + this.Comments.GetHashCode();
if (this.AdditionalDetails != null)
hash = hash * 59 + this.AdditionalDetails.GetHashCode();
return hash;
}
}
}
}
| |
namespace Ocelot.UnitTests.Requester
{
using Microsoft.Extensions.DependencyInjection;
using Moq;
using Ocelot.Configuration;
using Ocelot.Configuration.Builder;
using Ocelot.Logging;
using Ocelot.Requester;
using Ocelot.Requester.QoS;
using Ocelot.Responses;
using Responder;
using Shouldly;
using System;
using System.Collections.Generic;
using System.Net.Http;
using TestStack.BDDfy;
using Xunit;
public class DelegatingHandlerHandlerProviderFactoryTests
{
private DelegatingHandlerHandlerFactory _factory;
private readonly Mock<IOcelotLoggerFactory> _loggerFactory;
private readonly Mock<IOcelotLogger> _logger;
private DownstreamReRoute _downstreamReRoute;
private Response<List<Func<DelegatingHandler>>> _result;
private readonly Mock<IQoSFactory> _qosFactory;
private readonly Mock<ITracingHandlerFactory> _tracingFactory;
private IServiceProvider _serviceProvider;
private readonly IServiceCollection _services;
private readonly QosDelegatingHandlerDelegate _qosDelegate;
public DelegatingHandlerHandlerProviderFactoryTests()
{
_qosDelegate = (a, b) => new FakeQoSHandler();
_tracingFactory = new Mock<ITracingHandlerFactory>();
_qosFactory = new Mock<IQoSFactory>();
_loggerFactory = new Mock<IOcelotLoggerFactory>();
_logger = new Mock<IOcelotLogger>();
_loggerFactory.Setup(x => x.CreateLogger<DelegatingHandlerHandlerFactory>()).Returns(_logger.Object);
_services = new ServiceCollection();
_services.AddSingleton(_qosDelegate);
}
[Fact]
public void should_follow_ordering_add_specifics()
{
var qosOptions = new QoSOptionsBuilder()
.WithTimeoutValue(1)
.WithDurationOfBreak(1)
.WithExceptionsAllowedBeforeBreaking(1)
.Build();
var reRoute = new DownstreamReRouteBuilder()
.WithQosOptions(qosOptions)
.WithHttpHandlerOptions(new HttpHandlerOptions(true, true, true, true, int.MaxValue))
.WithDelegatingHandlers(new List<string>
{
"FakeDelegatingHandler",
"FakeDelegatingHandlerTwo"
})
.WithLoadBalancerKey("")
.Build();
this.Given(x => GivenTheFollowingRequest(reRoute))
.And(x => GivenTheQosFactoryReturns(new FakeQoSHandler()))
.And(x => GivenTheTracingFactoryReturns())
.And(x => GivenTheServiceProviderReturnsGlobalDelegatingHandlers<FakeDelegatingHandlerThree, FakeDelegatingHandlerFour>())
.And(x => GivenTheServiceProviderReturnsSpecificDelegatingHandlers<FakeDelegatingHandler, FakeDelegatingHandlerTwo>())
.When(x => WhenIGet())
.Then(x => ThenThereIsDelegatesInProvider(6))
.And(x => ThenHandlerAtPositionIs<FakeDelegatingHandlerThree>(0))
.And(x => ThenHandlerAtPositionIs<FakeDelegatingHandlerFour>(1))
.And(x => ThenHandlerAtPositionIs<FakeDelegatingHandler>(2))
.And(x => ThenHandlerAtPositionIs<FakeDelegatingHandlerTwo>(3))
.And(x => ThenHandlerAtPositionIs<FakeTracingHandler>(4))
.And(x => ThenHandlerAtPositionIs<FakeQoSHandler>(5))
.BDDfy();
}
[Fact]
public void should_follow_ordering_order_specifics_and_globals()
{
var qosOptions = new QoSOptionsBuilder()
.WithTimeoutValue(1)
.WithDurationOfBreak(1)
.WithExceptionsAllowedBeforeBreaking(1)
.Build();
var reRoute = new DownstreamReRouteBuilder()
.WithQosOptions(qosOptions)
.WithHttpHandlerOptions(new HttpHandlerOptions(true, true, true, true, int.MaxValue))
.WithDelegatingHandlers(new List<string>
{
"FakeDelegatingHandlerTwo",
"FakeDelegatingHandler",
"FakeDelegatingHandlerFour"
})
.WithLoadBalancerKey("")
.Build();
this.Given(x => GivenTheFollowingRequest(reRoute))
.And(x => GivenTheQosFactoryReturns(new FakeQoSHandler()))
.And(x => GivenTheTracingFactoryReturns())
.And(x => GivenTheServiceProviderReturnsGlobalDelegatingHandlers<FakeDelegatingHandlerFour, FakeDelegatingHandlerThree>())
.And(x => GivenTheServiceProviderReturnsSpecificDelegatingHandlers<FakeDelegatingHandler, FakeDelegatingHandlerTwo>())
.When(x => WhenIGet())
.Then(x => ThenThereIsDelegatesInProvider(6))
.And(x => ThenHandlerAtPositionIs<FakeDelegatingHandlerThree>(0)) //first because global not in config
.And(x => ThenHandlerAtPositionIs<FakeDelegatingHandlerTwo>(1)) //first from config
.And(x => ThenHandlerAtPositionIs<FakeDelegatingHandler>(2)) //second from config
.And(x => ThenHandlerAtPositionIs<FakeDelegatingHandlerFour>(3)) //third from config (global)
.And(x => ThenHandlerAtPositionIs<FakeTracingHandler>(4))
.And(x => ThenHandlerAtPositionIs<FakeQoSHandler>(5))
.BDDfy();
}
[Fact]
public void should_follow_ordering_order_specifics()
{
var qosOptions = new QoSOptionsBuilder()
.WithTimeoutValue(1)
.WithDurationOfBreak(1)
.WithExceptionsAllowedBeforeBreaking(1)
.Build();
var reRoute = new DownstreamReRouteBuilder()
.WithQosOptions(qosOptions)
.WithHttpHandlerOptions(new HttpHandlerOptions(true, true, true, true, int.MaxValue))
.WithDelegatingHandlers(new List<string>
{
"FakeDelegatingHandlerTwo",
"FakeDelegatingHandler"
})
.WithLoadBalancerKey("")
.Build();
this.Given(x => GivenTheFollowingRequest(reRoute))
.And(x => GivenTheQosFactoryReturns(new FakeQoSHandler()))
.And(x => GivenTheTracingFactoryReturns())
.And(x => GivenTheServiceProviderReturnsGlobalDelegatingHandlers<FakeDelegatingHandlerThree, FakeDelegatingHandlerFour>())
.And(x => GivenTheServiceProviderReturnsSpecificDelegatingHandlers<FakeDelegatingHandler, FakeDelegatingHandlerTwo>())
.When(x => WhenIGet())
.Then(x => ThenThereIsDelegatesInProvider(6))
.And(x => ThenHandlerAtPositionIs<FakeDelegatingHandlerThree>(0))
.And(x => ThenHandlerAtPositionIs<FakeDelegatingHandlerFour>(1))
.And(x => ThenHandlerAtPositionIs<FakeDelegatingHandlerTwo>(2))
.And(x => ThenHandlerAtPositionIs<FakeDelegatingHandler>(3))
.And(x => ThenHandlerAtPositionIs<FakeTracingHandler>(4))
.And(x => ThenHandlerAtPositionIs<FakeQoSHandler>(5))
.BDDfy();
}
[Fact]
public void should_follow_ordering_order_and_only_add_specifics_in_config()
{
var qosOptions = new QoSOptionsBuilder()
.WithTimeoutValue(1)
.WithDurationOfBreak(1)
.WithExceptionsAllowedBeforeBreaking(1)
.Build();
var reRoute = new DownstreamReRouteBuilder()
.WithQosOptions(qosOptions)
.WithHttpHandlerOptions(new HttpHandlerOptions(true, true, true, true, int.MaxValue))
.WithDelegatingHandlers(new List<string>
{
"FakeDelegatingHandler",
})
.WithLoadBalancerKey("")
.Build();
this.Given(x => GivenTheFollowingRequest(reRoute))
.And(x => GivenTheQosFactoryReturns(new FakeQoSHandler()))
.And(x => GivenTheTracingFactoryReturns())
.And(x => GivenTheServiceProviderReturnsGlobalDelegatingHandlers<FakeDelegatingHandlerThree, FakeDelegatingHandlerFour>())
.And(x => GivenTheServiceProviderReturnsSpecificDelegatingHandlers<FakeDelegatingHandler, FakeDelegatingHandlerTwo>())
.When(x => WhenIGet())
.Then(x => ThenThereIsDelegatesInProvider(5))
.And(x => ThenHandlerAtPositionIs<FakeDelegatingHandlerThree>(0))
.And(x => ThenHandlerAtPositionIs<FakeDelegatingHandlerFour>(1))
.And(x => ThenHandlerAtPositionIs<FakeDelegatingHandler>(2))
.And(x => ThenHandlerAtPositionIs<FakeTracingHandler>(3))
.And(x => ThenHandlerAtPositionIs<FakeQoSHandler>(4))
.BDDfy();
}
[Fact]
public void should_follow_ordering_dont_add_specifics()
{
var qosOptions = new QoSOptionsBuilder()
.WithTimeoutValue(1)
.WithDurationOfBreak(1)
.WithExceptionsAllowedBeforeBreaking(1)
.Build();
var reRoute = new DownstreamReRouteBuilder()
.WithQosOptions(qosOptions)
.WithHttpHandlerOptions(new HttpHandlerOptions(true, true, true, true, int.MaxValue))
.WithLoadBalancerKey("")
.Build();
this.Given(x => GivenTheFollowingRequest(reRoute))
.And(x => GivenTheQosFactoryReturns(new FakeQoSHandler()))
.And(x => GivenTheTracingFactoryReturns())
.And(x => GivenTheServiceProviderReturnsGlobalDelegatingHandlers<FakeDelegatingHandler, FakeDelegatingHandlerTwo>())
.And(x => GivenTheServiceProviderReturnsSpecificDelegatingHandlers<FakeDelegatingHandler, FakeDelegatingHandlerTwo>())
.When(x => WhenIGet())
.Then(x => ThenThereIsDelegatesInProvider(4))
.And(x => ThenHandlerAtPositionIs<FakeDelegatingHandler>(0))
.And(x => ThenHandlerAtPositionIs<FakeDelegatingHandlerTwo>(1))
.And(x => ThenHandlerAtPositionIs<FakeTracingHandler>(2))
.And(x => ThenHandlerAtPositionIs<FakeQoSHandler>(3))
.BDDfy();
}
[Fact]
public void should_apply_re_route_specific()
{
var qosOptions = new QoSOptionsBuilder()
.Build();
var reRoute = new DownstreamReRouteBuilder()
.WithQosOptions(qosOptions)
.WithHttpHandlerOptions(new HttpHandlerOptions(true, true, false, true, int.MaxValue))
.WithDelegatingHandlers(new List<string>
{
"FakeDelegatingHandler",
"FakeDelegatingHandlerTwo"
})
.WithLoadBalancerKey("")
.Build();
this.Given(x => GivenTheFollowingRequest(reRoute))
.And(x => GivenTheServiceProviderReturnsSpecificDelegatingHandlers<FakeDelegatingHandler, FakeDelegatingHandlerTwo>())
.When(x => WhenIGet())
.Then(x => ThenThereIsDelegatesInProvider(2))
.And(x => ThenTheDelegatesAreAddedCorrectly())
.BDDfy();
}
[Fact]
public void should_all_from_all_routes_provider_and_qos()
{
var qosOptions = new QoSOptionsBuilder()
.WithTimeoutValue(1)
.WithDurationOfBreak(1)
.WithExceptionsAllowedBeforeBreaking(1)
.Build();
var reRoute = new DownstreamReRouteBuilder()
.WithQosOptions(qosOptions)
.WithHttpHandlerOptions(new HttpHandlerOptions(true, true, false, true, int.MaxValue)).WithLoadBalancerKey("").Build();
this.Given(x => GivenTheFollowingRequest(reRoute))
.And(x => GivenTheQosFactoryReturns(new FakeQoSHandler()))
.And(x => GivenTheServiceProviderReturnsGlobalDelegatingHandlers<FakeDelegatingHandler, FakeDelegatingHandlerTwo>())
.When(x => WhenIGet())
.Then(x => ThenThereIsDelegatesInProvider(3))
.And(x => ThenTheDelegatesAreAddedCorrectly())
.And(x => ThenItIsQosHandler(2))
.BDDfy();
}
[Fact]
public void should_return_provider_with_no_delegates()
{
var qosOptions = new QoSOptionsBuilder()
.Build();
var reRoute = new DownstreamReRouteBuilder()
.WithQosOptions(qosOptions)
.WithHttpHandlerOptions(new HttpHandlerOptions(true, true, false, true, int.MaxValue)).WithLoadBalancerKey("").Build();
this.Given(x => GivenTheFollowingRequest(reRoute))
.And(x => GivenTheServiceProviderReturnsNothing())
.When(x => WhenIGet())
.Then(x => ThenNoDelegatesAreInTheProvider())
.BDDfy();
}
[Fact]
public void should_return_provider_with_qos_delegate()
{
var qosOptions = new QoSOptionsBuilder()
.WithTimeoutValue(1)
.WithDurationOfBreak(1)
.WithExceptionsAllowedBeforeBreaking(1)
.Build();
var reRoute = new DownstreamReRouteBuilder()
.WithQosOptions(qosOptions)
.WithHttpHandlerOptions(new HttpHandlerOptions(true, true, false, true, int.MaxValue)).WithLoadBalancerKey("").Build();
this.Given(x => GivenTheFollowingRequest(reRoute))
.And(x => GivenTheQosFactoryReturns(new FakeQoSHandler()))
.And(x => GivenTheServiceProviderReturnsNothing())
.When(x => WhenIGet())
.Then(x => ThenThereIsDelegatesInProvider(1))
.And(x => ThenItIsQosHandler(0))
.BDDfy();
}
[Fact]
public void should_return_provider_with_qos_delegate_when_timeout_value_set()
{
var qosOptions = new QoSOptionsBuilder()
.WithTimeoutValue(1)
.Build();
var reRoute = new DownstreamReRouteBuilder()
.WithQosOptions(qosOptions)
.WithHttpHandlerOptions(new HttpHandlerOptions(true, true, false, true, int.MaxValue)).WithLoadBalancerKey("").Build();
this.Given(x => GivenTheFollowingRequest(reRoute))
.And(x => GivenTheQosFactoryReturns(new FakeQoSHandler()))
.And(x => GivenTheServiceProviderReturnsNothing())
.When(x => WhenIGet())
.Then(x => ThenThereIsDelegatesInProvider(1))
.And(x => ThenItIsQosHandler(0))
.BDDfy();
}
[Fact]
public void should_log_error_and_return_no_qos_provider_delegate_when_qos_factory_returns_error()
{
var qosOptions = new QoSOptionsBuilder()
.WithTimeoutValue(1)
.WithDurationOfBreak(1)
.WithExceptionsAllowedBeforeBreaking(1)
.Build();
var reRoute = new DownstreamReRouteBuilder()
.WithQosOptions(qosOptions)
.WithHttpHandlerOptions(new HttpHandlerOptions(true, true, true, true, int.MaxValue))
.WithLoadBalancerKey("")
.Build();
this.Given(x => GivenTheFollowingRequest(reRoute))
.And(x => GivenTheQosFactoryReturnsError())
.And(x => GivenTheTracingFactoryReturns())
.And(x => GivenTheServiceProviderReturnsGlobalDelegatingHandlers<FakeDelegatingHandler, FakeDelegatingHandlerTwo>())
.And(x => GivenTheServiceProviderReturnsSpecificDelegatingHandlers<FakeDelegatingHandler, FakeDelegatingHandlerTwo>())
.When(x => WhenIGet())
.Then(x => ThenThereIsDelegatesInProvider(4))
.And(x => ThenHandlerAtPositionIs<FakeDelegatingHandler>(0))
.And(x => ThenHandlerAtPositionIs<FakeDelegatingHandlerTwo>(1))
.And(x => ThenHandlerAtPositionIs<FakeTracingHandler>(2))
.And(x => ThenHandlerAtPositionIs<NoQosDelegatingHandler>(3))
.And(_ => ThenTheWarningIsLogged())
.BDDfy();
}
[Fact]
public void should_log_error_and_return_no_qos_provider_delegate_when_qos_factory_returns_null()
{
var qosOptions = new QoSOptionsBuilder()
.WithTimeoutValue(1)
.WithDurationOfBreak(1)
.WithExceptionsAllowedBeforeBreaking(1)
.Build();
var reRoute = new DownstreamReRouteBuilder()
.WithQosOptions(qosOptions)
.WithHttpHandlerOptions(new HttpHandlerOptions(true, true, true, true, int.MaxValue))
.WithLoadBalancerKey("")
.Build();
this.Given(x => GivenTheFollowingRequest(reRoute))
.And(x => GivenTheQosFactoryReturnsNull())
.And(x => GivenTheTracingFactoryReturns())
.And(x => GivenTheServiceProviderReturnsGlobalDelegatingHandlers<FakeDelegatingHandler, FakeDelegatingHandlerTwo>())
.And(x => GivenTheServiceProviderReturnsSpecificDelegatingHandlers<FakeDelegatingHandler, FakeDelegatingHandlerTwo>())
.When(x => WhenIGet())
.Then(x => ThenThereIsDelegatesInProvider(4))
.And(x => ThenHandlerAtPositionIs<FakeDelegatingHandler>(0))
.And(x => ThenHandlerAtPositionIs<FakeDelegatingHandlerTwo>(1))
.And(x => ThenHandlerAtPositionIs<FakeTracingHandler>(2))
.And(x => ThenHandlerAtPositionIs<NoQosDelegatingHandler>(3))
.And(_ => ThenTheWarningIsLogged())
.BDDfy();
}
private void ThenTheWarningIsLogged()
{
_logger.Verify(x => x.LogWarning($"ReRoute {_downstreamReRoute.UpstreamPathTemplate} specifies use QoS but no QosHandler found in DI container. Will use not use a QosHandler, please check your setup!"), Times.Once);
}
private void ThenHandlerAtPositionIs<T>(int pos)
where T : DelegatingHandler
{
var delegates = _result.Data;
var del = delegates[pos].Invoke();
del.ShouldBeOfType<T>();
}
private void GivenTheTracingFactoryReturns()
{
_tracingFactory
.Setup(x => x.Get())
.Returns(new FakeTracingHandler());
}
private void GivenTheServiceProviderReturnsGlobalDelegatingHandlers<TOne, TTwo>()
where TOne : DelegatingHandler
where TTwo : DelegatingHandler
{
_services.AddTransient<TOne>();
_services.AddTransient<GlobalDelegatingHandler>(s =>
{
var service = s.GetService<TOne>();
return new GlobalDelegatingHandler(service);
});
_services.AddTransient<TTwo>();
_services.AddTransient<GlobalDelegatingHandler>(s =>
{
var service = s.GetService<TTwo>();
return new GlobalDelegatingHandler(service);
});
}
private void GivenTheServiceProviderReturnsSpecificDelegatingHandlers<TOne, TTwo>()
where TOne : DelegatingHandler
where TTwo : DelegatingHandler
{
_services.AddTransient<DelegatingHandler, TOne>();
_services.AddTransient<DelegatingHandler, TTwo>();
}
private void GivenTheServiceProviderReturnsNothing()
{
_serviceProvider = _services.BuildServiceProvider();
}
private void ThenAnErrorIsReturned()
{
_result.IsError.ShouldBeTrue();
}
private void ThenTheDelegatesAreAddedCorrectly()
{
var delegates = _result.Data;
var del = delegates[0].Invoke();
var handler = (FakeDelegatingHandler)del;
handler.Order.ShouldBe(1);
del = delegates[1].Invoke();
var handlerTwo = (FakeDelegatingHandlerTwo)del;
handlerTwo.Order.ShouldBe(2);
}
private void GivenTheQosFactoryReturns(DelegatingHandler handler)
{
_qosFactory
.Setup(x => x.Get(It.IsAny<DownstreamReRoute>()))
.Returns(new OkResponse<DelegatingHandler>(handler));
}
private void GivenTheQosFactoryReturnsError()
{
_qosFactory
.Setup(x => x.Get(It.IsAny<DownstreamReRoute>()))
.Returns(new ErrorResponse<DelegatingHandler>(new AnyError()));
}
private void GivenTheQosFactoryReturnsNull()
{
_qosFactory
.Setup(x => x.Get(It.IsAny<DownstreamReRoute>()))
.Returns((ErrorResponse<DelegatingHandler>)null);
}
private void ThenItIsQosHandler(int i)
{
var delegates = _result.Data;
var del = delegates[i].Invoke();
del.ShouldBeOfType<FakeQoSHandler>();
}
private void ThenThereIsDelegatesInProvider(int count)
{
_result.ShouldNotBeNull();
_result.Data.Count.ShouldBe(count);
}
private void GivenTheFollowingRequest(DownstreamReRoute request)
{
_downstreamReRoute = request;
}
private void WhenIGet()
{
_serviceProvider = _services.BuildServiceProvider();
_factory = new DelegatingHandlerHandlerFactory(_tracingFactory.Object, _qosFactory.Object, _serviceProvider, _loggerFactory.Object);
_result = _factory.Get(_downstreamReRoute);
}
private void ThenNoDelegatesAreInTheProvider()
{
_result.ShouldNotBeNull();
_result.Data.Count.ShouldBe(0);
}
}
internal class FakeTracingHandler : DelegatingHandler, ITracingHandler
{
}
internal class FakeQoSHandler : DelegatingHandler
{
}
}
| |
#region License
// Copyright (c) Jeremy Skinner (http://www.jeremyskinner.co.uk)
//
// 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.
//
// The latest version of this file can be found at http://www.codeplex.com/FluentValidation
#endregion
namespace FluentValidation {
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq.Expressions;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using Internal;
using Results;
using Validators;
/// <summary>
/// Extension methods that provide the default set of validators.
/// </summary>
public static class DefaultValidatorExtensions {
/// <summary>
/// Defines a 'not null' validator on the current rule builder.
/// Validation will fail if the property is null.
/// </summary>
/// <typeparam name="T">Type of object being validated</typeparam>
/// <typeparam name="TProperty">Type of property being validated</typeparam>
/// <param name="ruleBuilder">The rule builder on which the validator should be defined</param>
/// <returns></returns>
public static IRuleBuilderOptions<T, TProperty> NotNull<T, TProperty>(this IRuleBuilder<T, TProperty> ruleBuilder) {
return ruleBuilder.SetValidator(new NotNullValidator());
}
/// <summary>
/// Defines a 'not empty' validator on the current rule builder.
/// Validation will fail if the property is null, an empty or the default value for the type (for example, 0 for integers)
/// </summary>
/// <typeparam name="T">Type of object being validated</typeparam>
/// <typeparam name="TProperty">Type of property being validated</typeparam>
/// <param name="ruleBuilder">The rule builder on which the validator should be defined</param>
/// <returns></returns>
public static IRuleBuilderOptions<T, TProperty> NotEmpty<T, TProperty>(this IRuleBuilder<T, TProperty> ruleBuilder) {
return ruleBuilder.SetValidator(new NotEmptyValidator(default(TProperty)));
}
/// <summary>
/// Defines a length validator on the current rule builder, but only for string properties.
/// Validation will fail if the length of the string is outside of the specifed range. The range is inclusive.
/// </summary>
/// <typeparam name="T">Type of object being validated</typeparam>
/// <param name="ruleBuilder">The rule builder on which the validator should be defined</param>
/// <returns></returns>
public static IRuleBuilderOptions<T, string> Length<T>(this IRuleBuilder<T, string> ruleBuilder, int min, int max) {
return ruleBuilder.SetValidator(new LengthValidator(min, max));
}
/// <summary>
/// Defines a length validator on the current rule builder, but only for string properties.
/// Validation will fail if the length of the string is not equal to the length specified.
/// </summary>
/// <typeparam name="T">Type of object being validated</typeparam>
/// <param name="ruleBuilder">The rule builder on which the validator should be defined</param>
/// <returns></returns>
public static IRuleBuilderOptions<T, string> Length<T>(this IRuleBuilder<T, string> ruleBuilder, int exactLength) {
return ruleBuilder.SetValidator(new ExactLengthValidator(exactLength));
}
/// <summary>
/// Defines a regular expression validator on the current rule builder, but only for string properties.
/// Validation will fail if the value returned by the lambda does not match the regular expression.
/// </summary>
/// <typeparam name="T">Type of object being validated</typeparam>
/// <param name="ruleBuilder">The rule builder on which the validator should be defined</param>
/// <param name="expression">The regular expression to check the value against.</param>
/// <returns></returns>
public static IRuleBuilderOptions<T, string> Matches<T>(this IRuleBuilder<T, string> ruleBuilder, string expression) {
return ruleBuilder.SetValidator(new RegularExpressionValidator(expression));
}
/// <summary>
/// Defines a regular expression validator on the current rule builder, but only for string properties.
/// Validation will fail if the value returned by the lambda does not match the regular expression.
/// </summary>
/// <typeparam name="T">Type of object being validated</typeparam>
/// <param name="ruleBuilder">The rule builder on which the validator should be defined</param>
/// <param name="regex">The regular expression to use</param>
/// <returns></returns>
public static IRuleBuilderOptions<T, string> Matches<T>(this IRuleBuilder<T, string> ruleBuilder, Regex regex) {
return ruleBuilder.SetValidator(new RegularExpressionValidator(regex));
}
/// <summary>
/// Defines a regular expression validator on the current rule builder, but only for string properties.
/// Validation will fail if the value returned by the lambda does not match the regular expression.
/// </summary>
/// <typeparam name="T">Type of object being validated</typeparam>
/// <param name="ruleBuilder">The rule builder on which the validator should be defined</param>
/// <param name="expression">The regular expression to check the value against.</param>
/// <param name="options">Regex options</param>
/// <returns></returns>
public static IRuleBuilderOptions<T, string> Matches<T>(this IRuleBuilder<T, string> ruleBuilder, string expression, RegexOptions options) {
return ruleBuilder.SetValidator(new RegularExpressionValidator(expression, options));
}
/// <summary>
/// Defines a regular expression validator on the current rule builder, but only for string properties.
/// Validation will fail if the value returned by the lambda is not a valid email address.
/// </summary>
/// <typeparam name="T">Type of object being validated</typeparam>
/// <param name="ruleBuilder">The rule builder on which the validator should be defined</param>
/// <returns></returns>
public static IRuleBuilderOptions<T, string> EmailAddress<T>(this IRuleBuilder<T, string> ruleBuilder) {
return ruleBuilder.SetValidator(new EmailValidator());
}
/// <summary>
/// Defines a 'not equal' validator on the current rule builder.
/// Validation will fail if the specified value is equal to the value of the property.
/// </summary>
/// <typeparam name="T">Type of object being validated</typeparam>
/// <typeparam name="TProperty">Type of property being validated</typeparam>
/// <param name="ruleBuilder">The rule builder on which the validator should be defined</param>
/// <param name="toCompare">The value to compare</param>
/// <param name="comparer">Equality comparer to use</param>
/// <returns></returns>
public static IRuleBuilderOptions<T, TProperty> NotEqual<T, TProperty>(this IRuleBuilder<T, TProperty> ruleBuilder,
TProperty toCompare, IEqualityComparer comparer = null) {
return ruleBuilder.SetValidator(new NotEqualValidator(toCompare, comparer));
}
/// <summary>
/// Defines a 'not equal' validator on the current rule builder using a lambda to specify the value.
/// Validation will fail if the value returned by the lambda is equal to the value of the property.
/// </summary>
/// <typeparam name="T">Type of object being validated</typeparam>
/// <typeparam name="TProperty">Type of property being validated</typeparam>
/// <param name="ruleBuilder">The rule builder on which the validator should be defined</param>
/// <param name="expression">A lambda expression to provide the comparison value</param>
/// <param name="comparer">Equality Comparer to use</param>
/// <returns></returns>
public static IRuleBuilderOptions<T, TProperty> NotEqual<T, TProperty>(this IRuleBuilder<T, TProperty> ruleBuilder,
Expression<Func<T, TProperty>> expression, IEqualityComparer comparer = null) {
var func = expression.Compile();
return ruleBuilder.SetValidator(new NotEqualValidator(func.CoerceToNonGeneric(), expression.GetMember(), comparer));
}
/// <summary>
/// Defines an 'equals' validator on the current rule builder.
/// Validation will fail if the specified value is not equal to the value of the property.
/// </summary>
/// <typeparam name="T">Type of object being validated</typeparam>
/// <typeparam name="TProperty">Type of property being validated</typeparam>
/// <param name="ruleBuilder">The rule builder on which the validator should be defined</param>
/// <param name="toCompare">The value to compare</param>
/// <param name="comparer">Equality Comparer to use</param>
/// <returns></returns>
public static IRuleBuilderOptions<T, TProperty> Equal<T, TProperty>(this IRuleBuilder<T, TProperty> ruleBuilder, TProperty toCompare, IEqualityComparer comparer = null) {
return ruleBuilder.SetValidator(new EqualValidator(toCompare, comparer));
}
/// <summary>
/// Defines an 'equals' validator on the current rule builder using a lambda to specify the comparison value.
/// Validation will fail if the value returned by the lambda is not equal to the value of the property.
/// </summary>
/// <typeparam name="T">The type of object being validated</typeparam>
/// <typeparam name="TProperty">Type of property being validated</typeparam>
/// <param name="ruleBuilder">The rule builder on which the validator should be defined</param>
/// <param name="expression">A lambda expression to provide the comparison value</param>
/// <param name="comparer">Equality comparer to use</param>
/// <returns></returns>
public static IRuleBuilderOptions<T, TProperty> Equal<T, TProperty>(this IRuleBuilder<T, TProperty> ruleBuilder, Expression<Func<T, TProperty>> expression, IEqualityComparer comparer = null) {
var func = expression.Compile();
return ruleBuilder.SetValidator(new EqualValidator(func.CoerceToNonGeneric(), expression.GetMember(), comparer));
}
/// <summary>
/// Defines a predicate validator on the current rule builder using a lambda expression to specify the predicate.
/// Validation will fail if the specified lambda returns false.
/// Validation will succeed if the specifed lambda returns true.
/// </summary>
/// <typeparam name="T">Type of object being validated</typeparam>
/// <typeparam name="TProperty">Type of property being validated</typeparam>
/// <param name="ruleBuilder">The rule builder on which the validator should be defined</param>
/// <param name="predicate">A lambda expression specifying the predicate</param>
/// <returns></returns>
public static IRuleBuilderOptions<T, TProperty> Must<T, TProperty>(this IRuleBuilder<T, TProperty> ruleBuilder, Func<TProperty, bool> predicate) {
predicate.Guard("Cannot pass a null predicate to Must.");
return ruleBuilder.Must((x, val) => predicate(val));
}
/// <summary>
/// Defines a predicate validator on the current rule builder using a lambda expression to specify the predicate.
/// Validation will fail if the specified lambda returns false.
/// Validation will succeed if the specifed lambda returns true.
/// This overload accepts the object being validated in addition to the property being validated.
/// </summary>
/// <typeparam name="T">Type of object being validated</typeparam>
/// <typeparam name="TProperty">Type of property being validated</typeparam>
/// <param name="ruleBuilder">The rule builder on which the validator should be defined</param>
/// <param name="predicate">A lambda expression specifying the predicate</param>
/// <returns></returns>
public static IRuleBuilderOptions<T, TProperty> Must<T, TProperty>(this IRuleBuilder<T, TProperty> ruleBuilder, Func<T, TProperty, bool> predicate) {
predicate.Guard("Cannot pass a null predicate to Must.");
return ruleBuilder.Must((x, val, propertyValidatorContext) => predicate(x, val));
}
/// <summary>
/// Defines a predicate validator on the current rule builder using a lambda expression to specify the predicate.
/// Validation will fail if the specified lambda returns false.
/// Validation will succeed if the specifed lambda returns true.
/// This overload accepts the object being validated in addition to the property being validated.
/// </summary>
/// <typeparam name="T">Type of object being validated</typeparam>
/// <typeparam name="TProperty">Type of property being validated</typeparam>
/// <param name="ruleBuilder">The rule builder on which the validator should be defined</param>
/// <param name="predicate">A lambda expression specifying the predicate</param>
/// <returns></returns>
public static IRuleBuilderOptions<T, TProperty> Must<T, TProperty>(this IRuleBuilder<T, TProperty> ruleBuilder, Func<T, TProperty, PropertyValidatorContext, bool> predicate) {
predicate.Guard("Cannot pass a null predicate to Must.");
return ruleBuilder.SetValidator(new PredicateValidator((instance, property, propertyValidatorContext) => predicate((T) instance, (TProperty) property, propertyValidatorContext)));
}
/// <summary>
/// Defines an asynchronous predicate validator on the current rule builder using a lambda expression to specify the predicate.
/// Validation will fail if the specified lambda returns false.
/// Validation will succeed if the specifed lambda returns true.
/// </summary>
/// <typeparam name="T">Type of object being validated</typeparam>
/// <typeparam name="TProperty">Type of property being validated</typeparam>
/// <param name="ruleBuilder">The rule builder on which the validator should be defined</param>
/// <param name="predicate">A lambda expression specifying the predicate</param>
/// <returns></returns>
public static IRuleBuilderOptions<T, TProperty> MustAsync<T, TProperty>(this IRuleBuilder<T, TProperty> ruleBuilder, Func<TProperty, Task<bool>> predicate) {
predicate.Guard("Cannot pass a null predicate to Must.");
return ruleBuilder.MustAsync((x, val) => predicate(val));
}
/// <summary>
/// Defines an asynchronous predicate validator on the current rule builder using a lambda expression to specify the predicate.
/// Validation will fail if the specified lambda returns false.
/// Validation will succeed if the specifed lambda returns true.
/// This overload accepts the object being validated in addition to the property being validated.
/// </summary>
/// <typeparam name="T">Type of object being validated</typeparam>
/// <typeparam name="TProperty">Type of property being validated</typeparam>
/// <param name="ruleBuilder">The rule builder on which the validator should be defined</param>
/// <param name="predicate">A lambda expression specifying the predicate</param>
/// <returns></returns>
public static IRuleBuilderOptions<T, TProperty> MustAsync<T, TProperty>(this IRuleBuilder<T, TProperty> ruleBuilder, Func<T, TProperty, Task<bool>> predicate) {
predicate.Guard("Cannot pass a null predicate to Must.");
return ruleBuilder.MustAsync((x, val, propertyValidatorContext) => predicate(x, val));
}
/// <summary>
/// Defines an asynchronous predicate validator on the current rule builder using a lambda expression to specify the predicate.
/// Validation will fail if the specified lambda returns false.
/// Validation will succeed if the specifed lambda returns true.
/// This overload accepts the object being validated in addition to the property being validated.
/// </summary>
/// <typeparam name="T">Type of object being validated</typeparam>
/// <typeparam name="TProperty">Type of property being validated</typeparam>
/// <param name="ruleBuilder">The rule builder on which the validator should be defined</param>
/// <param name="predicate">A lambda expression specifying the predicate</param>
/// <returns></returns>
public static IRuleBuilderOptions<T, TProperty> MustAsync<T, TProperty>(this IRuleBuilder<T, TProperty> ruleBuilder, Func<T, TProperty, PropertyValidatorContext, Task<bool>> predicate) {
predicate.Guard("Cannot pass a null predicate to Must.");
return ruleBuilder.SetValidator(new AsyncPredicateValidator((instance, property, propertyValidatorContext) => predicate((T) instance, (TProperty) property, propertyValidatorContext)));
}
/// <summary>
/// Defines a 'less than' validator on the current rule builder.
/// The validation will succeed if the property value is less than the specified value.
/// The validation will fail if the property value is greater than or equal to the specified value.
/// </summary>
/// <typeparam name="T">Type of object being validated</typeparam>
/// <typeparam name="TProperty">Type of property being validated</typeparam>
/// <param name="ruleBuilder">The rule builder on which the validator should be defined</param>
/// <param name="valueToCompare">The value being compared</param>
/// <returns></returns>
public static IRuleBuilderOptions<T, TProperty> LessThan<T, TProperty>(this IRuleBuilder<T, TProperty> ruleBuilder,
TProperty valueToCompare)
where TProperty : IComparable<TProperty>, IComparable {
return ruleBuilder.SetValidator(new LessThanValidator(valueToCompare));
}
/// <summary>
/// Defines a 'less than' validator on the current rule builder.
/// The validation will succeed if the property value is less than the specified value.
/// The validation will fail if the property value is greater than or equal to the specified value.
/// </summary>
/// <typeparam name="T">Type of object being validated</typeparam>
/// <typeparam name="TProperty">Type of property being validated</typeparam>
/// <param name="ruleBuilder">The rule builder on which the validator should be defined</param>
/// <param name="valueToCompare">The value being compared</param>
/// <returns></returns>
public static IRuleBuilderOptions<T, Nullable<TProperty>> LessThan<T, TProperty>(this IRuleBuilder<T, Nullable<TProperty>> ruleBuilder,
TProperty valueToCompare)
where TProperty : struct, IComparable<TProperty>, IComparable {
return ruleBuilder.SetValidator(new LessThanValidator(valueToCompare));
}
/// <summary>
/// Defines a 'less than or equal' validator on the current rule builder.
/// The validation will succeed if the property value is less than or equal to the specified value.
/// The validation will fail if the property value is greater than the specified value.
/// </summary>
/// <typeparam name="T">Type of object being validated</typeparam>
/// <typeparam name="TProperty">Type of property being validated</typeparam>
/// <param name="ruleBuilder">The rule builder on which the validator should be defined</param>
/// <param name="valueToCompare">The value being compared</param>
/// <returns></returns>
public static IRuleBuilderOptions<T, TProperty> LessThanOrEqualTo<T, TProperty>(
this IRuleBuilder<T, TProperty> ruleBuilder, TProperty valueToCompare) where TProperty : IComparable<TProperty>, IComparable {
return ruleBuilder.SetValidator(new LessThanOrEqualValidator(valueToCompare));
}
/// <summary>
/// Defines a 'less than or equal' validator on the current rule builder.
/// The validation will succeed if the property value is less than or equal to the specified value.
/// The validation will fail if the property value is greater than the specified value.
/// </summary>
/// <typeparam name="T">Type of object being validated</typeparam>
/// <typeparam name="TProperty">Type of property being validated</typeparam>
/// <param name="ruleBuilder">The rule builder on which the validator should be defined</param>
/// <param name="valueToCompare">The value being compared</param>
/// <returns></returns>
public static IRuleBuilderOptions<T, Nullable<TProperty>> LessThanOrEqualTo<T, TProperty>(
this IRuleBuilder<T, Nullable<TProperty>> ruleBuilder, TProperty valueToCompare) where TProperty : struct, IComparable<TProperty>, IComparable {
return ruleBuilder.SetValidator(new LessThanOrEqualValidator(valueToCompare));
}
/// <summary>
/// Defines a 'greater than' validator on the current rule builder.
/// The validation will succeed if the property value is greater than the specified value.
/// The validation will fail if the property value is less than or equal to the specified value.
/// </summary>
/// <typeparam name="T">Type of object being validated</typeparam>
/// <typeparam name="TProperty">Type of property being validated</typeparam>
/// <param name="ruleBuilder">The rule builder on which the validator should be defined</param>
/// <param name="valueToCompare">The value being compared</param>
/// <returns></returns>
public static IRuleBuilderOptions<T, TProperty> GreaterThan<T, TProperty>(this IRuleBuilder<T, TProperty> ruleBuilder, TProperty valueToCompare)
where TProperty : IComparable<TProperty>, IComparable {
return ruleBuilder.SetValidator(new GreaterThanValidator(valueToCompare));
}
/// <summary>
/// Defines a 'greater than' validator on the current rule builder.
/// The validation will succeed if the property value is greater than the specified value.
/// The validation will fail if the property value is less than or equal to the specified value.
/// </summary>
/// <typeparam name="T">Type of object being validated</typeparam>
/// <typeparam name="TProperty">Type of property being validated</typeparam>
/// <param name="ruleBuilder">The rule builder on which the validator should be defined</param>
/// <param name="valueToCompare">The value being compared</param>
/// <returns></returns>
public static IRuleBuilderOptions<T, TProperty?> GreaterThan<T, TProperty>(this IRuleBuilder<T, TProperty?> ruleBuilder, TProperty valueToCompare)
where TProperty : struct, IComparable<TProperty>, IComparable {
return ruleBuilder.SetValidator(new GreaterThanValidator(valueToCompare));
}
/// <summary>
/// Defines a 'greater than or equal' validator on the current rule builder.
/// The validation will succeed if the property value is greater than or equal the specified value.
/// The validation will fail if the property value is less than the specified value.
/// </summary>
/// <typeparam name="T">Type of object being validated</typeparam>
/// <typeparam name="TProperty">Type of property being validated</typeparam>
/// <param name="ruleBuilder">The rule builder on which the validator should be defined</param>
/// <param name="valueToCompare">The value being compared</param>
/// <returns></returns>
public static IRuleBuilderOptions<T, TProperty> GreaterThanOrEqualTo<T, TProperty>(
this IRuleBuilder<T, TProperty> ruleBuilder, TProperty valueToCompare) where TProperty : IComparable<TProperty>, IComparable {
return ruleBuilder.SetValidator(new GreaterThanOrEqualValidator(valueToCompare));
}
/// <summary>
/// Defines a 'greater than or equal' validator on the current rule builder.
/// The validation will succeed if the property value is greater than or equal the specified value.
/// The validation will fail if the property value is less than the specified value.
/// </summary>
/// <typeparam name="T">Type of object being validated</typeparam>
/// <typeparam name="TProperty">Type of property being validated</typeparam>
/// <param name="ruleBuilder">The rule builder on which the validator should be defined</param>
/// <param name="valueToCompare">The value being compared</param>
/// <returns></returns>
public static IRuleBuilderOptions<T, Nullable<TProperty>> GreaterThanOrEqualTo<T, TProperty>(
this IRuleBuilder<T, Nullable<TProperty>> ruleBuilder, TProperty valueToCompare) where TProperty : struct, IComparable<TProperty>, IComparable {
return ruleBuilder.SetValidator(new GreaterThanOrEqualValidator(valueToCompare));
}
/// <summary>
/// Defines a 'less than' validator on the current rule builder using a lambda expression.
/// The validation will succeed if the property value is less than the specified value.
/// The validation will fail if the property value is greater than or equal to the specified value.
/// </summary>
/// <typeparam name="T">Type of object being validated</typeparam>
/// <typeparam name="TProperty">Type of property being validated</typeparam>
/// <param name="ruleBuilder">The rule builder on which the validator should be defined</param>
/// <param name="expression">A lambda that should return the value being compared</param>
/// <returns></returns>
public static IRuleBuilderOptions<T, TProperty> LessThan<T, TProperty>(this IRuleBuilder<T, TProperty> ruleBuilder,
Expression<Func<T, TProperty>> expression)
where TProperty : IComparable<TProperty>, IComparable {
expression.Guard("Cannot pass null to LessThan");
var func = expression.Compile();
return ruleBuilder.SetValidator(new LessThanValidator(func.CoerceToNonGeneric(), expression.GetMember()));
}
/// <summary>
/// Defines a 'less than' validator on the current rule builder using a lambda expression.
/// The validation will succeed if the property value is less than the specified value.
/// The validation will fail if the property value is greater than or equal to the specified value.
/// </summary>
/// <typeparam name="T">Type of object being validated</typeparam>
/// <typeparam name="TProperty">Type of property being validated</typeparam>
/// <param name="ruleBuilder">The rule builder on which the validator should be defined</param>
/// <param name="expression">A lambda that should return the value being compared</param>
/// <returns></returns>
public static IRuleBuilderOptions<T, Nullable<TProperty>> LessThan<T, TProperty>(this IRuleBuilder<T, Nullable<TProperty>> ruleBuilder,
Expression<Func<T, TProperty>> expression)
where TProperty : struct, IComparable<TProperty>, IComparable {
expression.Guard("Cannot pass null to LessThan");
var func = expression.Compile();
return ruleBuilder.SetValidator(new LessThanValidator(func.CoerceToNonGeneric(), expression.GetMember()));
}
/// <summary>
/// Defines a 'less than or equal' validator on the current rule builder using a lambda expression.
/// The validation will succeed if the property value is less than or equal to the specified value.
/// The validation will fail if the property value is greater than the specified value.
/// </summary>
/// <typeparam name="T">Type of object being validated</typeparam>
/// <typeparam name="TProperty">Type of property being validated</typeparam>
/// <param name="ruleBuilder">The rule builder on which the validator should be defined</param>
/// <param name="expression">The value being compared</param>
/// <returns></returns>
public static IRuleBuilderOptions<T, TProperty> LessThanOrEqualTo<T, TProperty>(
this IRuleBuilder<T, TProperty> ruleBuilder, Expression<Func<T, TProperty>> expression)
where TProperty : IComparable<TProperty>, IComparable {
var func = expression.Compile();
return ruleBuilder.SetValidator(new LessThanOrEqualValidator(func.CoerceToNonGeneric(), expression.GetMember()));
}
/// <summary>
/// Defines a 'less than or equal' validator on the current rule builder using a lambda expression.
/// The validation will succeed if the property value is less than or equal to the specified value.
/// The validation will fail if the property value is greater than the specified value.
/// </summary>
/// <typeparam name="T">Type of object being validated</typeparam>
/// <typeparam name="TProperty">Type of property being validated</typeparam>
/// <param name="ruleBuilder">The rule builder on which the validator should be defined</param>
/// <param name="expression">The value being compared</param>
/// <returns></returns>
public static IRuleBuilderOptions<T, Nullable<TProperty>> LessThanOrEqualTo<T, TProperty>(
this IRuleBuilder<T, Nullable<TProperty>> ruleBuilder, Expression<Func<T, TProperty>> expression)
where TProperty : struct, IComparable<TProperty>, IComparable
{
var func = expression.Compile();
return ruleBuilder.SetValidator(new LessThanOrEqualValidator(func.CoerceToNonGeneric(), expression.GetMember()));
}
/// <summary>
/// Defines a 'less than or equal' validator on the current rule builder using a lambda expression.
/// The validation will succeed if the property value is less than or equal to the specified value.
/// The validation will fail if the property value is greater than the specified value.
/// </summary>
/// <typeparam name="T">Type of object being validated</typeparam>
/// <typeparam name="TProperty">Type of property being validated</typeparam>
/// <param name="ruleBuilder">The rule builder on which the validator should be defined</param>
/// <param name="expression">The value being compared</param>
/// <returns></returns>
public static IRuleBuilderOptions<T, TProperty?> LessThanOrEqualTo<T, TProperty>(
this IRuleBuilder<T, TProperty?> ruleBuilder, Expression<Func<T, TProperty?>> expression)
where TProperty : struct, IComparable<TProperty>, IComparable {
var func = expression.Compile();
return ruleBuilder.SetValidator(new LessThanOrEqualValidator(func.CoerceToNonGeneric(), expression.GetMember()));
}
/// <summary>
/// Defines a 'less than' validator on the current rule builder using a lambda expression.
/// The validation will succeed if the property value is greater than the specified value.
/// The validation will fail if the property value is less than or equal to the specified value.
/// </summary>
/// <typeparam name="T">Type of object being validated</typeparam>
/// <typeparam name="TProperty">Type of property being validated</typeparam>
/// <param name="ruleBuilder">The rule builder on which the validator should be defined</param>
/// <param name="expression">The value being compared</param>
/// <returns></returns>
public static IRuleBuilderOptions<T, TProperty> GreaterThan<T, TProperty>(this IRuleBuilder<T, TProperty> ruleBuilder,
Expression<Func<T, TProperty>> expression)
where TProperty : IComparable<TProperty>, IComparable {
var func = expression.Compile();
return ruleBuilder.SetValidator(new GreaterThanValidator(func.CoerceToNonGeneric(), expression.GetMember()));
}
/// <summary>
/// Defines a 'less than' validator on the current rule builder using a lambda expression.
/// The validation will succeed if the property value is greater than the specified value.
/// The validation will fail if the property value is less than or equal to the specified value.
/// </summary>
/// <typeparam name="T">Type of object being validated</typeparam>
/// <typeparam name="TProperty">Type of property being validated</typeparam>
/// <param name="ruleBuilder">The rule builder on which the validator should be defined</param>
/// <param name="expression">The value being compared</param>
/// <returns></returns>
public static IRuleBuilderOptions<T, Nullable<TProperty>> GreaterThan<T, TProperty>(this IRuleBuilder<T, Nullable<TProperty>> ruleBuilder,
Expression<Func<T, TProperty>> expression)
where TProperty : struct, IComparable<TProperty>, IComparable
{
var func = expression.Compile();
return ruleBuilder.SetValidator(new GreaterThanValidator(func.CoerceToNonGeneric(), expression.GetMember()));
}
/// <summary>
/// Defines a 'less than' validator on the current rule builder using a lambda expression.
/// The validation will succeed if the property value is greater than or equal the specified value.
/// The validation will fail if the property value is less than the specified value.
/// </summary>
/// <typeparam name="T">Type of object being validated</typeparam>
/// <typeparam name="TProperty">Type of property being validated</typeparam>
/// <param name="ruleBuilder">The rule builder on which the validator should be defined</param>
/// <param name="valueToCompare">The value being compared</param>
/// <returns></returns>
public static IRuleBuilderOptions<T, TProperty> GreaterThanOrEqualTo<T, TProperty>(
this IRuleBuilder<T, TProperty> ruleBuilder, Expression<Func<T, TProperty>> valueToCompare)
where TProperty : IComparable<TProperty>, IComparable {
var func = valueToCompare.Compile();
return ruleBuilder.SetValidator(new GreaterThanOrEqualValidator(func.CoerceToNonGeneric(), valueToCompare.GetMember()));
}
/// <summary>
/// Defines a 'greater than or equal to' validator on the current rule builder using a lambda expression.
/// The validation will succeed if the property value is greater than or equal the specified value.
/// The validation will fail if the property value is less than the specified value.
/// </summary>
/// <typeparam name="T">Type of object being validated</typeparam>
/// <typeparam name="TProperty">Type of property being validated</typeparam>
/// <param name="ruleBuilder">The rule builder on which the validator should be defined</param>
/// <param name="valueToCompare">The value being compared</param>
/// <returns></returns>
public static IRuleBuilderOptions<T, TProperty?> GreaterThanOrEqualTo<T, TProperty>(this IRuleBuilder<T, TProperty?> ruleBuilder, Expression<Func<T, TProperty?>> valueToCompare)
where TProperty : struct, IComparable<TProperty>, IComparable
{
var func = valueToCompare.Compile();
return ruleBuilder.SetValidator(new GreaterThanOrEqualValidator(func.CoerceToNonGeneric(), valueToCompare.GetMember()));
}
/// <summary>
/// Defines a 'greater than or equal to' validator on the current rule builder using a lambda expression.
/// The validation will succeed if the property value is greater than or equal the specified value.
/// The validation will fail if the property value is less than the specified value.
/// </summary>
/// <typeparam name="T">Type of object being validated</typeparam>
/// <typeparam name="TProperty">Type of property being validated</typeparam>
/// <param name="ruleBuilder">The rule builder on which the validator should be defined</param>
/// <param name="valueToCompare">The value being compared</param>
/// <returns></returns>
public static IRuleBuilderOptions<T, TProperty?> GreaterThanOrEqualTo<T, TProperty>(
this IRuleBuilder<T, TProperty?> ruleBuilder, Expression<Func<T, TProperty>> valueToCompare)
where TProperty : struct, IComparable<TProperty>, IComparable
{
var func = valueToCompare.Compile();
return ruleBuilder.SetValidator(new GreaterThanOrEqualValidator(func.CoerceToNonGeneric(), valueToCompare.GetMember()));
}
/// <summary>
/// Validates certain properties of the specified instance.
/// </summary>
/// <param name="validator">The current validator</param>
/// <param name="instance">The object to validate</param>
/// <param name="propertyExpressions">Expressions to specify the properties to validate</param>
/// <returns>A ValidationResult object containing any validation failures</returns>
public static ValidationResult Validate<T>(this IValidator<T> validator, T instance, params Expression<Func<T, object>>[] propertyExpressions) {
var context = new ValidationContext<T>(instance, new PropertyChain(), MemberNameValidatorSelector.FromExpressions(propertyExpressions));
return validator.Validate(context);
}
/// <summary>
/// Validates certain properties of the specified instance.
/// </summary>
/// <param name="instance">The object to validate</param>
/// <param name="properties">The names of the properties to validate.</param>
/// <returns>A ValidationResult object containing any validation failures.</returns>
public static ValidationResult Validate<T>(this IValidator<T> validator, T instance, params string[] properties) {
var context = new ValidationContext<T>(instance, new PropertyChain(), new MemberNameValidatorSelector(properties));
return validator.Validate(context);
}
public static ValidationResult Validate<T>(this IValidator<T> validator, T instance, IValidatorSelector selector = null, string ruleSet = null) {
if(selector != null && ruleSet != null) {
throw new InvalidOperationException("Cannot specify both an IValidatorSelector and a RuleSet.");
}
if(selector == null) {
selector = new DefaultValidatorSelector();
}
if(ruleSet != null) {
var ruleSetNames = ruleSet.Split(',', ';');
selector = new RulesetValidatorSelector(ruleSetNames);
}
var context = new ValidationContext<T>(instance, new PropertyChain(), selector);
return validator.Validate(context);
}
/// <summary>
/// Validates certain properties of the specified instance asynchronously.
/// </summary>
/// <param name="validator">The current validator</param>
/// <param name="instance">The object to validate</param>
/// <param name="propertyExpressions">Expressions to specify the properties to validate</param>
/// <returns>A ValidationResult object containing any validation failures</returns>
public static Task<ValidationResult> ValidateAsync<T>(this IValidator<T> validator, T instance, params Expression<Func<T, object>>[] propertyExpressions) {
var context = new ValidationContext<T>(instance, new PropertyChain(), MemberNameValidatorSelector.FromExpressions(propertyExpressions));
return validator.ValidateAsync(context);
}
/// <summary>
/// Validates certain properties of the specified instance asynchronously.
/// </summary>
/// <param name="instance">The object to validate</param>
/// <param name="properties">The names of the properties to validate.</param>
/// <returns>A ValidationResult object containing any validation failures.</returns>
public static Task<ValidationResult> ValidateAsync<T>(this IValidator<T> validator, T instance, params string[] properties) {
var context = new ValidationContext<T>(instance, new PropertyChain(), new MemberNameValidatorSelector(properties));
return validator.ValidateAsync(context);
}
public static Task<ValidationResult> ValidateAsync<T>(this IValidator<T> validator, T instance, IValidatorSelector selector = null, string ruleSet = null) {
if (selector != null && ruleSet != null) {
throw new InvalidOperationException("Cannot specify both an IValidatorSelector and a RuleSet.");
}
if (selector == null) {
selector = new DefaultValidatorSelector();
}
if (ruleSet != null) {
var ruleSetNames = ruleSet.Split(',', ';');
selector = new RulesetValidatorSelector(ruleSetNames);
}
var context = new ValidationContext<T>(instance, new PropertyChain(), selector);
return validator.ValidateAsync(context);
}
/// <summary>
/// Performs validation and then throws an exception if validation fails.
/// </summary>
public static void ValidateAndThrow<T>(this IValidator<T> validator, T instance) {
var result = validator.Validate(instance);
if(! result.IsValid) {
throw new ValidationException(result.Errors);
}
}
/// <summary>
/// Performs validation asynchronously and then throws an exception if validation fails.
/// </summary>
public static Task ValidateAndThrowAsync<T>(this IValidator<T> validator, T instance) {
return validator
.ValidateAsync(instance)
.Then(r => r.IsValid ? TaskHelpers.Completed() : TaskHelpers.FromError(new ValidationException(r.Errors)));
}
/// <summary>
/// Defines an 'inclusive between' validator on the current rule builder, but only for properties of types that implement IComparable.
/// Validation will fail if the value of the property is outside of the specifed range. The range is inclusive.
/// </summary>
/// <typeparam name="T">Type of object being validated</typeparam>
/// <typeparam name="TProperty">Type of property being validated</typeparam>
/// <param name="ruleBuilder">The rule builder on which the validator should be defined</param>
/// <param name="from">The lowest allowed value</param>
/// <param name="to">The highest allowed value</param>
/// <returns></returns>
public static IRuleBuilderOptions<T, TProperty> InclusiveBetween<T, TProperty>(this IRuleBuilder<T, TProperty> ruleBuilder, TProperty from, TProperty to) where TProperty : IComparable<TProperty>, IComparable {
return ruleBuilder.SetValidator(new InclusiveBetweenValidator(from, to));
}
/// <summary>
/// Defines an 'inclusive between' validator on the current rule builder, but only for properties of types that implement IComparable.
/// Validation will fail if the value of the property is outside of the specifed range. The range is inclusive.
/// </summary>
/// <typeparam name="T">Type of object being validated</typeparam>
/// <typeparam name="TProperty">Type of property being validated</typeparam>
/// <param name="ruleBuilder">The rule builder on which the validator should be defined</param>
/// <param name="from">The lowest allowed value</param>
/// <param name="to">The highest allowed value</param>
/// <returns></returns>
public static IRuleBuilderOptions<T, Nullable<TProperty>> InclusiveBetween<T, TProperty>(this IRuleBuilder<T, Nullable<TProperty>> ruleBuilder, TProperty from, TProperty to) where TProperty : struct, IComparable<TProperty>, IComparable {
return ruleBuilder.SetValidator(new InclusiveBetweenValidator(from, to));
}
/// <summary>
/// Defines an 'exclusive between' validator on the current rule builder, but only for properties of types that implement IComparable.
/// Validation will fail if the value of the property is outside of the specifed range. The range is exclusive.
/// </summary>
/// <typeparam name="T">Type of object being validated</typeparam>
/// <typeparam name="TProperty">Type of property being validated</typeparam>
/// <param name="ruleBuilder">The rule builder on which the validator should be defined</param>
/// <param name="from">The lowest allowed value</param>
/// <param name="to">The highest allowed value</param>
/// <returns></returns>
public static IRuleBuilderOptions<T, TProperty> ExclusiveBetween<T, TProperty>(this IRuleBuilder<T, TProperty> ruleBuilder, TProperty from, TProperty to) where TProperty : IComparable<TProperty>, IComparable {
return ruleBuilder.SetValidator(new ExclusiveBetweenValidator(from, to));
}
/// <summary>
/// Defines an 'exclusive between' validator on the current rule builder, but only for properties of types that implement IComparable.
/// Validation will fail if the value of the property is outside of the specifed range. The range is exclusive.
/// </summary>
/// <typeparam name="T">Type of object being validated</typeparam>
/// <typeparam name="TProperty">Type of property being validated</typeparam>
/// <param name="ruleBuilder">The rule builder on which the validator should be defined</param>
/// <param name="from">The lowest allowed value</param>
/// <param name="to">The highest allowed value</param>
/// <returns></returns>
public static IRuleBuilderOptions<T, Nullable<TProperty>> ExclusiveBetween<T, TProperty>(this IRuleBuilder<T, Nullable<TProperty>> ruleBuilder, TProperty from, TProperty to) where TProperty : struct, IComparable<TProperty>, IComparable {
return ruleBuilder.SetValidator(new ExclusiveBetweenValidator(from, to));
}
/// <summary>
/// Defines a credit card validator for the current rule builder that ensures that the specified string is a valid credit card number.
/// </summary>
public static IRuleBuilderOptions<T,string> CreditCard<T>(this IRuleBuilder<T, string> ruleBuilder) {
return ruleBuilder.SetValidator(new CreditCardValidator());
}
}
}
| |
// 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.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Management.Monitor
{
using Microsoft.Azure;
using Microsoft.Azure.Management;
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Microsoft.Rest.Azure.OData;
using Models;
using Newtonsoft.Json;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// ActivityLogsOperations operations.
/// </summary>
internal partial class ActivityLogsOperations : IServiceOperations<MonitorClient>, IActivityLogsOperations
{
/// <summary>
/// Initializes a new instance of the ActivityLogsOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
internal ActivityLogsOperations(MonitorClient client)
{
if (client == null)
{
throw new System.ArgumentNullException("client");
}
Client = client;
}
/// <summary>
/// Gets a reference to the MonitorClient
/// </summary>
public MonitorClient Client { get; private set; }
/// <summary>
/// Provides the list of records from the activity logs.
/// </summary>
/// <param name='odataQuery'>
/// OData parameters to apply to the operation.
/// </param>
/// <param name='select'>
/// Used to fetch events with only the given properties.<br>The
/// **$select** argument is a comma separated list of property names to be
/// returned. Possible values are: *authorization*, *claims*, *correlationId*,
/// *description*, *eventDataId*, *eventName*, *eventTimestamp*, *httpRequest*,
/// *level*, *operationId*, *operationName*, *properties*, *resourceGroupName*,
/// *resourceProviderName*, *resourceId*, *status*, *submissionTimestamp*,
/// *subStatus*, *subscriptionId*
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorResponseException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<IPage<EventData>>> ListWithHttpMessagesAsync(ODataQuery<EventData> odataQuery = default(ODataQuery<EventData>), string select = default(string), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
string apiVersion = "2015-04-01";
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("odataQuery", odataQuery);
tracingParameters.Add("apiVersion", apiVersion);
tracingParameters.Add("select", select);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "List", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/providers/microsoft.insights/eventtypes/management/values").ToString();
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (odataQuery != null)
{
var _odataFilter = odataQuery.ToString();
if (!string.IsNullOrEmpty(_odataFilter))
{
_queryParameters.Add(_odataFilter);
}
}
if (apiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion)));
}
if (select != null)
{
_queryParameters.Add(string.Format("$select={0}", System.Uri.EscapeDataString(select)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new ErrorResponseException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
ErrorResponse _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<ErrorResponse>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<IPage<EventData>>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page1<EventData>>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Provides the list of records from the activity logs.
/// </summary>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorResponseException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<IPage<EventData>>> ListNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (nextPageLink == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "nextPageLink");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("nextPageLink", nextPageLink);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "ListNext", tracingParameters);
}
// Construct URL
string _url = "{nextLink}";
_url = _url.Replace("{nextLink}", nextPageLink);
List<string> _queryParameters = new List<string>();
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new ErrorResponseException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
ErrorResponse _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<ErrorResponse>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<IPage<EventData>>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page1<EventData>>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
}
}
| |
// Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
using gagvr = Google.Ads.GoogleAds.V9.Resources;
using gax = Google.Api.Gax;
using gaxgrpc = Google.Api.Gax.Grpc;
using gaxgrpccore = Google.Api.Gax.Grpc.GrpcCore;
using proto = Google.Protobuf;
using grpccore = Grpc.Core;
using grpcinter = Grpc.Core.Interceptors;
using sys = System;
using scg = System.Collections.Generic;
using sco = System.Collections.ObjectModel;
using st = System.Threading;
using stt = System.Threading.Tasks;
namespace Google.Ads.GoogleAds.V9.Services
{
/// <summary>Settings for <see cref="UserInterestServiceClient"/> instances.</summary>
public sealed partial class UserInterestServiceSettings : gaxgrpc::ServiceSettingsBase
{
/// <summary>Get a new instance of the default <see cref="UserInterestServiceSettings"/>.</summary>
/// <returns>A new instance of the default <see cref="UserInterestServiceSettings"/>.</returns>
public static UserInterestServiceSettings GetDefault() => new UserInterestServiceSettings();
/// <summary>Constructs a new <see cref="UserInterestServiceSettings"/> object with default settings.</summary>
public UserInterestServiceSettings()
{
}
private UserInterestServiceSettings(UserInterestServiceSettings existing) : base(existing)
{
gax::GaxPreconditions.CheckNotNull(existing, nameof(existing));
GetUserInterestSettings = existing.GetUserInterestSettings;
OnCopy(existing);
}
partial void OnCopy(UserInterestServiceSettings existing);
/// <summary>
/// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to
/// <c>UserInterestServiceClient.GetUserInterest</c> and <c>UserInterestServiceClient.GetUserInterestAsync</c>.
/// </summary>
/// <remarks>
/// <list type="bullet">
/// <item><description>Initial retry delay: 5000 milliseconds.</description></item>
/// <item><description>Retry delay multiplier: 1.3</description></item>
/// <item><description>Retry maximum delay: 60000 milliseconds.</description></item>
/// <item><description>Maximum attempts: Unlimited</description></item>
/// <item>
/// <description>
/// Retriable status codes: <see cref="grpccore::StatusCode.Unavailable"/>,
/// <see cref="grpccore::StatusCode.DeadlineExceeded"/>.
/// </description>
/// </item>
/// <item><description>Timeout: 3600 seconds.</description></item>
/// </list>
/// </remarks>
public gaxgrpc::CallSettings GetUserInterestSettings { get; set; } = gaxgrpc::CallSettingsExtensions.WithRetry(gaxgrpc::CallSettings.FromExpiration(gax::Expiration.FromTimeout(sys::TimeSpan.FromMilliseconds(3600000))), gaxgrpc::RetrySettings.FromExponentialBackoff(maxAttempts: 2147483647, initialBackoff: sys::TimeSpan.FromMilliseconds(5000), maxBackoff: sys::TimeSpan.FromMilliseconds(60000), backoffMultiplier: 1.3, retryFilter: gaxgrpc::RetrySettings.FilterForStatusCodes(grpccore::StatusCode.Unavailable, grpccore::StatusCode.DeadlineExceeded)));
/// <summary>Creates a deep clone of this object, with all the same property values.</summary>
/// <returns>A deep clone of this <see cref="UserInterestServiceSettings"/> object.</returns>
public UserInterestServiceSettings Clone() => new UserInterestServiceSettings(this);
}
/// <summary>
/// Builder class for <see cref="UserInterestServiceClient"/> to provide simple configuration of credentials,
/// endpoint etc.
/// </summary>
internal sealed partial class UserInterestServiceClientBuilder : gaxgrpc::ClientBuilderBase<UserInterestServiceClient>
{
/// <summary>The settings to use for RPCs, or <c>null</c> for the default settings.</summary>
public UserInterestServiceSettings Settings { get; set; }
/// <summary>Creates a new builder with default settings.</summary>
public UserInterestServiceClientBuilder()
{
UseJwtAccessWithScopes = UserInterestServiceClient.UseJwtAccessWithScopes;
}
partial void InterceptBuild(ref UserInterestServiceClient client);
partial void InterceptBuildAsync(st::CancellationToken cancellationToken, ref stt::Task<UserInterestServiceClient> task);
/// <summary>Builds the resulting client.</summary>
public override UserInterestServiceClient Build()
{
UserInterestServiceClient client = null;
InterceptBuild(ref client);
return client ?? BuildImpl();
}
/// <summary>Builds the resulting client asynchronously.</summary>
public override stt::Task<UserInterestServiceClient> BuildAsync(st::CancellationToken cancellationToken = default)
{
stt::Task<UserInterestServiceClient> task = null;
InterceptBuildAsync(cancellationToken, ref task);
return task ?? BuildAsyncImpl(cancellationToken);
}
private UserInterestServiceClient BuildImpl()
{
Validate();
grpccore::CallInvoker callInvoker = CreateCallInvoker();
return UserInterestServiceClient.Create(callInvoker, Settings);
}
private async stt::Task<UserInterestServiceClient> BuildAsyncImpl(st::CancellationToken cancellationToken)
{
Validate();
grpccore::CallInvoker callInvoker = await CreateCallInvokerAsync(cancellationToken).ConfigureAwait(false);
return UserInterestServiceClient.Create(callInvoker, Settings);
}
/// <summary>Returns the endpoint for this builder type, used if no endpoint is otherwise specified.</summary>
protected override string GetDefaultEndpoint() => UserInterestServiceClient.DefaultEndpoint;
/// <summary>
/// Returns the default scopes for this builder type, used if no scopes are otherwise specified.
/// </summary>
protected override scg::IReadOnlyList<string> GetDefaultScopes() => UserInterestServiceClient.DefaultScopes;
/// <summary>Returns the channel pool to use when no other options are specified.</summary>
protected override gaxgrpc::ChannelPool GetChannelPool() => UserInterestServiceClient.ChannelPool;
/// <summary>Returns the default <see cref="gaxgrpc::GrpcAdapter"/>to use if not otherwise specified.</summary>
protected override gaxgrpc::GrpcAdapter DefaultGrpcAdapter => gaxgrpccore::GrpcCoreAdapter.Instance;
}
/// <summary>UserInterestService client wrapper, for convenient use.</summary>
/// <remarks>
/// Service to fetch Google Ads User Interest.
/// </remarks>
public abstract partial class UserInterestServiceClient
{
/// <summary>
/// The default endpoint for the UserInterestService service, which is a host of "googleads.googleapis.com" and
/// a port of 443.
/// </summary>
public static string DefaultEndpoint { get; } = "googleads.googleapis.com:443";
/// <summary>The default UserInterestService scopes.</summary>
/// <remarks>
/// The default UserInterestService scopes are:
/// <list type="bullet"><item><description>https://www.googleapis.com/auth/adwords</description></item></list>
/// </remarks>
public static scg::IReadOnlyList<string> DefaultScopes { get; } = new sco::ReadOnlyCollection<string>(new string[]
{
"https://www.googleapis.com/auth/adwords",
});
internal static gaxgrpc::ChannelPool ChannelPool { get; } = new gaxgrpc::ChannelPool(DefaultScopes, UseJwtAccessWithScopes);
internal static bool UseJwtAccessWithScopes
{
get
{
bool useJwtAccessWithScopes = true;
MaybeUseJwtAccessWithScopes(ref useJwtAccessWithScopes);
return useJwtAccessWithScopes;
}
}
static partial void MaybeUseJwtAccessWithScopes(ref bool useJwtAccessWithScopes);
/// <summary>
/// Asynchronously creates a <see cref="UserInterestServiceClient"/> using the default credentials, endpoint and
/// settings. To specify custom credentials or other settings, use
/// <see cref="UserInterestServiceClientBuilder"/>.
/// </summary>
/// <param name="cancellationToken">
/// The <see cref="st::CancellationToken"/> to use while creating the client.
/// </param>
/// <returns>The task representing the created <see cref="UserInterestServiceClient"/>.</returns>
public static stt::Task<UserInterestServiceClient> CreateAsync(st::CancellationToken cancellationToken = default) =>
new UserInterestServiceClientBuilder().BuildAsync(cancellationToken);
/// <summary>
/// Synchronously creates a <see cref="UserInterestServiceClient"/> using the default credentials, endpoint and
/// settings. To specify custom credentials or other settings, use
/// <see cref="UserInterestServiceClientBuilder"/>.
/// </summary>
/// <returns>The created <see cref="UserInterestServiceClient"/>.</returns>
public static UserInterestServiceClient Create() => new UserInterestServiceClientBuilder().Build();
/// <summary>
/// Creates a <see cref="UserInterestServiceClient"/> which uses the specified call invoker for remote
/// operations.
/// </summary>
/// <param name="callInvoker">
/// The <see cref="grpccore::CallInvoker"/> for remote operations. Must not be null.
/// </param>
/// <param name="settings">Optional <see cref="UserInterestServiceSettings"/>.</param>
/// <returns>The created <see cref="UserInterestServiceClient"/>.</returns>
internal static UserInterestServiceClient Create(grpccore::CallInvoker callInvoker, UserInterestServiceSettings settings = null)
{
gax::GaxPreconditions.CheckNotNull(callInvoker, nameof(callInvoker));
grpcinter::Interceptor interceptor = settings?.Interceptor;
if (interceptor != null)
{
callInvoker = grpcinter::CallInvokerExtensions.Intercept(callInvoker, interceptor);
}
UserInterestService.UserInterestServiceClient grpcClient = new UserInterestService.UserInterestServiceClient(callInvoker);
return new UserInterestServiceClientImpl(grpcClient, settings);
}
/// <summary>
/// Shuts down any channels automatically created by <see cref="Create()"/> and
/// <see cref="CreateAsync(st::CancellationToken)"/>. Channels which weren't automatically created are not
/// affected.
/// </summary>
/// <remarks>
/// After calling this method, further calls to <see cref="Create()"/> and
/// <see cref="CreateAsync(st::CancellationToken)"/> will create new channels, which could in turn be shut down
/// by another call to this method.
/// </remarks>
/// <returns>A task representing the asynchronous shutdown operation.</returns>
public static stt::Task ShutdownDefaultChannelsAsync() => ChannelPool.ShutdownChannelsAsync();
/// <summary>The underlying gRPC UserInterestService client</summary>
public virtual UserInterestService.UserInterestServiceClient GrpcClient => throw new sys::NotImplementedException();
/// <summary>
/// Returns the requested user interest in full detail
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual gagvr::UserInterest GetUserInterest(GetUserInterestRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Returns the requested user interest in full detail
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<gagvr::UserInterest> GetUserInterestAsync(GetUserInterestRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Returns the requested user interest in full detail
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<gagvr::UserInterest> GetUserInterestAsync(GetUserInterestRequest request, st::CancellationToken cancellationToken) =>
GetUserInterestAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
/// <summary>
/// Returns the requested user interest in full detail
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="resourceName">
/// Required. Resource name of the UserInterest to fetch.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual gagvr::UserInterest GetUserInterest(string resourceName, gaxgrpc::CallSettings callSettings = null) =>
GetUserInterest(new GetUserInterestRequest
{
ResourceName = gax::GaxPreconditions.CheckNotNullOrEmpty(resourceName, nameof(resourceName)),
}, callSettings);
/// <summary>
/// Returns the requested user interest in full detail
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="resourceName">
/// Required. Resource name of the UserInterest to fetch.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<gagvr::UserInterest> GetUserInterestAsync(string resourceName, gaxgrpc::CallSettings callSettings = null) =>
GetUserInterestAsync(new GetUserInterestRequest
{
ResourceName = gax::GaxPreconditions.CheckNotNullOrEmpty(resourceName, nameof(resourceName)),
}, callSettings);
/// <summary>
/// Returns the requested user interest in full detail
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="resourceName">
/// Required. Resource name of the UserInterest to fetch.
/// </param>
/// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<gagvr::UserInterest> GetUserInterestAsync(string resourceName, st::CancellationToken cancellationToken) =>
GetUserInterestAsync(resourceName, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
/// <summary>
/// Returns the requested user interest in full detail
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="resourceName">
/// Required. Resource name of the UserInterest to fetch.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual gagvr::UserInterest GetUserInterest(gagvr::UserInterestName resourceName, gaxgrpc::CallSettings callSettings = null) =>
GetUserInterest(new GetUserInterestRequest
{
ResourceNameAsUserInterestName = gax::GaxPreconditions.CheckNotNull(resourceName, nameof(resourceName)),
}, callSettings);
/// <summary>
/// Returns the requested user interest in full detail
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="resourceName">
/// Required. Resource name of the UserInterest to fetch.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<gagvr::UserInterest> GetUserInterestAsync(gagvr::UserInterestName resourceName, gaxgrpc::CallSettings callSettings = null) =>
GetUserInterestAsync(new GetUserInterestRequest
{
ResourceNameAsUserInterestName = gax::GaxPreconditions.CheckNotNull(resourceName, nameof(resourceName)),
}, callSettings);
/// <summary>
/// Returns the requested user interest in full detail
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="resourceName">
/// Required. Resource name of the UserInterest to fetch.
/// </param>
/// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<gagvr::UserInterest> GetUserInterestAsync(gagvr::UserInterestName resourceName, st::CancellationToken cancellationToken) =>
GetUserInterestAsync(resourceName, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
}
/// <summary>UserInterestService client wrapper implementation, for convenient use.</summary>
/// <remarks>
/// Service to fetch Google Ads User Interest.
/// </remarks>
public sealed partial class UserInterestServiceClientImpl : UserInterestServiceClient
{
private readonly gaxgrpc::ApiCall<GetUserInterestRequest, gagvr::UserInterest> _callGetUserInterest;
/// <summary>
/// Constructs a client wrapper for the UserInterestService service, with the specified gRPC client and
/// settings.
/// </summary>
/// <param name="grpcClient">The underlying gRPC client.</param>
/// <param name="settings">The base <see cref="UserInterestServiceSettings"/> used within this client.</param>
public UserInterestServiceClientImpl(UserInterestService.UserInterestServiceClient grpcClient, UserInterestServiceSettings settings)
{
GrpcClient = grpcClient;
UserInterestServiceSettings effectiveSettings = settings ?? UserInterestServiceSettings.GetDefault();
gaxgrpc::ClientHelper clientHelper = new gaxgrpc::ClientHelper(effectiveSettings);
_callGetUserInterest = clientHelper.BuildApiCall<GetUserInterestRequest, gagvr::UserInterest>(grpcClient.GetUserInterestAsync, grpcClient.GetUserInterest, effectiveSettings.GetUserInterestSettings).WithGoogleRequestParam("resource_name", request => request.ResourceName);
Modify_ApiCall(ref _callGetUserInterest);
Modify_GetUserInterestApiCall(ref _callGetUserInterest);
OnConstruction(grpcClient, effectiveSettings, clientHelper);
}
partial void Modify_ApiCall<TRequest, TResponse>(ref gaxgrpc::ApiCall<TRequest, TResponse> call) where TRequest : class, proto::IMessage<TRequest> where TResponse : class, proto::IMessage<TResponse>;
partial void Modify_GetUserInterestApiCall(ref gaxgrpc::ApiCall<GetUserInterestRequest, gagvr::UserInterest> call);
partial void OnConstruction(UserInterestService.UserInterestServiceClient grpcClient, UserInterestServiceSettings effectiveSettings, gaxgrpc::ClientHelper clientHelper);
/// <summary>The underlying gRPC UserInterestService client</summary>
public override UserInterestService.UserInterestServiceClient GrpcClient { get; }
partial void Modify_GetUserInterestRequest(ref GetUserInterestRequest request, ref gaxgrpc::CallSettings settings);
/// <summary>
/// Returns the requested user interest in full detail
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public override gagvr::UserInterest GetUserInterest(GetUserInterestRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_GetUserInterestRequest(ref request, ref callSettings);
return _callGetUserInterest.Sync(request, callSettings);
}
/// <summary>
/// Returns the requested user interest in full detail
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public override stt::Task<gagvr::UserInterest> GetUserInterestAsync(GetUserInterestRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_GetUserInterestRequest(ref request, ref callSettings);
return _callGetUserInterest.Async(request, callSettings);
}
}
}
| |
// 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.Globalization;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Security;
using System.Text;
namespace TestLibrary
{
public static class Generator
{
internal static Random m_rand = new Random();
internal static int? seed = null;
public static int? Seed
{
get
{
if (seed.HasValue)
{
return seed.Value;
}
else
{
return null;
}
}
set
{
if (!(seed.HasValue))
{
seed = value;
if (seed.HasValue)
{
TestFramework.LogVerbose("Seeding Random with: " + seed.Value.ToString());
m_rand = new Random(seed.Value);
}
}
else
{
TestFramework.LogVerbose("Attempt to seed Random to " + value.ToString() + " rejected it was already seeded to: " + seed.Value.ToString());
}
}
}
// returns a byte array of random data
public static void GetBytes(int new_seed, byte[] buffer)
{
Seed = new_seed;
GetBytes(buffer);
}
public static void GetBytes(byte[] buffer)
{
m_rand.NextBytes(buffer);
TestFramework.LogVerbose("Random Byte[] produced: " + Utilities.ByteArrayToString(buffer));
}
// returns a non-negative Int64 between 0 and Int64.MaxValue
public static Int64 GetInt64(Int32 new_seed)
{
Seed = new_seed;
return GetInt64();
}
public static Int64 GetInt64()
{
byte[] buffer = new byte[8];
Int64 iVal;
GetBytes(buffer);
// convert to Int64
iVal = 0;
for (int i = 0; i < buffer.Length; i++)
{
iVal |= ((Int64)buffer[i] << (i * 8));
}
if (0 > iVal) iVal *= -1;
TestFramework.LogVerbose("Random Int64 produced: " + iVal.ToString());
return iVal;
}
// returns a non-negative Int32 between 0 and Int32.MaxValue
public static Int32 GetInt32(Int32 new_seed)
{
Seed = new_seed;
return GetInt32();
}
public static Int32 GetInt32()
{
Int32 i = m_rand.Next();
TestFramework.LogVerbose("Random Int32 produced: " + i.ToString());
return i;
}
// returns a non-negative Int16 between 0 and Int16.MaxValue
public static Int16 GetInt16(Int32 new_seed)
{
Seed = new_seed;
return GetInt16();
}
public static Int16 GetInt16()
{
Int16 i = Convert.ToInt16(m_rand.Next() % (1 + Int16.MaxValue));
TestFramework.LogVerbose("Random Int16 produced: " + i.ToString());
return i;
}
// returns a non-negative Byte between 0 and Byte.MaxValue
public static Byte GetByte(Int32 new_seed)
{
Seed = new_seed;
return GetByte();
}
public static Byte GetByte()
{
Byte i = Convert.ToByte(m_rand.Next() % (1 + Byte.MaxValue));
TestFramework.LogVerbose("Random Byte produced: " + i.ToString());
return i;
}
// returns a non-negative Double between 0.0 and 1.0
public static Double GetDouble(Int32 new_seed)
{
Seed = new_seed;
return GetDouble();
}
public static Double GetDouble()
{
Double i = m_rand.NextDouble();
TestFramework.LogVerbose("Random Double produced: " + i.ToString());
return i;
}
// returns a non-negative Single between 0.0 and 1.0
public static Single GetSingle(Int32 new_seed)
{
Seed = new_seed;
return GetSingle();
}
public static Single GetSingle()
{
Single i = Convert.ToSingle(m_rand.NextDouble());
TestFramework.LogVerbose("Random Single produced: " + i.ToString());
return i;
}
// returns a valid char that is a letter
public static Char GetCharLetter(Int32 new_seed)
{
Seed = new_seed;
return GetCharLetter();
}
public static Char GetCharLetter()
{
return GetCharLetter(true);
}
//returns a valid char that is a letter
//if allowsurrogate is true then surrogates are valid return values
public static Char GetCharLetter(Int32 new_seed, bool allowsurrogate)
{
Seed = new_seed;
return GetCharLetter(allowsurrogate);
}
public static Char GetCharLetter(bool allowsurrogate)
{
return GetCharLetter(allowsurrogate, true);
}
//returns a valid char that is a letter
//if allowsurrogate is true then surrogates are valid return values
//if allownoweight is true, then no-weight characters are valid return values
public static Char GetCharLetter(Int32 new_seed, bool allowsurrogate, bool allownoweight)
{
Seed = new_seed;
return GetCharLetter(allowsurrogate, allownoweight);
}
public static Char GetCharLetter(bool allowsurrogate, bool allownoweight)
{
Int16 iVal;
Char c = 'a'; //this value is never used
Int32 counter;
bool loopCondition = true;
// attempt to randomly find a letter
counter = 100;
do
{
counter--;
iVal = GetInt16();
TestFramework.LogVerbose("Random CharLetter produced: " + Convert.ToChar(iVal).ToString());
if (false == allownoweight)
{
throw new NotSupportedException("allownoweight = false is not supported in TestLibrary with FEATURE_NOPINVOKES");
}
c = Convert.ToChar(iVal);
loopCondition = allowsurrogate ? (!Char.IsLetter(c)) : (!Char.IsLetter(c) || Char.IsSurrogate(c));
}
while (loopCondition && 0 < counter);
if (!Char.IsLetter(c))
{
// we tried and failed to get a letter
// Grab an ASCII letter
c = Convert.ToChar(GetInt16() % 26 + 'A');
}
TestFramework.LogVerbose("Random Char produced: " + c.ToString());
return c;
}
// returns a valid char that is a number
public static char GetCharNumber(Int32 new_seed)
{
Seed = new_seed;
return GetCharNumber();
}
public static char GetCharNumber()
{
return GetCharNumber(true);
}
// returns a valid char that is a number
//if allownoweight is true, then no-weight characters are valid return values
public static char GetCharNumber(Int32 new_seed, bool allownoweight)
{
Seed = new_seed;
return GetCharNumber(allownoweight);
}
public static char GetCharNumber(bool allownoweight)
{
Char c = '0'; //this value is never used
Int32 counter;
Int16 iVal;
bool loopCondition = true;
// attempt to randomly find a number
counter = 100;
do
{
counter--;
iVal = GetInt16();
TestFramework.LogVerbose("Random Char produced: " + Convert.ToChar(iVal).ToString());
if (false == allownoweight)
{
throw new InvalidOperationException("allownoweight = false is not supported in TestLibrary with FEATURE_NOPINVOKES");
}
c = Convert.ToChar(iVal);
loopCondition = !Char.IsNumber(c);
}
while (loopCondition && 0 < counter);
if (!Char.IsNumber(c))
{
// we tried and failed to get a letter
// Grab an ASCII number
c = Convert.ToChar(GetInt16() % 10 + '0');
}
TestFramework.LogVerbose("Random Char produced: " + c.ToString());
return c;
}
// returns a valid char
public static Char GetChar(Int32 new_seed)
{
Seed = new_seed;
return GetChar();
}
public static Char GetChar()
{
return GetChar(true);
}
// returns a valid char
//if allowsurrogate is true then surrogates are valid return values
public static Char GetChar(Int32 new_seed, bool allowsurrogate)
{
Seed = new_seed;
return GetChar(allowsurrogate);
}
public static Char GetChar(bool allowsurrogate)
{
return GetChar(allowsurrogate, true);
}
// returns a valid char
// if allowsurrogate is true then surrogates are valid return values
// if allownoweight characters then noweight characters are valid return values
public static Char GetChar(Int32 new_seed, bool allowsurrogate, bool allownoweight)
{
Seed = new_seed;
return GetChar(allowsurrogate, allownoweight);
}
public static Char GetChar(bool allowsurrogate, bool allownoweight)
{
Int16 iVal = GetInt16();
Char c = (char)(iVal);
if (!Char.IsLetter(c))
{
// we tried and failed to get a letter
// Just grab an ASCII letter
// This is a hack but will work for now
c = (char)(GetInt16() % 26 + 'A');
}
return c;
}
// if value is no-weight char, return true
public static bool NoWeightChar(int value)
{
if ((int)'a' == value) // 'a' = 97
return false;
String strA = "a" + Convert.ToChar(value);
String strB = "a";
if (0 == GlobLocHelper.OSCompare(CultureInfo.CurrentCulture, strA, 0, 2, strB, 0, 1, CompareOptions.None))
return true;
return false;
}
// returns a string. If "validPath" is set, only valid path characters
// will be included
public static string GetString(Int32 new_seed, Boolean validPath, Int32 minLength, Int32 maxLength)
{
Seed = new_seed;
return GetString(validPath, minLength, maxLength);
}
public static string GetString(Boolean validPath, Int32 minLength, Int32 maxLength)
{
return GetString(validPath, true, true, minLength, maxLength);
}
// several string APIs don't like nulls in them, so this generates a string without nulls
public static string GetString(Int32 new_seed, Boolean validPath, Boolean allowNulls, Int32 minLength, Int32 maxLength)
{
Seed = new_seed;
return GetString(validPath, allowNulls, minLength, maxLength);
}
public static string GetString(Boolean validPath, Boolean allowNulls, Int32 minLength, Int32 maxLength)
{
return GetString(validPath, allowNulls, true, minLength, maxLength);
}
// some string operations don't like no-weight characters
public static string GetString(Int32 new_seed, Boolean validPath, Boolean allowNulls, Boolean allowNoWeight, Int32 minLength, Int32 maxLength)
{
Seed = new_seed;
return GetString(validPath, allowNulls, allowNoWeight, minLength, maxLength);
}
public static string GetString(Boolean validPath, Boolean allowNulls, Boolean allowNoWeight, Int32 minLength, Int32 maxLength)
{
StringBuilder sVal = new StringBuilder();
Char c;
Int32 length;
if (0 == minLength && 0 == maxLength) return String.Empty;
if (minLength > maxLength) return null;
length = minLength;
if (minLength != maxLength)
{
length = (GetInt32() % (maxLength - minLength)) + minLength;
}
for (int i = 0; length > i; i++)
{
if (validPath)
{
// TODO: Make this smarter
if (0 == (GetByte() % 2))
{
c = GetCharLetter(true, allowNoWeight);
}
else
{
c = GetCharNumber(allowNoWeight);
}
}
else if (!allowNulls)
{
do
{
c = GetChar(true, allowNoWeight);
} while (c == '\u0000');
}
else
{
c = GetChar(true, allowNoWeight);
}
sVal.Append(c);
}
string s = sVal.ToString();
TestFramework.LogVerbose("Random String produced: " + s);
return s;
}
public static string[] GetStrings(Int32 new_seed, Boolean validPath, Int32 minLength, Int32 maxLength)
{
Seed = new_seed;
return GetStrings(validPath, minLength, maxLength);
}
public static string[] GetStrings(Boolean validPath, Int32 minLength, Int32 maxLength)
{
string validString;
const char c_LATIN_A = '\u0100';
const char c_LOWER_A = 'a';
const char c_UPPER_A = 'A';
const char c_ZERO_WEIGHT = '\uFEFF';
const char c_DOUBLE_WIDE_A = '\uFF21';
const string c_SURROGATE_UPPER = "\uD801\uDC00";
const string c_SURROGATE_LOWER = "\uD801\uDC28";
const char c_LOWER_SIGMA1 = (char)0x03C2;
const char c_LOWER_SIGMA2 = (char)0x03C3;
const char c_UPPER_SIGMA = (char)0x03A3;
const char c_SPACE = ' ';
int numConsts = 12;
string[] retStrings;
if (2 >= minLength && 2 >= maxLength || minLength > maxLength) return null;
retStrings = new string[numConsts];
validString = TestLibrary.Generator.GetString(validPath, minLength - 1, maxLength - 1);
retStrings[0] = TestLibrary.Generator.GetString(validPath, minLength, maxLength);
retStrings[1] = validString + c_LATIN_A;
retStrings[2] = validString + c_LOWER_A;
retStrings[3] = validString + c_UPPER_A;
retStrings[4] = validString + c_ZERO_WEIGHT;
retStrings[5] = validString + c_DOUBLE_WIDE_A;
retStrings[6] = TestLibrary.Generator.GetString(validPath, minLength - 2, maxLength - 2) + c_SURROGATE_UPPER;
retStrings[7] = TestLibrary.Generator.GetString(validPath, minLength - 2, maxLength - 2) + c_SURROGATE_LOWER;
retStrings[8] = validString + c_LOWER_SIGMA1;
retStrings[9] = validString + c_LOWER_SIGMA2;
retStrings[10] = validString + c_UPPER_SIGMA;
retStrings[11] = validString + c_SPACE;
return retStrings;
}
[SecuritySafeCritical]
public static object GetType(Type t)
{
return Activator.CreateInstance(t);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Text;
using System.ComponentModel;
using System.ComponentModel.Design;
using System.ComponentModel.Design.Serialization;
using System.Drawing;
using System.Windows.Forms;
namespace CommonTools.TreeList
{
[TypeConverterAttribute(typeof(OptionsSettingTypeConverter))]
public class TextFormatting
{
ContentAlignment m_alignment = ContentAlignment.MiddleLeft;
Color m_foreColor = SystemColors.ControlText;
Color m_backColor = Color.Transparent;
Padding m_padding = new Padding(0,0,0,0);
public TextFormatFlags GetFormattingFlags()
{
TextFormatFlags flags = 0;
switch (TextAlignment)
{
case ContentAlignment.TopLeft:
flags = TextFormatFlags.Top | TextFormatFlags.Left;
break;
case ContentAlignment.TopCenter:
flags = TextFormatFlags.Top | TextFormatFlags.HorizontalCenter;
break;
case ContentAlignment.TopRight:
flags = TextFormatFlags.Top | TextFormatFlags.Right;
break;
case ContentAlignment.MiddleLeft:
flags = TextFormatFlags.VerticalCenter | TextFormatFlags.Left;
break;
case ContentAlignment.MiddleCenter:
flags = TextFormatFlags.VerticalCenter | TextFormatFlags.HorizontalCenter;
break;
case ContentAlignment.MiddleRight:
flags = TextFormatFlags.VerticalCenter | TextFormatFlags.Right;
break;
case ContentAlignment.BottomLeft:
flags = TextFormatFlags.Bottom | TextFormatFlags.Left;
break;
case ContentAlignment.BottomCenter:
flags = TextFormatFlags.Bottom | TextFormatFlags.HorizontalCenter;
break;
case ContentAlignment.BottomRight:
flags = TextFormatFlags.Bottom | TextFormatFlags.Right;
break;
}
return flags;
}
[DefaultValue(typeof(Padding), "0,0,0,0")]
public Padding Padding
{
get { return m_padding; }
set { m_padding = value; }
}
[DefaultValue(typeof(ContentAlignment), "MiddleLeft")]
public ContentAlignment TextAlignment
{
get { return m_alignment; }
set { m_alignment = value; }
}
[DefaultValue(typeof(Color), "ControlText")]
public Color ForeColor
{
get { return m_foreColor; }
set { m_foreColor = value; }
}
[DefaultValue(typeof(Color), "Transparent")]
public Color BackColor
{
get { return m_backColor; }
set { m_backColor = value; }
}
public TextFormatting()
{
}
public TextFormatting(TextFormatting aCopy)
{
m_alignment = aCopy.m_alignment;
m_foreColor = aCopy.m_foreColor;
m_backColor = aCopy.m_backColor;
m_padding = aCopy.m_padding;
}
}
[TypeConverterAttribute(typeof(OptionsSettingTypeConverter))]
public class ViewSetting
{
TreeListView m_owner;
BorderStyle m_borderStyle = BorderStyle.None;
int m_indent = 16;
bool m_showLine = true;
bool m_showPlusMinus = true;
bool m_showGridLines = true;
[Category("Behavior")]
[DefaultValue(typeof(int), "16")]
public int Indent
{
get { return m_indent; }
set
{
m_indent = value;
m_owner.Invalidate();
}
}
[Category("Behavior")]
[DefaultValue(typeof(bool), "True")]
public bool ShowLine
{
get { return m_showLine; }
set
{
m_showLine = value;
m_owner.Invalidate();
}
}
[Category("Behavior")]
[DefaultValue(typeof(bool), "True")]
public bool ShowPlusMinus
{
get { return m_showPlusMinus; }
set
{
m_showPlusMinus = value;
m_owner.Invalidate();
}
}
[Category("Behavior")]
[DefaultValue(typeof(bool), "True")]
public bool ShowGridLines
{
get { return m_showGridLines; }
set
{
m_showGridLines = value;
m_owner.Invalidate();
}
}
[Category("Appearance")]
[DefaultValue(typeof(BorderStyle), "None")]
public BorderStyle BorderStyle
{
get { return m_borderStyle; }
set
{
if (m_borderStyle != value)
{
m_borderStyle = value;
m_owner.internalUpdateStyles();
m_owner.Invalidate();
}
}
}
public ViewSetting(TreeListView owner)
{
m_owner = owner;
}
}
[TypeConverterAttribute(typeof(OptionsSettingTypeConverter))]
public class CollumnSetting
{
int m_leftMargin = 5;
int m_headerHeight = 20;
TreeListView m_owner;
[DefaultValue(5)]
public int LeftMargin
{
get { return m_leftMargin; }
set
{
m_leftMargin = value;
m_owner.Columns.RecalcVisibleColumsRect();
m_owner.Invalidate();
}
}
[DefaultValue(20)]
public int HeaderHeight
{
get { return m_headerHeight; }
set
{
m_headerHeight = value;
m_owner.Columns.RecalcVisibleColumsRect();
m_owner.Invalidate();
}
}
public CollumnSetting(TreeListView owner)
{
m_owner = owner;
}
}
[TypeConverterAttribute(typeof(OptionsSettingTypeConverter))]
public class RowSetting
{
TreeListView m_owner;
bool m_showHeader = true;
int m_headerWidth = 15;
int m_itemHeight = 16;
[DefaultValue(true)]
public bool ShowHeader
{
get { return m_showHeader; }
set
{
if (m_showHeader == value)
return;
m_showHeader = value;
m_owner.Columns.RecalcVisibleColumsRect();
m_owner.Invalidate();
}
}
[DefaultValue(15)]
public int HeaderWidth
{
get { return m_headerWidth; }
set
{
if (m_headerWidth == value)
return;
m_headerWidth = value;
m_owner.Columns.RecalcVisibleColumsRect();
m_owner.Invalidate();
}
}
[Category("Behavior")]
[DefaultValue(typeof(int), "16")]
public int ItemHeight
{
get { return m_itemHeight; }
set
{
m_itemHeight = value;
m_owner.Invalidate();
}
}
public RowSetting(TreeListView owner)
{
m_owner = owner;
}
}
class OptionsSettingTypeConverter : ExpandableObjectConverter
{
public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType)
{
if (destinationType == typeof(ViewSetting))
return true;
if (destinationType == typeof(RowSetting))
return true;
if (destinationType == typeof(CollumnSetting))
return true;
if (destinationType == typeof(TextFormatting))
return true;
return base.CanConvertTo(context, destinationType);
}
public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destinationType)
{
if (destinationType == typeof(string) && value.GetType() == typeof(ViewSetting))
return "(View Options)";
if (destinationType == typeof(string) && value.GetType() == typeof(RowSetting))
return "(Row Header Options)";
if (destinationType == typeof(string) && value.GetType() == typeof(CollumnSetting))
return "(Columns Options)";
if (destinationType == typeof(string) && value.GetType() == typeof(TextFormatting))
return "(Formatting)";
return base.ConvertTo(context, culture, value, destinationType);
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Management.Automation.Language;
namespace System.Management.Automation
{
/// <summary>
/// This attribute is used to specify an argument completer for a parameter to a cmdlet or function.
/// <example>
/// <code>
/// [Parameter()]
/// [ArgumentCompleter(typeof(NounArgumentCompleter))]
/// public string Noun { get; set; }
/// </code>
/// </example>
/// </summary>
[AttributeUsage(AttributeTargets.Field | AttributeTargets.Property)]
public class ArgumentCompleterAttribute : Attribute
{
/// <summary/>
[SuppressMessage("Microsoft.Naming", "CA1721:PropertyNamesShouldNotMatchGetMethods")]
public Type Type { get; private set; }
/// <summary/>
public ScriptBlock ScriptBlock { get; private set; }
/// <param name="type">The type must implement <see cref="IArgumentCompleter"/> and have a default constructor.</param>
public ArgumentCompleterAttribute(Type type)
{
if (type == null || (type.GetInterfaces().All(t => t != typeof(IArgumentCompleter))))
{
throw PSTraceSource.NewArgumentException("type");
}
Type = type;
}
/// <summary>
/// This constructor is used primarily via PowerShell scripts.
/// </summary>
/// <param name="scriptBlock"></param>
public ArgumentCompleterAttribute(ScriptBlock scriptBlock)
{
if (scriptBlock == null)
{
throw PSTraceSource.NewArgumentNullException("scriptBlock");
}
ScriptBlock = scriptBlock;
}
}
/// <summary>
/// A type specified by the <see cref="ArgumentCompleterAttribute"/> must implement this interface.
/// </summary>
public interface IArgumentCompleter
{
/// <summary>
/// Implementations of this function are called by PowerShell to complete arguments.
/// </summary>
/// <param name="commandName">The name of the command that needs argument completion.</param>
/// <param name="parameterName">The name of the parameter that needs argument completion.</param>
/// <param name="wordToComplete">The (possibly empty) word being completed.</param>
/// <param name="commandAst">The command ast in case it is needed for completion.</param>
/// <param name="fakeBoundParameters">
/// This parameter is similar to $PSBoundParameters, except that sometimes PowerShell cannot or
/// will not attempt to evaluate an argument, in which case you may need to use <paramref name="commandAst"/>.
/// </param>
/// <returns>
/// A collection of completion results, most like with <see cref="CompletionResult.ResultType"/> set to
/// <see cref="CompletionResultType.ParameterValue"/>.
/// </returns>
IEnumerable<CompletionResult> CompleteArgument(
string commandName,
string parameterName,
string wordToComplete,
CommandAst commandAst,
IDictionary fakeBoundParameters);
}
/// <summary>
/// </summary>
[Cmdlet(VerbsLifecycle.Register, "ArgumentCompleter", HelpUri = "https://go.microsoft.com/fwlink/?LinkId=528576")]
public class RegisterArgumentCompleterCommand : PSCmdlet
{
/// <summary>
/// </summary>
[Parameter(ParameterSetName = "NativeSet", Mandatory = true)]
[Parameter(ParameterSetName = "PowerShellSet")]
[SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")]
public string[] CommandName { get; set; }
/// <summary>
/// </summary>
[Parameter(ParameterSetName = "PowerShellSet", Mandatory = true)]
public string ParameterName { get; set; }
/// <summary>
/// </summary>
[Parameter(Mandatory = true)]
[AllowNull()]
public ScriptBlock ScriptBlock { get; set; }
/// <summary>
/// </summary>
[Parameter(ParameterSetName = "NativeSet")]
public SwitchParameter Native { get; set; }
/// <summary>
/// </summary>
protected override void EndProcessing()
{
Dictionary<string, ScriptBlock> completerDictionary;
if (ParameterName != null)
{
completerDictionary = Context.CustomArgumentCompleters ??
(Context.CustomArgumentCompleters = new Dictionary<string, ScriptBlock>(StringComparer.OrdinalIgnoreCase));
}
else
{
completerDictionary = Context.NativeArgumentCompleters ??
(Context.NativeArgumentCompleters = new Dictionary<string, ScriptBlock>(StringComparer.OrdinalIgnoreCase));
}
if (CommandName == null || CommandName.Length == 0)
{
CommandName = new[] { "" };
}
for (int i = 0; i < CommandName.Length; i++)
{
var key = CommandName[i];
if (!string.IsNullOrWhiteSpace(ParameterName))
{
if (!string.IsNullOrWhiteSpace(key))
{
key = key + ":" + ParameterName;
}
else
{
key = ParameterName;
}
}
completerDictionary[key] = ScriptBlock;
}
}
}
/// <summary>
/// This attribute is used to specify an argument completions for a parameter of a cmdlet or function
/// based on string array.
/// <example>
/// [Parameter()]
/// [ArgumentCompletions("Option1","Option2","Option3")]
/// public string Noun { get; set; }
/// </example>
/// </summary>
[AttributeUsage(AttributeTargets.Field | AttributeTargets.Property)]
public class ArgumentCompletionsAttribute : Attribute
{
private string[] _completions;
/// <summary>
/// Initializes a new instance of the ArgumentCompletionsAttribute class.
/// </summary>
/// <param name="completions">List of complete values.</param>
/// <exception cref="ArgumentNullException">For null arguments.</exception>
/// <exception cref="ArgumentOutOfRangeException">For invalid arguments.</exception>
public ArgumentCompletionsAttribute(params string[] completions)
{
if (completions == null)
{
throw PSTraceSource.NewArgumentNullException("completions");
}
if (completions.Length == 0)
{
throw PSTraceSource.NewArgumentOutOfRangeException("completions", completions);
}
_completions = completions;
}
/// <summary>
/// The function returns completions for arguments.
/// </summary>
public IEnumerable<CompletionResult> CompleteArgument(string commandName, string parameterName, string wordToComplete, CommandAst commandAst, IDictionary fakeBoundParameters)
{
var wordToCompletePattern = WildcardPattern.Get(string.IsNullOrWhiteSpace(wordToComplete) ? "*" : wordToComplete + "*", WildcardOptions.IgnoreCase);
foreach (var str in _completions)
{
if (wordToCompletePattern.IsMatch(str))
{
yield return new CompletionResult(str, str, CompletionResultType.ParameterValue, str);
}
}
}
}
}
| |
// 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.Collections.ObjectModel;
using System.Diagnostics;
using System.Linq.Expressions;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Threading;
namespace System.Dynamic.Utils
{
internal static class ExpressionUtils
{
public static ReadOnlyCollection<T> ReturnReadOnly<T>(ref IList<T> collection)
{
IList<T> value = collection;
// if it's already read-only just return it.
ReadOnlyCollection<T> res = value as ReadOnlyCollection<T>;
if (res != null)
{
return res;
}
// otherwise make sure only readonly collection every gets exposed
Interlocked.CompareExchange<IList<T>>(
ref collection,
value.ToReadOnly(),
value
);
// and return it
return (ReadOnlyCollection<T>)collection;
}
/// <summary>
/// Helper used for ensuring we only return 1 instance of a ReadOnlyCollection of T.
///
/// This is similar to the ReturnReadOnly of T. This version supports nodes which hold
/// onto multiple Expressions where one is typed to object. That object field holds either
/// an expression or a ReadOnlyCollection of Expressions. When it holds a ReadOnlyCollection
/// the IList which backs it is a ListArgumentProvider which uses the Expression which
/// implements IArgumentProvider to get 2nd and additional values. The ListArgumentProvider
/// continues to hold onto the 1st expression.
///
/// This enables users to get the ReadOnlyCollection w/o it consuming more memory than if
/// it was just an array. Meanwhile The DLR internally avoids accessing which would force
/// the readonly collection to be created resulting in a typical memory savings.
/// </summary>
public static ReadOnlyCollection<Expression> ReturnReadOnly(IArgumentProvider provider, ref object collection)
{
Expression tObj = collection as Expression;
if (tObj != null)
{
// otherwise make sure only one readonly collection ever gets exposed
Interlocked.CompareExchange(
ref collection,
new ReadOnlyCollection<Expression>(new ListArgumentProvider(provider, tObj)),
tObj
);
}
// and return what is not guaranteed to be a readonly collection
return (ReadOnlyCollection<Expression>)collection;
}
/// <summary>
/// Helper which is used for specialized subtypes which use ReturnReadOnly(ref object, ...).
/// This is the reverse version of ReturnReadOnly which takes an IArgumentProvider.
///
/// This is used to return the 1st argument. The 1st argument is typed as object and either
/// contains a ReadOnlyCollection or the Expression. We check for the Expression and if it's
/// present we return that, otherwise we return the 1st element of the ReadOnlyCollection.
/// </summary>
public static T ReturnObject<T>(object collectionOrT) where T : class
{
T t = collectionOrT as T;
if (t != null)
{
return t;
}
return ((ReadOnlyCollection<T>)collectionOrT)[0];
}
public static void ValidateArgumentTypes(MethodBase method, ExpressionType nodeKind, ref ReadOnlyCollection<Expression> arguments)
{
Debug.Assert(nodeKind == ExpressionType.Invoke || nodeKind == ExpressionType.Call || nodeKind == ExpressionType.Dynamic || nodeKind == ExpressionType.New);
ParameterInfo[] pis = GetParametersForValidation(method, nodeKind);
ValidateArgumentCount(method, nodeKind, arguments.Count, pis);
Expression[] newArgs = null;
for (int i = 0, n = pis.Length; i < n; i++)
{
Expression arg = arguments[i];
ParameterInfo pi = pis[i];
arg = ValidateOneArgument(method, nodeKind, arg, pi);
if (newArgs == null && arg != arguments[i])
{
newArgs = new Expression[arguments.Count];
for (int j = 0; j < i; j++)
{
newArgs[j] = arguments[j];
}
}
if (newArgs != null)
{
newArgs[i] = arg;
}
}
if (newArgs != null)
{
arguments = new TrueReadOnlyCollection<Expression>(newArgs);
}
}
public static void ValidateArgumentCount(MethodBase method, ExpressionType nodeKind, int count, ParameterInfo[] pis)
{
if (pis.Length != count)
{
// Throw the right error for the node we were given
switch (nodeKind)
{
case ExpressionType.New:
throw Error.IncorrectNumberOfConstructorArguments();
case ExpressionType.Invoke:
throw Error.IncorrectNumberOfLambdaArguments();
case ExpressionType.Dynamic:
case ExpressionType.Call:
throw Error.IncorrectNumberOfMethodCallArguments(method);
default:
throw ContractUtils.Unreachable;
}
}
}
public static Expression ValidateOneArgument(MethodBase method, ExpressionType nodeKind, Expression arguments, ParameterInfo pi)
{
RequiresCanRead(arguments, nameof(arguments));
Type pType = pi.ParameterType;
if (pType.IsByRef)
{
pType = pType.GetElementType();
}
TypeUtils.ValidateType(pType, nameof(pi));
if (!TypeUtils.AreReferenceAssignable(pType, arguments.Type))
{
if (!TryQuote(pType, ref arguments))
{
// Throw the right error for the node we were given
switch (nodeKind)
{
case ExpressionType.New:
throw Error.ExpressionTypeDoesNotMatchConstructorParameter(arguments.Type, pType);
case ExpressionType.Invoke:
throw Error.ExpressionTypeDoesNotMatchParameter(arguments.Type, pType);
case ExpressionType.Dynamic:
case ExpressionType.Call:
throw Error.ExpressionTypeDoesNotMatchMethodParameter(arguments.Type, pType, method);
default:
throw ContractUtils.Unreachable;
}
}
}
return arguments;
}
public static void RequiresCanRead(Expression expression, string paramName)
{
if (expression == null)
{
throw new ArgumentNullException(paramName);
}
// validate that we can read the node
switch (expression.NodeType)
{
case ExpressionType.Index:
IndexExpression index = (IndexExpression)expression;
if (index.Indexer != null && !index.Indexer.CanRead)
{
throw new ArgumentException(Strings.ExpressionMustBeReadable, paramName);
}
break;
case ExpressionType.MemberAccess:
MemberExpression member = (MemberExpression)expression;
PropertyInfo prop = member.Member as PropertyInfo;
if (prop != null)
{
if (!prop.CanRead)
{
throw new ArgumentException(Strings.ExpressionMustBeReadable, paramName);
}
}
break;
}
}
// Attempts to auto-quote the expression tree. Returns true if it succeeded, false otherwise.
public static bool TryQuote(Type parameterType, ref Expression argument)
{
// We used to allow quoting of any expression, but the behavior of
// quote (produce a new tree closed over parameter values), only
// works consistently for lambdas
Type quoteable = typeof(LambdaExpression);
if (TypeUtils.IsSameOrSubclass(quoteable, parameterType) &&
parameterType.IsAssignableFrom(argument.GetType()))
{
argument = Expression.Quote(argument);
return true;
}
return false;
}
internal static ParameterInfo[] GetParametersForValidation(MethodBase method, ExpressionType nodeKind)
{
ParameterInfo[] pis = method.GetParametersCached();
if (nodeKind == ExpressionType.Dynamic)
{
pis = pis.RemoveFirst(); // ignore CallSite argument
}
return pis;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Newtonsoft.Json.Linq;
using OpenIddict.Abstractions;
using OrchardCore.OpenId.Abstractions.Stores;
using OrchardCore.OpenId.YesSql.Indexes;
using OrchardCore.OpenId.YesSql.Models;
using YesSql;
using YesSql.Services;
namespace OrchardCore.OpenId.YesSql.Stores
{
public class OpenIdAuthorizationStore<TAuthorization> : IOpenIdAuthorizationStore<TAuthorization>
where TAuthorization : OpenIdAuthorization, new()
{
private readonly ISession _session;
public OpenIdAuthorizationStore(ISession session)
{
_session = session;
}
/// <summary>
/// Determines the number of authorizations that exist in the database.
/// </summary>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> that can be used to abort the operation.</param>
/// <returns>
/// A <see cref="Task"/> that can be used to monitor the asynchronous operation,
/// whose result returns the number of authorizations in the database.
/// </returns>
public virtual async Task<long> CountAsync(CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested();
return await _session.Query<TAuthorization>().CountAsync();
}
/// <summary>
/// Determines the number of authorizations that match the specified query.
/// </summary>
/// <typeparam name="TResult">The result type.</typeparam>
/// <param name="query">The query to execute.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> that can be used to abort the operation.</param>
/// <returns>
/// A <see cref="Task"/> that can be used to monitor the asynchronous operation,
/// whose result returns the number of authorizations that match the specified query.
/// </returns>
public virtual Task<long> CountAsync<TResult>(Func<IQueryable<TAuthorization>, IQueryable<TResult>> query, CancellationToken cancellationToken)
=> throw new NotSupportedException();
/// <summary>
/// Creates a new authorization.
/// </summary>
/// <param name="authorization">The authorization to create.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> that can be used to abort the operation.</param>
/// <returns>
/// A <see cref="Task"/> that can be used to monitor the asynchronous operation.
/// </returns>
public virtual Task CreateAsync(TAuthorization authorization, CancellationToken cancellationToken)
{
if (authorization == null)
{
throw new ArgumentNullException(nameof(authorization));
}
cancellationToken.ThrowIfCancellationRequested();
_session.Save(authorization);
return _session.CommitAsync();
}
/// <summary>
/// Removes an existing authorization.
/// </summary>
/// <param name="authorization">The authorization to delete.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> that can be used to abort the operation.</param>
/// <returns>
/// A <see cref="Task"/> that can be used to monitor the asynchronous operation.
/// </returns>
public virtual Task DeleteAsync(TAuthorization authorization, CancellationToken cancellationToken)
{
if (authorization == null)
{
throw new ArgumentNullException(nameof(authorization));
}
cancellationToken.ThrowIfCancellationRequested();
_session.Delete(authorization);
return _session.CommitAsync();
}
/// <summary>
/// Retrieves the authorizations corresponding to the specified
/// subject and associated with the application identifier.
/// </summary>
/// <param name="subject">The subject associated with the authorization.</param>
/// <param name="client">The client associated with the authorization.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> that can be used to abort the operation.</param>
/// <returns>
/// A <see cref="Task"/> that can be used to monitor the asynchronous operation,
/// whose result returns the authorizations corresponding to the subject/client.
/// </returns>
public virtual async Task<ImmutableArray<TAuthorization>> FindAsync(
string subject, string client, CancellationToken cancellationToken)
{
if (string.IsNullOrEmpty(subject))
{
throw new ArgumentException("The subject cannot be null or empty.", nameof(subject));
}
if (string.IsNullOrEmpty(client))
{
throw new ArgumentException("The client cannot be null or empty.", nameof(client));
}
cancellationToken.ThrowIfCancellationRequested();
return ImmutableArray.CreateRange(
await _session.Query<TAuthorization, OpenIdAuthorizationIndex>(
index => index.ApplicationId == client &&
index.Subject == subject).ListAsync());
}
/// <summary>
/// Retrieves the authorizations matching the specified parameters.
/// </summary>
/// <param name="subject">The subject associated with the authorization.</param>
/// <param name="client">The client associated with the authorization.</param>
/// <param name="status">The status associated with the authorization.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> that can be used to abort the operation.</param>
/// <returns>
/// A <see cref="Task"/> that can be used to monitor the asynchronous operation,
/// whose result returns the authorizations corresponding to the subject/client.
/// </returns>
public virtual async Task<ImmutableArray<TAuthorization>> FindAsync(
string subject, string client, string status, CancellationToken cancellationToken)
{
if (string.IsNullOrEmpty(subject))
{
throw new ArgumentException("The subject cannot be null or empty.", nameof(subject));
}
if (string.IsNullOrEmpty(client))
{
throw new ArgumentException("The client identifier cannot be null or empty.", nameof(client));
}
if (string.IsNullOrEmpty(status))
{
throw new ArgumentException("The status cannot be null or empty.", nameof(client));
}
cancellationToken.ThrowIfCancellationRequested();
return ImmutableArray.CreateRange(
await _session.Query<TAuthorization, OpenIdAuthorizationIndex>(
index => index.ApplicationId == client && index.Subject == subject && index.Status == status).ListAsync());
}
/// <summary>
/// Retrieves the authorizations matching the specified parameters.
/// </summary>
/// <param name="subject">The subject associated with the authorization.</param>
/// <param name="client">The client associated with the authorization.</param>
/// <param name="status">The status associated with the authorization.</param>
/// <param name="type">The type associated with the authorization.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> that can be used to abort the operation.</param>
/// <returns>
/// A <see cref="Task"/> that can be used to monitor the asynchronous operation,
/// whose result returns the authorizations corresponding to the subject/client.
/// </returns>
public virtual async Task<ImmutableArray<TAuthorization>> FindAsync(
string subject, string client,
string status, string type, CancellationToken cancellationToken)
{
if (string.IsNullOrEmpty(subject))
{
throw new ArgumentException("The subject cannot be null or empty.", nameof(subject));
}
if (string.IsNullOrEmpty(client))
{
throw new ArgumentException("The client identifier cannot be null or empty.", nameof(client));
}
if (string.IsNullOrEmpty(status))
{
throw new ArgumentException("The status cannot be null or empty.", nameof(client));
}
if (string.IsNullOrEmpty(type))
{
throw new ArgumentException("The type cannot be null or empty.", nameof(client));
}
cancellationToken.ThrowIfCancellationRequested();
return ImmutableArray.CreateRange(
await _session.Query<TAuthorization, OpenIdAuthorizationIndex>(
index => index.ApplicationId == client && index.Subject == subject &&
index.Status == status && index.Type == type).ListAsync());
}
/// <summary>
/// Retrieves the authorizations matching the specified parameters.
/// </summary>
/// <param name="subject">The subject associated with the authorization.</param>
/// <param name="client">The client associated with the authorization.</param>
/// <param name="status">The authorization status.</param>
/// <param name="type">The authorization type.</param>
/// <param name="scopes">The minimal scopes associated with the authorization.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> that can be used to abort the operation.</param>
/// <returns>
/// A <see cref="Task"/> that can be used to monitor the asynchronous operation,
/// whose result returns the authorizations corresponding to the criteria.
/// </returns>
public virtual async Task<ImmutableArray<TAuthorization>> FindAsync(
string subject, string client, string status, string type,
ImmutableArray<string> scopes, CancellationToken cancellationToken)
{
var authorizations = await FindAsync(subject, client, status, type, cancellationToken);
if (authorizations.IsEmpty)
{
return ImmutableArray.Create<TAuthorization>();
}
var builder = ImmutableArray.CreateBuilder<TAuthorization>(authorizations.Length);
foreach (var authorization in authorizations)
{
async Task<bool> HasScopesAsync()
=> (await GetScopesAsync(authorization, cancellationToken))
.ToImmutableHashSet(StringComparer.Ordinal)
.IsSupersetOf(scopes);
if (await HasScopesAsync())
{
builder.Add(authorization);
}
}
return builder.Count == builder.Capacity ?
builder.MoveToImmutable() :
builder.ToImmutable();
}
/// <summary>
/// Retrieves the list of authorizations corresponding to the specified application identifier.
/// </summary>
/// <param name="identifier">The application identifier associated with the authorizations.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> that can be used to abort the operation.</param>
/// <returns>
/// A <see cref="Task"/> that can be used to monitor the asynchronous operation,
/// whose result returns the authorizations corresponding to the specified application.
/// </returns>
public virtual async Task<ImmutableArray<TAuthorization>> FindByApplicationIdAsync(
string identifier, CancellationToken cancellationToken)
{
if (string.IsNullOrEmpty(identifier))
{
throw new ArgumentException("The identifier cannot be null or empty.", nameof(identifier));
}
cancellationToken.ThrowIfCancellationRequested();
return ImmutableArray.CreateRange(
await _session.Query<TAuthorization, OpenIdAuthorizationIndex>(
index => index.ApplicationId == identifier).ListAsync());
}
/// <summary>
/// Retrieves an authorization using its unique identifier.
/// </summary>
/// <param name="identifier">The unique identifier associated with the authorization.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> that can be used to abort the operation.</param>
/// <returns>
/// A <see cref="Task"/> that can be used to monitor the asynchronous operation,
/// whose result returns the authorization corresponding to the identifier.
/// </returns>
public virtual Task<TAuthorization> FindByIdAsync(string identifier, CancellationToken cancellationToken)
{
if (string.IsNullOrEmpty(identifier))
{
throw new ArgumentException("The identifier cannot be null or empty.", nameof(identifier));
}
cancellationToken.ThrowIfCancellationRequested();
return _session.Query<TAuthorization, OpenIdAuthorizationIndex>(
index => index.AuthorizationId == identifier).FirstOrDefaultAsync();
}
/// <summary>
/// Retrieves an authorization using its physical identifier.
/// </summary>
/// <param name="identifier">The physical identifier associated with the authorization.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> that can be used to abort the operation.</param>
/// <returns>
/// A <see cref="Task"/> that can be used to monitor the asynchronous operation,
/// whose result returns the authorization corresponding to the identifier.
/// </returns>
public virtual Task<TAuthorization> FindByPhysicalIdAsync(string identifier, CancellationToken cancellationToken)
{
if (string.IsNullOrEmpty(identifier))
{
throw new ArgumentException("The identifier cannot be null or empty.", nameof(identifier));
}
cancellationToken.ThrowIfCancellationRequested();
return _session.GetAsync<TAuthorization>(int.Parse(identifier, CultureInfo.InvariantCulture));
}
/// <summary>
/// Retrieves all the authorizations corresponding to the specified subject.
/// </summary>
/// <param name="subject">The subject associated with the authorization.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> that can be used to abort the operation.</param>
/// <returns>
/// A <see cref="Task"/> that can be used to monitor the asynchronous operation,
/// whose result returns the authorizations corresponding to the specified subject.
/// </returns>
public virtual async Task<ImmutableArray<TAuthorization>> FindBySubjectAsync(
string subject, CancellationToken cancellationToken)
{
if (string.IsNullOrEmpty(subject))
{
throw new ArgumentException("The subject cannot be null or empty.", nameof(subject));
}
cancellationToken.ThrowIfCancellationRequested();
return (await _session.Query<TAuthorization, OpenIdAuthorizationIndex>(
index => index.Subject == subject).ListAsync()).ToImmutableArray();
}
/// <summary>
/// Retrieves the optional application identifier associated with an authorization.
/// </summary>
/// <param name="authorization">The authorization.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> that can be used to abort the operation.</param>
/// <returns>
/// A <see cref="ValueTask{TResult}"/> that can be used to monitor the asynchronous operation,
/// whose result returns the application identifier associated with the authorization.
/// </returns>
public virtual ValueTask<string> GetApplicationIdAsync(TAuthorization authorization, CancellationToken cancellationToken)
{
if (authorization == null)
{
throw new ArgumentNullException(nameof(authorization));
}
return new ValueTask<string>(authorization.ApplicationId);
}
/// <summary>
/// Executes the specified query and returns the first element.
/// </summary>
/// <typeparam name="TState">The state type.</typeparam>
/// <typeparam name="TResult">The result type.</typeparam>
/// <param name="query">The query to execute.</param>
/// <param name="state">The optional state.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> that can be used to abort the operation.</param>
/// <returns>
/// A <see cref="Task"/> that can be used to monitor the asynchronous operation,
/// whose result returns the first element returned when executing the query.
/// </returns>
public virtual Task<TResult> GetAsync<TState, TResult>(
Func<IQueryable<TAuthorization>, TState, IQueryable<TResult>> query,
TState state, CancellationToken cancellationToken)
=> throw new NotSupportedException();
/// <summary>
/// Retrieves the unique identifier associated with an authorization.
/// </summary>
/// <param name="authorization">The authorization.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> that can be used to abort the operation.</param>
/// <returns>
/// A <see cref="ValueTask{TResult}"/> that can be used to monitor the asynchronous operation,
/// whose result returns the unique identifier associated with the authorization.
/// </returns>
public virtual ValueTask<string> GetIdAsync(TAuthorization authorization, CancellationToken cancellationToken)
{
if (authorization == null)
{
throw new ArgumentNullException(nameof(authorization));
}
return new ValueTask<string>(authorization.AuthorizationId);
}
/// <summary>
/// Retrieves the physical identifier associated with an authorization.
/// </summary>
/// <param name="authorization">The authorization.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> that can be used to abort the operation.</param>
/// <returns>
/// A <see cref="ValueTask{TResult}"/> that can be used to monitor the asynchronous operation,
/// whose result returns the physical identifier associated with the authorization.
/// </returns>
public virtual ValueTask<string> GetPhysicalIdAsync(TAuthorization authorization, CancellationToken cancellationToken)
{
if (authorization == null)
{
throw new ArgumentNullException(nameof(authorization));
}
return new ValueTask<string>(authorization.Id.ToString(CultureInfo.InvariantCulture));
}
/// <summary>
/// Retrieves the additional properties associated with an authorization.
/// </summary>
/// <param name="authorization">The authorization.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> that can be used to abort the operation.</param>
/// <returns>
/// A <see cref="ValueTask{TResult}"/> that can be used to monitor the asynchronous operation,
/// whose result returns all the additional properties associated with the authorization.
/// </returns>
public virtual ValueTask<JObject> GetPropertiesAsync(TAuthorization authorization, CancellationToken cancellationToken)
{
if (authorization == null)
{
throw new ArgumentNullException(nameof(authorization));
}
return new ValueTask<JObject>(authorization.Properties ?? new JObject());
}
/// <summary>
/// Retrieves the scopes associated with an authorization.
/// </summary>
/// <param name="authorization">The authorization.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> that can be used to abort the operation.</param>
/// <returns>
/// A <see cref="ValueTask{TResult}"/> that can be used to monitor the asynchronous operation,
/// whose result returns the scopes associated with the specified authorization.
/// </returns>
public virtual ValueTask<ImmutableArray<string>> GetScopesAsync(TAuthorization authorization, CancellationToken cancellationToken)
{
if (authorization == null)
{
throw new ArgumentNullException(nameof(authorization));
}
return new ValueTask<ImmutableArray<string>>(authorization.Scopes);
}
/// <summary>
/// Retrieves the status associated with an authorization.
/// </summary>
/// <param name="authorization">The authorization.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> that can be used to abort the operation.</param>
/// <returns>
/// A <see cref="ValueTask{TResult}"/> that can be used to monitor the asynchronous operation,
/// whose result returns the status associated with the specified authorization.
/// </returns>
public virtual ValueTask<string> GetStatusAsync(TAuthorization authorization, CancellationToken cancellationToken)
{
if (authorization == null)
{
throw new ArgumentNullException(nameof(authorization));
}
return new ValueTask<string>(authorization.Status);
}
/// <summary>
/// Retrieves the subject associated with an authorization.
/// </summary>
/// <param name="authorization">The authorization.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> that can be used to abort the operation.</param>
/// <returns>
/// A <see cref="ValueTask{TResult}"/> that can be used to monitor the asynchronous operation,
/// whose result returns the subject associated with the specified authorization.
/// </returns>
public virtual ValueTask<string> GetSubjectAsync(TAuthorization authorization, CancellationToken cancellationToken)
{
if (authorization == null)
{
throw new ArgumentNullException(nameof(authorization));
}
return new ValueTask<string>(authorization.Subject);
}
/// <summary>
/// Retrieves the type associated with an authorization.
/// </summary>
/// <param name="authorization">The authorization.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> that can be used to abort the operation.</param>
/// <returns>
/// A <see cref="ValueTask{TResult}"/> that can be used to monitor the asynchronous operation,
/// whose result returns the type associated with the specified authorization.
/// </returns>
public virtual ValueTask<string> GetTypeAsync(TAuthorization authorization, CancellationToken cancellationToken)
{
if (authorization == null)
{
throw new ArgumentNullException(nameof(authorization));
}
return new ValueTask<string>(authorization.Type);
}
/// <summary>
/// Instantiates a new authorization.
/// </summary>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> that can be used to abort the operation.</param>
/// <returns>
/// A <see cref="ValueTask{TResult}"/> that can be used to monitor the asynchronous operation,
/// whose result returns the instantiated authorization, that can be persisted in the database.
/// </returns>
public virtual ValueTask<TAuthorization> InstantiateAsync(CancellationToken cancellationToken)
=> new ValueTask<TAuthorization>(new TAuthorization { AuthorizationId = Guid.NewGuid().ToString("n") });
/// <summary>
/// Executes the specified query and returns all the corresponding elements.
/// </summary>
/// <param name="count">The number of results to return.</param>
/// <param name="offset">The number of results to skip.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> that can be used to abort the operation.</param>
/// <returns>
/// A <see cref="Task"/> that can be used to monitor the asynchronous operation,
/// whose result returns all the elements returned when executing the specified query.
/// </returns>
public virtual async Task<ImmutableArray<TAuthorization>> ListAsync(int? count, int? offset, CancellationToken cancellationToken)
{
var query = _session.Query<TAuthorization>();
if (offset.HasValue)
{
query = query.Skip(offset.Value);
}
if (count.HasValue)
{
query = query.Take(count.Value);
}
return ImmutableArray.CreateRange(await query.ListAsync());
}
/// <summary>
/// Executes the specified query and returns all the corresponding elements.
/// </summary>
/// <typeparam name="TState">The state type.</typeparam>
/// <typeparam name="TResult">The result type.</typeparam>
/// <param name="query">The query to execute.</param>
/// <param name="state">The optional state.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> that can be used to abort the operation.</param>
/// <returns>
/// A <see cref="Task"/> that can be used to monitor the asynchronous operation,
/// whose result returns all the elements returned when executing the specified query.
/// </returns>
public virtual Task<ImmutableArray<TResult>> ListAsync<TState, TResult>(
Func<IQueryable<TAuthorization>, TState, IQueryable<TResult>> query,
TState state, CancellationToken cancellationToken)
=> throw new NotSupportedException();
/// <summary>
/// Removes the ad-hoc authorizations that are marked as invalid or have no valid token attached.
/// </summary>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> that can be used to abort the operation.</param>
/// <returns>
/// A <see cref="Task"/> that can be used to monitor the asynchronous operation.
/// </returns>
public virtual async Task PruneAsync(CancellationToken cancellationToken)
{
// Note: YesSql doesn't support set-based deletes, which prevents removing entities
// in a single command without having to retrieve and materialize them first.
// To work around this limitation, entities are manually listed and deleted using a batch logic.
IList<Exception> exceptions = null;
for (var offset = 0; offset < 100_000; offset = offset + 1_000)
{
cancellationToken.ThrowIfCancellationRequested();
var authorizations = await _session.Query<TAuthorization, OpenIdAuthorizationIndex>(
authorization => authorization.Status != OpenIddictConstants.Statuses.Valid ||
(authorization.Type == OpenIddictConstants.AuthorizationTypes.AdHoc &&
authorization.AuthorizationId.IsNotIn<OpenIdTokenIndex>(
token => token.AuthorizationId,
token => token.Status == OpenIddictConstants.Statuses.Valid &&
token.ExpirationDate > DateTimeOffset.UtcNow))).Skip(offset).Take(1_000).ListAsync();
foreach (var authorization in authorizations)
{
_session.Delete(authorization);
}
try
{
await _session.CommitAsync();
}
catch (Exception exception)
{
if (exceptions == null)
{
exceptions = new List<Exception>(capacity: 1);
}
exceptions.Add(exception);
}
}
if (exceptions != null)
{
throw new AggregateException("An error occurred while pruning authorizations.", exceptions);
}
}
/// <summary>
/// Sets the application identifier associated with an authorization.
/// </summary>
/// <param name="authorization">The authorization.</param>
/// <param name="identifier">The unique identifier associated with the client application.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> that can be used to abort the operation.</param>
/// <returns>
/// A <see cref="Task"/> that can be used to monitor the asynchronous operation.
/// </returns>
public virtual Task SetApplicationIdAsync(TAuthorization authorization,
string identifier, CancellationToken cancellationToken)
{
if (authorization == null)
{
throw new ArgumentNullException(nameof(authorization));
}
if (string.IsNullOrEmpty(identifier))
{
authorization.ApplicationId = null;
}
else
{
authorization.ApplicationId = identifier;
}
return Task.CompletedTask;
}
/// <summary>
/// Sets the additional properties associated with an authorization.
/// </summary>
/// <param name="authorization">The authorization.</param>
/// <param name="properties">The additional properties associated with the authorization </param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> that can be used to abort the operation.</param>
/// <returns>
/// A <see cref="Task"/> that can be used to monitor the asynchronous operation.
/// </returns>
public virtual Task SetPropertiesAsync(TAuthorization authorization, JObject properties, CancellationToken cancellationToken)
{
if (authorization == null)
{
throw new ArgumentNullException(nameof(authorization));
}
authorization.Properties = properties;
return Task.CompletedTask;
}
/// <summary>
/// Sets the scopes associated with an authorization.
/// </summary>
/// <param name="authorization">The authorization.</param>
/// <param name="scopes">The scopes associated with the authorization.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> that can be used to abort the operation.</param>
/// <returns>
/// A <see cref="Task"/> that can be used to monitor the asynchronous operation.
/// </returns>
public virtual Task SetScopesAsync(TAuthorization authorization,
ImmutableArray<string> scopes, CancellationToken cancellationToken)
{
if (authorization == null)
{
throw new ArgumentNullException(nameof(authorization));
}
authorization.Scopes = scopes;
return Task.CompletedTask;
}
/// <summary>
/// Sets the status associated with an authorization.
/// </summary>
/// <param name="authorization">The authorization.</param>
/// <param name="status">The status associated with the authorization.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> that can be used to abort the operation.</param>
/// <returns>
/// A <see cref="Task"/> that can be used to monitor the asynchronous operation.
/// </returns>
public virtual Task SetStatusAsync(TAuthorization authorization,
string status, CancellationToken cancellationToken)
{
if (authorization == null)
{
throw new ArgumentNullException(nameof(authorization));
}
authorization.Status = status;
return Task.CompletedTask;
}
/// <summary>
/// Sets the subject associated with an authorization.
/// </summary>
/// <param name="authorization">The authorization.</param>
/// <param name="subject">The subject associated with the authorization.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> that can be used to abort the operation.</param>
/// <returns>
/// A <see cref="Task"/> that can be used to monitor the asynchronous operation.
/// </returns>
public virtual Task SetSubjectAsync(TAuthorization authorization,
string subject, CancellationToken cancellationToken)
{
if (authorization == null)
{
throw new ArgumentNullException(nameof(authorization));
}
authorization.Subject = subject;
return Task.CompletedTask;
}
/// <summary>
/// Sets the type associated with an authorization.
/// </summary>
/// <param name="authorization">The authorization.</param>
/// <param name="type">The type associated with the authorization.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> that can be used to abort the operation.</param>
/// <returns>
/// A <see cref="Task"/> that can be used to monitor the asynchronous operation.
/// </returns>
public virtual Task SetTypeAsync(TAuthorization authorization,
string type, CancellationToken cancellationToken)
{
if (authorization == null)
{
throw new ArgumentNullException(nameof(authorization));
}
authorization.Type = type;
return Task.CompletedTask;
}
/// <summary>
/// Updates an existing authorization.
/// </summary>
/// <param name="authorization">The authorization to update.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> that can be used to abort the operation.</param>
/// <returns>
/// A <see cref="Task"/> that can be used to monitor the asynchronous operation.
/// </returns>
public virtual async Task UpdateAsync(TAuthorization authorization, CancellationToken cancellationToken)
{
if (authorization == null)
{
throw new ArgumentNullException(nameof(authorization));
}
cancellationToken.ThrowIfCancellationRequested();
_session.Save(authorization, checkConcurrency: true);
try
{
await _session.CommitAsync();
}
catch (ConcurrencyException exception)
{
throw new OpenIddictExceptions.ConcurrencyException(new StringBuilder()
.AppendLine("The authorization was concurrently updated and cannot be persisted in its current state.")
.Append("Reload the authorization from the database and retry the operation.")
.ToString(), exception);
}
}
}
}
| |
using System;
using System.IO;
namespace Bsooner
{
public class FastBsonWriter : IDisposable
{
private Stream _stream;
private byte[] _buffer;
private readonly int _maxCharsInBuffer;
public const int DefaultBufferSize = 64;
public FastBsonWriter(Stream stream, int bufferSize = DefaultBufferSize)
{
if (!stream.CanSeek)
{
throw new NotSupportedException("Non seek-able streams are not supported");
}
_stream = stream;
_buffer = new byte[bufferSize];
_maxCharsInBuffer = _buffer.Length / BsonDefaults.MaxCharLength;
}
public Stream BaseStream
{
get { return _stream; }
}
public FastBsonWriter WriteProperty(string name, int value)
{
WriteType(BsonType.Int32).
WritePropertyName(name);
_buffer[0] = (byte)value;
_buffer[1] = (byte)(value >> 8);
_buffer[2] = (byte)(value >> 16);
_buffer[3] = (byte)(value >> 24);
_stream.Write(_buffer, 0, 4);
return this;
}
public FastBsonWriter WriteProperty(string name, int? value)
{
if (value.HasValue)
{
return WriteProperty(name, value.Value);
}
return WriteNullProperty(name);
}
public unsafe FastBsonWriter WriteProperty(string name, double value)
{
WriteType(BsonType.Double);
WritePropertyName(name);
ulong doubleAsULong = *(ulong*)&value;
_buffer[0] = (byte)doubleAsULong;
_buffer[1] = (byte)(doubleAsULong >> 8);
_buffer[2] = (byte)(doubleAsULong >> 16);
_buffer[3] = (byte)(doubleAsULong >> 24);
_buffer[4] = (byte)(doubleAsULong >> 32);
_buffer[5] = (byte)(doubleAsULong >> 40);
_buffer[6] = (byte)(doubleAsULong >> 48);
_buffer[7] = (byte)(doubleAsULong >> 56);
_stream.Write(_buffer, 0, 8);
return this;
}
public FastBsonWriter WriteProperty(string name, double? value)
{
if (value.HasValue)
{
return WriteProperty(name, value.Value);
}
return WriteNullProperty(name);
}
public FastBsonWriter WriteProperty(string name, bool value)
{
WriteType(BsonType.Boolean);
WritePropertyName(name);
_stream.WriteByte((byte)(value ? 1 : 0));
return this;
}
public FastBsonWriter WriteProperty(string name, bool? value)
{
if (value.HasValue)
{
return WriteProperty(name, value.Value);
}
return WriteNullProperty(name);
}
public FastBsonWriter WriteProperty(string name, long value)
{
WriteType(BsonType.Int64).
WritePropertyName(name);
WriteLong(value);
return this;
}
public FastBsonWriter WriteProperty(string name, long? value)
{
if (value.HasValue)
{
return WriteProperty(name, value.Value);
}
return WriteNullProperty(name);
}
public FastBsonWriter WriteBinary(string name, byte[] value)
{
if (value == null)
{
return WriteNullProperty(name);
}
WriteType(BsonType.Binary);
WritePropertyName(name);
WriteInt(value.Length);
_stream.WriteByte((byte)BinaryType.Generic);
_stream.Write(value, 0, value.Length);
return this;
}
public FastBsonWriter WriteStruct<TDocument>(string name, TDocument value)
where TDocument : struct
{
WriteType(BsonType.Document);
WritePropertyName(name);
BsonSerializer<TDocument>.Instance.Serialize(this, value);
return this;
}
public FastBsonWriter WriteNullableStruct<TDocument>(string name, TDocument? value)
where TDocument : struct
{
if (value.HasValue)
{
return WriteStruct(name, value.Value);
}
return WriteNullProperty(name);
}
public FastBsonWriter WriteClass<TDocument>(string name, TDocument value)
where TDocument : class
{
if (value != null)
{
WriteType(BsonType.Document);
WritePropertyName(name);
BsonSerializer<TDocument>.Instance.Serialize(this, value);
return this;
}
return WriteNullProperty(name);
}
public FastBsonWriter WriteProperty(string name, string value)
{
if (value == null)
{
return WriteNullProperty(name);
}
WriteType(BsonType.String);
WritePropertyName(name);
//placeholder
WriteInt(0);
var startPosition = _stream.Position;
WriteString(value);
_stream.WriteByte(0); //string terminator
var endPosition = _stream.Position;
var length = endPosition - startPosition; //plus terminator
_stream.Position = startPosition - 4;
WriteInt((int)length);
_stream.Position = endPosition;
return this;
}
public FastBsonWriter WriteProperty(string name, DateTime value)
{
var utcValue = value.ToUniversalTime();
long milliSeconds = (long)(utcValue - BsonDefaults.UnixEpoch).TotalMilliseconds;
WriteType(BsonType.UtcDateTime);
WritePropertyName(name)
.WriteLong(milliSeconds);
return this;
}
public FastBsonWriter WriteProperty(string name, DateTime? value)
{
if (value.HasValue)
{
return WriteProperty(name, value.Value);
}
return WriteNullProperty(name);
}
public FastBsonWriter WriteBsonId(string name, string value)
{
WriteType(BsonType.ObjectId);
WritePropertyName(name);
//empty id
if (string.IsNullOrWhiteSpace(value))
{
Array.Clear(_buffer, 0, 12);
}
else
{
value.EnsureValidObjectIdString();
_buffer[0] = value.ToByteFromHex(0);
_buffer[1] = value.ToByteFromHex(2);
_buffer[2] = value.ToByteFromHex(4);
_buffer[3] = value.ToByteFromHex(6);
_buffer[4] = value.ToByteFromHex(8);
_buffer[5] = value.ToByteFromHex(10);
_buffer[6] = value.ToByteFromHex(12);
_buffer[7] = value.ToByteFromHex(14);
_buffer[8] = value.ToByteFromHex(16);
_buffer[9] = value.ToByteFromHex(18);
_buffer[10] = value.ToByteFromHex(20);
_buffer[11] = value.ToByteFromHex(22);
}
_stream.Write(_buffer, 0, 12);
return this;
}
public FastBsonWriter WriteBsonId(string name, ObjectId? value)
{
if (value.HasValue)
{
return WriteBsonId(name, value.Value);
}
return WriteNullProperty(name);
}
public FastBsonWriter WriteBsonId(string name, ObjectId value)
{
WriteType(BsonType.ObjectId);
WritePropertyName(name);
_buffer[0] = value.Byte01;
_buffer[1] = value.Byte02;
_buffer[2] = value.Byte03;
_buffer[3] = value.Byte04;
_buffer[4] = value.Byte05;
_buffer[5] = value.Byte06;
_buffer[6] = value.Byte07;
_buffer[7] = value.Byte08;
_buffer[8] = value.Byte09;
_buffer[9] = value.Byte10;
_buffer[10] = value.Byte11;
_buffer[11] = value.Byte12;
_stream.Write(_buffer, 0, 12);
return this;
}
private FastBsonWriter WriteType(BsonType bsonType)
{
_stream.WriteByte((byte) bsonType);
return this;
}
private FastBsonWriter WritePropertyName(string name)
{
if (string.IsNullOrWhiteSpace(name))
{
throw new ArgumentException("property name could not be null", "name");
}
WriteString(name);
_stream.WriteByte(0);// string terminator
return this;
}
private FastBsonWriter WriteNullProperty(string name)
{
WriteType(BsonType.Null);
WritePropertyName(name);
return this;
}
internal void WriteInt(int value)
{
_buffer[0] = (byte)value;
_buffer[1] = (byte)(value >> 8);
_buffer[2] = (byte)(value >> 16);
_buffer[3] = (byte)(value >> 24);
_stream.Write(_buffer, 0, 4);
}
private unsafe void WriteString(string value)
{
int charStart = 0;
int numLeft = value.Length;
while (numLeft > 0)
{
int charsToProceed = (numLeft > _maxCharsInBuffer) ? _maxCharsInBuffer : numLeft;
int byteLen;
fixed (char* pChars = value)
{
fixed (byte* pBytes = _buffer)
{
byteLen = BsonDefaults.Encoder.GetBytes(pChars + charStart, charsToProceed, pBytes, _buffer.Length, charsToProceed == numLeft);
}
}
_stream.Write(_buffer, 0, byteLen);
charStart += charsToProceed;
numLeft -= charsToProceed;
}
}
private void WriteLong(long value)
{
_buffer[0] = (byte)value;
_buffer[1] = (byte)(value >> 8);
_buffer[2] = (byte)(value >> 16);
_buffer[3] = (byte)(value >> 24);
_buffer[4] = (byte)(value >> 32);
_buffer[5] = (byte)(value >> 40);
_buffer[6] = (byte)(value >> 48);
_buffer[7] = (byte)(value >> 56);
_stream.Write(_buffer, 0, 8);
}
public void Dispose()
{
_stream = null;
_buffer = null;
}
}
}
| |
using UnityEngine;
using UnityEditor;
using System.Collections.Generic;
using System.Linq;
public static class tk2dSpriteGuiUtility
{
public static int NameCompare(string na, string nb)
{
if (na.Length == 0 && nb.Length != 0) return 1;
else if (na.Length != 0 && nb.Length == 0) return -1;
else if (na.Length == 0 && nb.Length == 0) return 0;
int numStartA = na.Length - 1;
// last char is not a number, compare as regular strings
if (na[numStartA] < '0' || na[numStartA] > '9')
return System.String.Compare(na, nb, true);
while (numStartA > 0 && na[numStartA - 1] >= '0' && na[numStartA - 1] <= '9')
numStartA--;
int comp = System.String.Compare(na, 0, nb, 0, numStartA);
if (comp == 0)
{
if (nb.Length > numStartA)
{
bool numeric = true;
for (int i = numStartA; i < nb.Length; ++i)
{
if (nb[i] < '0' || nb[i] > '9')
{
numeric = false;
break;
}
}
if (numeric)
{
int numA = System.Convert.ToInt32(na.Substring(numStartA));
int numB = System.Convert.ToInt32(nb.Substring(numStartA));
return numA - numB;
}
}
}
return System.String.Compare(na, nb);
}
public delegate void SpriteChangedCallback(tk2dSpriteCollectionData spriteCollection, int spriteIndex, object callbackData);
class SpriteCollectionLUT
{
public int buildKey;
public string[] sortedSpriteNames;
public int[] spriteIdToSortedList;
public int[] sortedListToSpriteId;
}
static Dictionary<string, SpriteCollectionLUT> spriteSelectorLUT = new Dictionary<string, SpriteCollectionLUT>();
static int GetNamedSpriteInNewCollection(tk2dSpriteCollectionData spriteCollection, int spriteId, tk2dSpriteCollectionData newCollection) {
int newSpriteId = spriteId;
string oldSpriteName = (spriteCollection == null || spriteCollection.inst == null) ? "" : spriteCollection.inst.spriteDefinitions[spriteId].name;
int distance = -1;
for (int i = 0; i < newCollection.inst.spriteDefinitions.Length; ++i) {
if (newCollection.inst.spriteDefinitions[i].Valid) {
string newSpriteName = newCollection.inst.spriteDefinitions[i].name;
int tmpDistance = (newSpriteName == oldSpriteName) ? 0 :
Mathf.Abs ( (oldSpriteName.ToLower()).CompareTo(newSpriteName.ToLower ()));
if (distance == -1 || tmpDistance < distance) {
distance = tmpDistance;
newSpriteId = i;
}
}
}
return newSpriteId;
}
public static bool showOpenEditShortcuts = true;
public static void SpriteSelector( tk2dSpriteCollectionData spriteCollection, int spriteId, SpriteChangedCallback callback, object callbackData) {
tk2dSpriteCollectionData newCollection = spriteCollection;
int newSpriteId = spriteId;
GUILayout.BeginHorizontal();
GUILayout.BeginVertical();
GUILayout.BeginHorizontal();
newCollection = SpriteCollectionList("Collection", newCollection);
if (newCollection != spriteCollection) {
newSpriteId = GetNamedSpriteInNewCollection( spriteCollection, spriteId, newCollection );
}
if (showOpenEditShortcuts && newCollection != null && GUILayout.Button("o", EditorStyles.miniButton, GUILayout.Width(18))) {
EditorGUIUtility.PingObject(newCollection);
}
GUILayout.EndHorizontal();
if (newCollection != null && newCollection.Count != 0) {
if (newSpriteId < 0 || newSpriteId >= newCollection.Count || !newCollection.inst.spriteDefinitions[newSpriteId].Valid) {
newSpriteId = newCollection.FirstValidDefinitionIndex;
}
GUILayout.BeginHorizontal();
newSpriteId = SpriteList( "Sprite", newSpriteId, newCollection );
if ( showOpenEditShortcuts &&
newCollection != null && newCollection.dataGuid != TransientGUID &&
GUILayout.Button( "e", EditorStyles.miniButton, GUILayout.Width(18), GUILayout.MaxHeight( 14f ) ) ) {
tk2dSpriteCollection gen = AssetDatabase.LoadAssetAtPath( AssetDatabase.GUIDToAssetPath(newCollection.spriteCollectionGUID), typeof(tk2dSpriteCollection) ) as tk2dSpriteCollection;
if ( gen != null ) {
tk2dSpriteCollectionEditorPopup v = EditorWindow.GetWindow( typeof(tk2dSpriteCollectionEditorPopup), false, "Sprite Collection Editor" ) as tk2dSpriteCollectionEditorPopup;
v.SetGeneratorAndSelectedSprite(gen, newSpriteId);
v.Show();
}
}
GUILayout.EndHorizontal();
}
GUILayout.EndVertical();
if (newCollection != null && GUILayout.Button("...", GUILayout.Height(32), GUILayout.Width(32))) {
SpriteSelectorPopup( newCollection, newSpriteId, callback, callbackData );
}
GUILayout.EndHorizontal();
// Handle drag and drop
Rect rect = GUILayoutUtility.GetLastRect();
if (rect.Contains(Event.current.mousePosition)) {
if (Event.current.type == EventType.DragUpdated) {
bool valid = false;
if (DragAndDrop.objectReferences.Length == 1 && DragAndDrop.objectReferences[0] is GameObject) {
GameObject go = DragAndDrop.objectReferences[0] as GameObject;
if (go.GetComponent<tk2dSpriteCollection>() || go.GetComponent<tk2dSpriteCollectionData>()) {
valid = true;
}
Event.current.Use();
}
if (valid) {
DragAndDrop.visualMode = DragAndDropVisualMode.Copy;
}
else {
DragAndDrop.visualMode = DragAndDropVisualMode.None;
}
Event.current.Use();
}
else if (Event.current.type == EventType.DragPerform) {
DragAndDrop.visualMode = DragAndDropVisualMode.None;
Event.current.Use();
GameObject go = DragAndDrop.objectReferences[0] as GameObject;
tk2dSpriteCollection sc = go.GetComponent<tk2dSpriteCollection>();
tk2dSpriteCollectionData scd = go.GetComponent<tk2dSpriteCollectionData>();
if (sc != null && scd == null) {
scd = sc.spriteCollection;
}
if (scd != null) {
newCollection = scd;
if (newCollection != spriteCollection) {
newSpriteId = GetNamedSpriteInNewCollection( spriteCollection, spriteId, newCollection );
}
}
}
}
// Final callback
if (callback != null && (newCollection != spriteCollection || newSpriteId != spriteId)) {
callback(newCollection, newSpriteId, callbackData);
}
}
public static void SpriteSelectorPopup( tk2dSpriteCollectionData spriteCollection, int spriteId, SpriteChangedCallback callback, object callbackData) {
tk2dSpritePickerPopup.DoPickSprite(spriteCollection, spriteId, "Select sprite", callback, callbackData);
}
static int SpriteList(string label, int spriteId, tk2dSpriteCollectionData rootSpriteCollection)
{
tk2dSpriteCollectionData spriteCollection = rootSpriteCollection.inst;
int newSpriteId = spriteId;
// cope with guid not existing
if (spriteCollection.dataGuid == null || spriteCollection.dataGuid.Length == 0)
{
spriteCollection.dataGuid = AssetDatabase.AssetPathToGUID(AssetDatabase.GetAssetPath(spriteCollection));
}
SpriteCollectionLUT lut = null;
spriteSelectorLUT.TryGetValue(spriteCollection.dataGuid, out lut);
if (lut == null)
{
lut = new SpriteCollectionLUT();
lut.buildKey = spriteCollection.buildKey - 1; // force mismatch
spriteSelectorLUT[spriteCollection.dataGuid] = lut;
}
if (lut.buildKey != spriteCollection.buildKey)
{
var spriteDefs = spriteCollection.spriteDefinitions;
string[] spriteNames = new string[spriteDefs.Length];
int[] spriteLookupIndices = new int[spriteNames.Length];
for (int i = 0; i < spriteDefs.Length; ++i)
{
if (spriteDefs[i].name != null && spriteDefs[i].name.Length > 0)
{
if (tk2dPreferences.inst.showIds)
spriteNames[i] = spriteDefs[i].name + "\t[" + i.ToString() + "]";
else
spriteNames[i] = spriteDefs[i].name;
spriteLookupIndices[i] = i;
}
}
System.Array.Sort(spriteLookupIndices, (int a, int b) => tk2dSpriteGuiUtility.NameCompare((spriteDefs[a]!=null)?spriteDefs[a].name:"", (spriteDefs[b]!=null)?spriteDefs[b].name:""));
lut.sortedSpriteNames = new string[spriteNames.Length];
lut.sortedListToSpriteId = new int[spriteNames.Length];
lut.spriteIdToSortedList = new int[spriteNames.Length];
for (int i = 0; i < spriteLookupIndices.Length; ++i)
{
lut.spriteIdToSortedList[spriteLookupIndices[i]] = i;
lut.sortedListToSpriteId[i] = spriteLookupIndices[i];
lut.sortedSpriteNames[i] = spriteNames[spriteLookupIndices[i]];
}
lut.buildKey = spriteCollection.buildKey;
}
GUILayout.BeginHorizontal();
if (spriteId >= 0 && spriteId < lut.spriteIdToSortedList.Length) {
int spriteLocalIndex = lut.spriteIdToSortedList[spriteId];
int newSpriteLocalIndex = (label == null)?EditorGUILayout.Popup(spriteLocalIndex, lut.sortedSpriteNames):EditorGUILayout.Popup(label, spriteLocalIndex, lut.sortedSpriteNames);
if (newSpriteLocalIndex != spriteLocalIndex)
{
newSpriteId = lut.sortedListToSpriteId[newSpriteLocalIndex];
}
}
GUILayout.EndHorizontal();
return newSpriteId;
}
static List<tk2dSpriteCollectionIndex> allSpriteCollections = new List<tk2dSpriteCollectionIndex>();
static Dictionary<string, int> allSpriteCollectionLookup = new Dictionary<string, int>();
static string[] spriteCollectionNames = new string[0];
static string[] spriteCollectionNamesInclTransient = new string[0];
public static void GetSpriteCollectionAndCreate( System.Action<tk2dSpriteCollectionData> create ) {
// try to inherit from other Sprites in scene
tk2dBaseSprite spr = GameObject.FindObjectOfType(typeof(tk2dBaseSprite)) as tk2dBaseSprite;
if (spr) {
create( spr.Collection );
return;
}
else {
tk2dSpriteCollectionData data = GetDefaultSpriteCollection();
if (data != null) {
create( data );
return;
}
}
EditorUtility.DisplayDialog("Create Sprite", "Unable to create sprite as no valid SpriteCollections have been found.", "Ok");
}
public static tk2dSpriteCollectionData GetDefaultSpriteCollection() {
BuildLookupIndex(false);
foreach (tk2dSpriteCollectionIndex indexEntry in allSpriteCollections)
{
if (!indexEntry.managedSpriteCollection && indexEntry.spriteNames != null)
{
foreach (string name in indexEntry.spriteNames)
{
if (name != null && name.Length > 0)
{
GameObject scgo = AssetDatabase.LoadAssetAtPath(AssetDatabase.GUIDToAssetPath(indexEntry.spriteCollectionDataGUID), typeof(GameObject)) as GameObject;
if (scgo != null)
return scgo.GetComponent<tk2dSpriteCollectionData>();
}
}
}
}
Debug.LogError("Unable to find any sprite collections.");
return null;
}
static void BuildLookupIndex(bool force)
{
if (force)
tk2dEditorUtility.ForceCreateIndex();
allSpriteCollections = new List<tk2dSpriteCollectionIndex>();
tk2dSpriteCollectionIndex[] mainIndex = tk2dEditorUtility.GetOrCreateIndex().GetSpriteCollectionIndex();
foreach (tk2dSpriteCollectionIndex i in mainIndex)
{
if (!i.managedSpriteCollection)
allSpriteCollections.Add(i);
}
allSpriteCollections = allSpriteCollections.OrderBy( e => e.name, new tk2dEditor.Shared.NaturalComparer() ).ToList();
allSpriteCollectionLookup = new Dictionary<string, int>();
string spriteCollectionFolderSeparator = "__";
spriteCollectionNames = new string[allSpriteCollections.Count];
spriteCollectionNamesInclTransient = new string[allSpriteCollections.Count + 1];
for (int i = 0; i < allSpriteCollections.Count; ++i)
{
allSpriteCollectionLookup[allSpriteCollections[i].spriteCollectionDataGUID] = i;
string name = allSpriteCollections[i].name.Replace(spriteCollectionFolderSeparator, "/");
spriteCollectionNames[i] = name;
spriteCollectionNamesInclTransient[i] = name;
}
spriteCollectionNamesInclTransient[allSpriteCollections.Count] = "-"; // transient sprite collection
}
public static void ResetCache()
{
allSpriteCollections.Clear();
}
static tk2dSpriteCollectionData GetSpriteCollectionDataAtIndex(int index, tk2dSpriteCollectionData defaultValue)
{
if (index >= allSpriteCollections.Count) return defaultValue;
GameObject go = AssetDatabase.LoadAssetAtPath(AssetDatabase.GUIDToAssetPath(allSpriteCollections[index].spriteCollectionDataGUID), typeof(GameObject)) as GameObject;
if (go == null) return defaultValue;
tk2dSpriteCollectionData data = go.GetComponent<tk2dSpriteCollectionData>();
if (data == null) return defaultValue;
return data;
}
public static string TransientGUID { get { return "transient"; } }
public static int GetValidSpriteId(tk2dSpriteCollectionData spriteCollection, int spriteId)
{
if (! (spriteId > 0 && spriteId < spriteCollection.spriteDefinitions.Length &&
spriteCollection.spriteDefinitions[spriteId].Valid) )
{
spriteId = spriteCollection.FirstValidDefinitionIndex;
if (spriteId == -1) spriteId = 0;
}
return spriteId;
}
public static tk2dSpriteCollectionData SpriteCollectionList(tk2dSpriteCollectionData currentValue) {
// Initialize guid if not present
if (currentValue != null && (currentValue.dataGuid == null || currentValue.dataGuid.Length == 0))
{
string guid = AssetDatabase.AssetPathToGUID(AssetDatabase.GetAssetPath(currentValue));
currentValue.dataGuid = (guid.Length == 0)?TransientGUID:guid;
}
if (allSpriteCollections == null || allSpriteCollections.Count == 0)
BuildLookupIndex(false);
// if the sprite collection asset path == "", it means its either been created in the scene, or loaded from an asset bundle
if (currentValue == null || AssetDatabase.GetAssetPath(currentValue).Length == 0 || currentValue.dataGuid == TransientGUID)
{
int currentSelection = allSpriteCollections.Count;
int newSelection = EditorGUILayout.Popup(currentSelection, spriteCollectionNamesInclTransient);
if (newSelection != currentSelection)
{
currentValue = GetSpriteCollectionDataAtIndex(newSelection, currentValue);
GUI.changed = true;
}
}
else
{
int currentSelection = -1;
for (int iter = 0; iter < 2; ++iter) // 2 passes in worst case
{
for (int i = 0; i < allSpriteCollections.Count; ++i)
{
if (allSpriteCollections[i].spriteCollectionDataGUID == currentValue.dataGuid)
{
currentSelection = i;
break;
}
}
if (currentSelection != -1) break; // found something on first pass
// we are missing a sprite collection, rebuild index
BuildLookupIndex(true);
}
if (currentSelection == -1)
{
Debug.LogError("Unable to find sprite collection. This is a serious problem.");
GUILayout.Label(currentValue.spriteCollectionName, EditorStyles.popup);
}
else
{
int newSelection = EditorGUILayout.Popup(currentSelection, spriteCollectionNames);
if (newSelection != currentSelection)
{
tk2dSpriteCollectionData newData = GetSpriteCollectionDataAtIndex(newSelection, currentValue);
if (newData == null)
{
Debug.LogError("Unable to load sprite collection. Please rebuild index and try again.");
}
else if (newData.Count == 0)
{
EditorUtility.DisplayDialog("Error",
string.Format("Sprite collection '{0}' has no sprites", newData.name),
"Ok");
}
else if (newData != currentValue)
{
currentValue = newData;
GUI.changed = true;
}
}
}
}
return currentValue;
}
public static tk2dSpriteCollectionData SpriteCollectionList(string label, tk2dSpriteCollectionData currentValue)
{
GUILayout.BeginHorizontal();
if (label.Length > 0)
EditorGUILayout.PrefixLabel(label);
currentValue = SpriteCollectionList(currentValue);
GUILayout.EndHorizontal();
return currentValue;
}
}
| |
using Microsoft.SPOT.Hardware;
namespace uScoober.Hardware.I2C
{
/// <summary>Base class for I2C peripheral device drivers</summary>
public abstract class I2CDeviceCore : DisposableBase,
II2CDevice
{
private readonly byte[] _buffer1 = new byte[1];
private readonly byte[] _buffer2 = new byte[2];
private readonly byte[] _buffer3 = new byte[3];
private readonly II2CBus _bus;
private readonly I2CDevice.Configuration _config;
private readonly byte[] _registerAddressBuffer = new byte[1];
private int _timeoutMilliseconds;
protected I2CDeviceCore(II2CBus bus, ushort address, int clockRateKhz) {
_config = new I2CDevice.Configuration(address, clockRateKhz);
_bus = bus;
_timeoutMilliseconds = 1000;
}
public ushort Address {
get { return _config.Address; }
}
public int TimeoutMilliseconds {
get { return _timeoutMilliseconds; }
set { _timeoutMilliseconds = value; }
}
protected I2CDevice.I2CReadTransaction CreateReadTransaction(params byte[] buffer) {
return _bus.CreateReadTransaction(buffer);
}
protected I2CDevice.I2CWriteTransaction CreateWriteTransaction(params byte[] buffer) {
return _bus.CreateWriteTransaction(buffer);
}
protected int Execute(I2CDevice.I2CTransaction action) {
lock (_bus) {
return _bus.Execute(_config,
new[] {
action
},
_timeoutMilliseconds);
}
}
protected int Execute(I2CDevice.I2CTransaction[] actions) {
lock (_bus) {
return _bus.Execute(_config, actions, _timeoutMilliseconds);
}
}
protected bool Read(out byte value) {
lock (_bus) {
bool success = _bus.Read(_config, _buffer1, _timeoutMilliseconds);
if (!success) {
value = 0;
return false;
}
value = _buffer1[0];
return true;
}
}
protected bool Read(byte[] readBuffer) {
lock (_bus) {
return _bus.Read(_config, readBuffer, _timeoutMilliseconds);
}
}
protected bool Read(out ushort value, ByteOrder byteOrder) {
lock (_bus) {
bool success = _bus.Read(_config, _buffer2, _timeoutMilliseconds);
if (!success) {
value = 0;
return false;
}
if (byteOrder == ByteOrder.BigEndian) {
value = (ushort)(_buffer2[0] << 8 | _buffer2[1]);
}
else {
value = (ushort)(_buffer2[1] << 8 | _buffer2[0]);
}
return true;
}
}
protected bool ReadRegister(byte address, out byte value) {
lock (_bus) {
_registerAddressBuffer[0] = address;
bool success = _bus.WriteRead(_config, _registerAddressBuffer, _buffer1, _timeoutMilliseconds);
if (!success) {
value = 0;
return false;
}
value = _buffer1[0];
return true;
}
}
protected bool ReadRegister(byte address, out ushort value, ByteOrder byteOrder) {
lock (_bus) {
_registerAddressBuffer[0] = address;
bool success = _bus.WriteRead(_config, _registerAddressBuffer, _buffer2, _timeoutMilliseconds);
if (!success) {
value = 0;
return false;
}
if (byteOrder == ByteOrder.BigEndian) {
value = (ushort)(_buffer2[0] << 8 | _buffer2[1]);
}
else {
value = (ushort)(_buffer2[1] << 8 | _buffer2[0]);
}
return true;
}
}
protected bool ReadRegister(byte address, byte[] buffer) {
lock (_bus) {
_registerAddressBuffer[0] = address;
return _bus.WriteRead(_config, _registerAddressBuffer, buffer, _timeoutMilliseconds);
}
}
protected bool Write(byte[] writeBuffer) {
lock (_bus) {
return _bus.Write(_config, writeBuffer, _timeoutMilliseconds);
}
}
protected bool Write(byte value) {
lock (_bus) {
_buffer1[0] = value;
return _bus.Write(_config, _buffer1, _timeoutMilliseconds);
}
}
protected bool Write(ushort value, ByteOrder byteOrder) {
lock (_bus) {
if (byteOrder == ByteOrder.BigEndian) {
_buffer2[1] = (byte)(value >> 8);
_buffer2[2] = (byte)value;
}
else {
_buffer2[2] = (byte)(value >> 8);
_buffer2[1] = (byte)value;
}
return _bus.Write(_config, _buffer2, _timeoutMilliseconds);
}
}
protected bool WriteRead(byte[] writeBuffer, byte[] readBuffer) {
lock (_bus) {
return _bus.WriteRead(_config, writeBuffer, readBuffer, _timeoutMilliseconds);
}
}
protected bool WriteRegister(byte address, ushort value, ByteOrder byteOrder) {
lock (_bus) {
_buffer3[0] = address;
if (byteOrder == ByteOrder.BigEndian) {
_buffer3[1] = (byte)(value >> 8);
_buffer3[2] = (byte)value;
}
else {
_buffer3[2] = (byte)(value >> 8);
_buffer3[1] = (byte)value;
}
return _bus.Write(_config, _buffer3, _timeoutMilliseconds);
}
}
protected bool WriteRegister(byte address, byte[] buffer) {
lock (_bus) {
var temp = new byte[buffer.Length + 1];
temp[0] = address;
buffer.CopyTo(temp, 1);
return _bus.Write(_config, temp, _timeoutMilliseconds);
}
}
protected bool WriteRegister(byte address, byte value) {
lock (_bus) {
_buffer2[0] = address;
_buffer2[1] = value;
return _bus.Write(_config, _buffer2, _timeoutMilliseconds);
}
}
I2CDevice.I2CReadTransaction II2CDevice.CreateReadTransaction(params byte[] buffer) {
return CreateReadTransaction(buffer);
}
I2CDevice.I2CWriteTransaction II2CDevice.CreateWriteTransaction(params byte[] buffer) {
return CreateWriteTransaction(buffer);
}
int II2CDevice.Execute(I2CDevice.I2CTransaction action) {
return Execute(action);
}
int II2CDevice.Execute(I2CDevice.I2CTransaction[] actions) {
return Execute(actions);
}
bool II2CDevice.Read(byte[] readBuffer) {
return Read(readBuffer);
}
bool II2CDevice.Read(out byte value) {
return Read(out value);
}
bool II2CDevice.Read(out ushort value, ByteOrder byteOrder) {
return Read(out value, byteOrder);
}
bool II2CDevice.ReadRegister(byte address, out byte value) {
return ReadRegister(address, out value);
}
bool II2CDevice.ReadRegister(byte address, out ushort value, ByteOrder byteOrder) {
return ReadRegister(address, out value, byteOrder);
}
bool II2CDevice.ReadRegister(byte address, byte[] buffer) {
return ReadRegister(address, buffer);
}
bool II2CDevice.Write(byte[] writeBuffer) {
return Write(writeBuffer);
}
bool II2CDevice.Write(byte value) {
return Write(value);
}
bool II2CDevice.Write(ushort value, ByteOrder byteOrder) {
return Write(value, byteOrder);
}
bool II2CDevice.WriteRead(byte[] writeBuffer, byte[] readBuffer) {
return WriteRead(writeBuffer, readBuffer);
}
bool II2CDevice.WriteRegister(byte address, ushort value, ByteOrder byteOrder) {
return WriteRegister(address, value, byteOrder);
}
bool II2CDevice.WriteRegister(byte address, byte[] buffer) {
return WriteRegister(address, buffer);
}
bool II2CDevice.WriteRegister(byte address, byte value) {
return WriteRegister(address, value);
}
}
}
| |
///////////////////////////////////////////////////////////////////////////////////
// Open 3D Model Viewer (open3mod) (v2.0)
// [AnimationInspectionView.cs]
// (c) 2012-2015, Open3Mod Contributors
//
// Licensed under the terms and conditions of the 3-clause BSD license. See
// the LICENSE file in the root folder of the repository for the details.
//
// HIS 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.Diagnostics;
using System.Drawing;
using System.Windows.Forms;
using Assimp;
namespace open3mod
{
public sealed partial class AnimationInspectionView : UserControl
{
private readonly Scene _scene;
private Timer _timer;
private double _duration;
private bool _playing;
private double _animPlaybackSpeed = 1.0;
private const int TimerInterval = 30;
private const double PlaybackSpeedAdjustFactor = 0.6666;
private int _speedAdjust;
private const int MaxSpeedAdjustLevels = 8;
private readonly Image _imagePlay;
private readonly Image _imageStop;
public AnimationInspectionView(Scene scene, TabPage tabPageAnimations)
{
_scene = scene;
Anchor = AnchorStyles.Left | AnchorStyles.Right | AnchorStyles.Top;
Dock = DockStyle.Fill;
InitializeComponent();
tabPageAnimations.Controls.Add(this);
listBoxAnimations.Items.Add("None (Bind Pose)");
if (scene.Raw.Animations != null)
{
foreach (var anim in scene.Raw.Animations)
{
listBoxAnimations.Items.Add(FormatAnimationName(anim));
}
}
listBoxAnimations.SelectedIndex = 0;
checkBoxLoop.Checked = _scene.SceneAnimator.Loop;
_imagePlay = ImageFromResource.Get("open3mod.Images.PlayAnim.png");
_imageStop = ImageFromResource.Get("open3mod.Images.StopAnim.png");
buttonPlay.Image = _imagePlay;
// initially, animations are disabled.
_scene.SceneAnimator.AnimationPlaybackSpeed = 0.0;
labelSpeedValue.Text = "1.0x";
timeSlideControl.Rewind += (o, args) =>
{
if (_scene.SceneAnimator.ActiveAnimation >= 0)
{
_scene.SceneAnimator.AnimationCursor = args.NewPosition;
}
};
}
private static string FormatAnimationName(Animation anim)
{
var dur = anim.DurationInTicks;
if (anim.TicksPerSecond > 1e-10)
{
dur /= anim.TicksPerSecond;
}
else
{
dur /= SceneAnimator.DefaultTicksPerSecond;
}
string text = string.Format("{0} ({1}s)", anim.Name, dur.ToString("0.000"));
return text;
}
public bool Empty
{
get { return _scene.Raw.AnimationCount == 0; }
}
public bool Playing
{
get { return _playing; }
set
{
if (value == _playing)
{
return;
}
_playing = value;
if (value)
{
StartPlayingTimer();
_scene.SceneAnimator.AnimationPlaybackSpeed = _scene.SceneAnimator.ActiveAnimation >= 0 ? AnimPlaybackSpeed : 0.0;
}
else
{
StopPlayingTimer();
_scene.SceneAnimator.AnimationPlaybackSpeed = 0.0;
}
}
}
public double AnimPlaybackSpeed
{
get { return _animPlaybackSpeed; }
private set {
Debug.Assert(value > 1e-6, "use Playing=false to not play animations");
_animPlaybackSpeed = value;
// avoid float noise close to 1
if (Math.Abs(_animPlaybackSpeed-1) < 1e-7)
{
_animPlaybackSpeed = 1.0;
}
if (_playing)
{
_scene.SceneAnimator.AnimationPlaybackSpeed = AnimPlaybackSpeed;
}
BeginInvoke(new MethodInvoker(() =>
{
labelSpeedValue.Text = string.Format("{0}x", _animPlaybackSpeed.ToString("0.00"));
}));
}
}
private Animation ActiveRawAnimation
{
get {
return listBoxAnimations.SelectedIndex == 0
? null
: _scene.Raw.Animations[listBoxAnimations.SelectedIndex - 1];
}
}
private void StopPlayingTimer()
{
if (_timer != null)
{
_timer.Stop();
_timer = null;
}
}
private void StartPlayingTimer()
{
if (!Playing)
{
return;
}
_timer = new Timer { Interval = (TimerInterval) };
_timer.Tick += (o, args) =>
{
var d = _scene.SceneAnimator.AnimationCursor;
if (!_scene.SceneAnimator.IsInEndPosition)
{
d %= _duration;
}
timeSlideControl.Position = d;
};
_timer.Start();
}
private void OnChangeSelectedAnimation(object sender, EventArgs e)
{
_scene.SceneAnimator.ActiveAnimation = listBoxAnimations.SelectedIndex - 1;
if (_scene.SceneAnimator.ActiveAnimation >= 0 && ActiveRawAnimation.DurationInTicks > 0.0)
{
var anim = ActiveRawAnimation;
foreach (var control in panelAnimTools.Controls)
{
if (control == buttonSlower && _speedAdjust == -MaxSpeedAdjustLevels ||
control == buttonFaster && _speedAdjust == MaxSpeedAdjustLevels)
{
continue;
}
((Control)control).Enabled = true;
}
_duration = _scene.SceneAnimator.AnimationDuration;
timeSlideControl.RangeMin = 0.0;
timeSlideControl.RangeMax = _duration;
timeSlideControl.Position = 0.0;
_scene.SceneAnimator.AnimationCursor = 0;
StartPlayingTimer();
}
else
{
foreach(var control in panelAnimTools.Controls)
{
((Control) control).Enabled = false;
}
StopPlayingTimer();
}
}
private void OnPlay(object sender, EventArgs e)
{
Playing = !Playing;
buttonPlay.Image = Playing ? _imageStop : _imagePlay;
}
private void OnSlower(object sender, EventArgs e)
{
Debug.Assert(_speedAdjust > -MaxSpeedAdjustLevels);
if (--_speedAdjust == -MaxSpeedAdjustLevels)
{
buttonSlower.Enabled = false;
}
buttonFaster.Enabled = true;
AnimPlaybackSpeed *= PlaybackSpeedAdjustFactor;
}
private void OnFaster(object sender, EventArgs e)
{
Debug.Assert(_speedAdjust < MaxSpeedAdjustLevels);
if (++_speedAdjust == MaxSpeedAdjustLevels)
{
buttonFaster.Enabled = false;
}
buttonSlower.Enabled = true;
AnimPlaybackSpeed /= PlaybackSpeedAdjustFactor;
}
private void OnChangeLooping(object sender, EventArgs e)
{
_scene.SceneAnimator.Loop = checkBoxLoop.Checked;
}
private void OnGoTo(object sender, KeyEventArgs e)
{
labelGotoError.Text = "";
if (e.KeyCode != Keys.Enter)
{
return;
}
var text = textBoxGoto.Text;
double pos;
try
{
pos = Double.Parse(text);
if (pos < 0 || pos > _duration)
{
throw new FormatException();
}
}
catch(FormatException)
{
labelGotoError.Text = "Not a valid time";
return;
}
Debug.Assert(pos >= 0);
_scene.SceneAnimator.AnimationCursor = pos;
}
private void OnDeleteAnimation(object sender, EventArgs e)
{
Animation animation = ActiveRawAnimation;
if (animation == null)
{
return;
}
int oldIndex = FindAnimationIndex(animation);
_scene.UndoStack.PushAndDo("Delete Animation " + animation.Name,
// Do
() =>
{
_scene.Raw.Animations.Remove(animation);
listBoxAnimations.Items.RemoveAt(oldIndex + 1);
_scene.SceneAnimator.ActiveAnimation = -1;
},
// Undo
() =>
{
_scene.Raw.Animations.Insert(oldIndex, animation);
listBoxAnimations.Items.Insert(oldIndex + 1, FormatAnimationName(animation));
listBoxAnimations.SelectedIndex = oldIndex + 1;
});
}
private void OnRenameAnimation(object sender, EventArgs e)
{
if (ActiveRawAnimation == null)
{
return;
}
Animation animation = ActiveRawAnimation;
SafeRenamer renamer = new SafeRenamer(_scene);
// Animations names need not be unique even amongst themselves, but it's good if they are.
// Put all names in the entire scene into the greylist.
RenameDialog dialog = new RenameDialog(animation.Name, new HashSet<string>(),
renamer.GetAllAnimationNames());
if (dialog.ShowDialog() == DialogResult.OK)
{
string newName = dialog.NewName;
string oldName = animation.Name;
_scene.UndoStack.PushAndDo("Rename Animation",
// Do
() => renamer.RenameAnimation(animation, newName),
// Undo
() => renamer.RenameAnimation(animation, oldName),
// Update
() => listBoxAnimations.Items[FindAnimationIndex(animation) + 1] = FormatAnimationName(animation));
}
}
private int FindAnimationIndex(Animation animation)
{
int i = 0;
foreach (Animation anim in _scene.Raw.Animations)
{
if (anim == animation)
{
return i;
}
++i;
}
return -1;
}
private void OnAnimationContextMenu(object sender, MouseEventArgs e)
{
if (e.Button != MouseButtons.Right) return;
var item = listBoxAnimations.IndexFromPoint(e.Location);
if (item > 0) // Exclude 0 (Bind Pose)
{
listBoxAnimations.SelectedIndex = item;
contextMenuStripAnims.Show(listBoxAnimations, e.Location);
}
}
}
}
/* vi: set shiftwidth=4 tabstop=4: */
| |
// Copyright (c) Brock Allen & Dominick Baier. All rights reserved.
// Licensed under the Apache License, Version 2.0. See LICENSE in the project root for license information.
using IdentityServer4.Events;
using IdentityServer4.Models;
using IdentityServer4.Services;
using IdentityServer4.Stores;
using IdentityServer4.Extensions;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using System.Linq;
using System.Threading.Tasks;
using DotNetScaffolder.Domain.Services.WebApi.IdentityServer.Controllers;
using DotNetScaffolder.Domain.Services.WebApi.IdentityServer.Controllers.Account;
using DotNetScaffolder.Domain.Services.WebApi.IdentityServer.Controllers.Consent;
namespace IdentityServer4.Quickstart.UI
{
/// <summary>
/// This controller processes the consent UI
/// </summary>
[SecurityHeaders]
[Authorize]
public class ConsentController : Controller
{
private readonly IIdentityServerInteractionService _interaction;
private readonly IClientStore _clientStore;
private readonly IResourceStore _resourceStore;
private readonly IEventService _events;
private readonly ILogger<ConsentController> _logger;
public ConsentController(
IIdentityServerInteractionService interaction,
IClientStore clientStore,
IResourceStore resourceStore,
IEventService events,
ILogger<ConsentController> logger)
{
_interaction = interaction;
_clientStore = clientStore;
_resourceStore = resourceStore;
_events = events;
_logger = logger;
}
/// <summary>
/// Shows the consent screen
/// </summary>
/// <param name="returnUrl"></param>
/// <returns></returns>
[HttpGet]
public async Task<IActionResult> Index(string returnUrl)
{
var vm = await BuildViewModelAsync(returnUrl);
if (vm != null)
{
return View("Index", vm);
}
return View("Error");
}
/// <summary>
/// Handles the consent screen postback
/// </summary>
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Index(ConsentInputModel model)
{
var result = await ProcessConsent(model);
if (result.IsRedirect)
{
if (await _clientStore.IsPkceClientAsync(result.ClientId))
{
// if the client is PKCE then we assume it's native, so this change in how to
// return the response is for better UX for the end user.
return View("Redirect", new RedirectViewModel { RedirectUrl = result.RedirectUri });
}
return Redirect(result.RedirectUri);
}
if (result.HasValidationError)
{
ModelState.AddModelError(string.Empty, result.ValidationError);
}
if (result.ShowView)
{
return View("Index", result.ViewModel);
}
return View("Error");
}
/*****************************************/
/* helper APIs for the ConsentController */
/*****************************************/
private async Task<ProcessConsentResult> ProcessConsent(ConsentInputModel model)
{
var result = new ProcessConsentResult();
// validate return url is still valid
var request = await _interaction.GetAuthorizationContextAsync(model.ReturnUrl);
if (request == null) return result;
ConsentResponse grantedConsent = null;
// user clicked 'no' - send back the standard 'access_denied' response
if (model?.Button == "no")
{
grantedConsent = ConsentResponse.Denied;
// emit event
await _events.RaiseAsync(new ConsentDeniedEvent(User.GetSubjectId(), request.ClientId, request.ScopesRequested));
}
// user clicked 'yes' - validate the data
else if (model?.Button == "yes")
{
// if the user consented to some scope, build the response model
if (model.ScopesConsented != null && model.ScopesConsented.Any())
{
var scopes = model.ScopesConsented;
if (ConsentOptions.EnableOfflineAccess == false)
{
scopes = scopes.Where(x => x != IdentityServer4.IdentityServerConstants.StandardScopes.OfflineAccess);
}
grantedConsent = new ConsentResponse
{
RememberConsent = model.RememberConsent,
ScopesConsented = scopes.ToArray()
};
// emit event
await _events.RaiseAsync(new ConsentGrantedEvent(User.GetSubjectId(), request.ClientId, request.ScopesRequested, grantedConsent.ScopesConsented, grantedConsent.RememberConsent));
}
else
{
result.ValidationError = ConsentOptions.MustChooseOneErrorMessage;
}
}
else
{
result.ValidationError = ConsentOptions.InvalidSelectionErrorMessage;
}
if (grantedConsent != null)
{
// communicate outcome of consent back to identityserver
await _interaction.GrantConsentAsync(request, grantedConsent);
// indicate that's it ok to redirect back to authorization endpoint
result.RedirectUri = model.ReturnUrl;
result.ClientId = request.ClientId;
}
else
{
// we need to redisplay the consent UI
result.ViewModel = await BuildViewModelAsync(model.ReturnUrl, model);
}
return result;
}
private async Task<ConsentViewModel> BuildViewModelAsync(string returnUrl, ConsentInputModel model = null)
{
var request = await _interaction.GetAuthorizationContextAsync(returnUrl);
if (request != null)
{
var client = await _clientStore.FindEnabledClientByIdAsync(request.ClientId);
if (client != null)
{
var resources = await _resourceStore.FindEnabledResourcesByScopeAsync(request.ScopesRequested);
if (resources != null && (resources.IdentityResources.Any() || resources.ApiResources.Any()))
{
return CreateConsentViewModel(model, returnUrl, request, client, resources);
}
else
{
_logger.LogError("No scopes matching: {0}", request.ScopesRequested.Aggregate((x, y) => x + ", " + y));
}
}
else
{
_logger.LogError("Invalid client id: {0}", request.ClientId);
}
}
else
{
_logger.LogError("No consent request matching request: {0}", returnUrl);
}
return null;
}
private ConsentViewModel CreateConsentViewModel(
ConsentInputModel model, string returnUrl,
AuthorizationRequest request,
Client client, Resources resources)
{
var vm = new ConsentViewModel
{
RememberConsent = model?.RememberConsent ?? true,
ScopesConsented = model?.ScopesConsented ?? Enumerable.Empty<string>(),
ReturnUrl = returnUrl,
ClientName = client.ClientName ?? client.ClientId,
ClientUrl = client.ClientUri,
ClientLogoUrl = client.LogoUri,
AllowRememberConsent = client.AllowRememberConsent
};
vm.IdentityScopes = resources.IdentityResources.Select(x => CreateScopeViewModel(x, vm.ScopesConsented.Contains(x.Name) || model == null)).ToArray();
vm.ResourceScopes = resources.ApiResources.SelectMany(x => x.Scopes).Select(x => CreateScopeViewModel(x, vm.ScopesConsented.Contains(x.Name) || model == null)).ToArray();
if (ConsentOptions.EnableOfflineAccess && resources.OfflineAccess)
{
vm.ResourceScopes = vm.ResourceScopes.Union(new ScopeViewModel[] {
GetOfflineAccessScope(vm.ScopesConsented.Contains(IdentityServer4.IdentityServerConstants.StandardScopes.OfflineAccess) || model == null)
});
}
return vm;
}
private ScopeViewModel CreateScopeViewModel(IdentityResource identity, bool check)
{
return new ScopeViewModel
{
Name = identity.Name,
DisplayName = identity.DisplayName,
Description = identity.Description,
Emphasize = identity.Emphasize,
Required = identity.Required,
Checked = check || identity.Required
};
}
public ScopeViewModel CreateScopeViewModel(Scope scope, bool check)
{
return new ScopeViewModel
{
Name = scope.Name,
DisplayName = scope.DisplayName,
Description = scope.Description,
Emphasize = scope.Emphasize,
Required = scope.Required,
Checked = check || scope.Required
};
}
private ScopeViewModel GetOfflineAccessScope(bool check)
{
return new ScopeViewModel
{
Name = IdentityServer4.IdentityServerConstants.StandardScopes.OfflineAccess,
DisplayName = ConsentOptions.OfflineAccessDisplayName,
Description = ConsentOptions.OfflineAccessDescription,
Emphasize = true,
Checked = check
};
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.IO;
using System.Xml;
using System.Net.Sockets;
using System.Net.NetworkInformation;
using System.Threading.Tasks;
namespace Orleans.Runtime.Configuration
{
/// <summary>
/// Data object holding Silo configuration parameters.
/// </summary>
[Serializable]
public class ClusterConfiguration
{
/// <summary>
/// The global configuration parameters that apply uniformly to all silos.
/// </summary>
public GlobalConfiguration Globals { get; private set; }
/// <summary>
/// The default configuration parameters that apply to each and every silo.
/// These can be over-written on a per silo basis.
/// </summary>
public NodeConfiguration Defaults { get; private set; }
/// <summary>
/// The configuration file.
/// </summary>
public string SourceFile { get; private set; }
private IPEndPoint primaryNode;
/// <summary>
/// The Primary Node IP and port (in dev setting).
/// </summary>
public IPEndPoint PrimaryNode { get { return primaryNode; } set { SetPrimaryNode(value); } }
/// <summary>
/// Per silo configuration parameters overrides.
/// </summary>
public IDictionary<string, NodeConfiguration> Overrides { get; private set; }
private Dictionary<string, string> overrideXml;
private readonly Dictionary<string, List<Action>> listeners = new Dictionary<string, List<Action>>();
internal bool IsRunningAsUnitTest { get; set; }
/// <summary>
/// ClusterConfiguration constructor.
/// </summary>
public ClusterConfiguration()
{
Init();
}
/// <summary>
/// ClusterConfiguration constructor.
/// </summary>
public ClusterConfiguration(TextReader input)
{
Load(input);
}
private void Init()
{
Globals = new GlobalConfiguration();
Defaults = new NodeConfiguration();
Overrides = new Dictionary<string, NodeConfiguration>();
overrideXml = new Dictionary<string, string>();
SourceFile = "";
IsRunningAsUnitTest = false;
}
/// <summary>
/// Loads configuration from a given input text reader.
/// </summary>
/// <param name="input">The TextReader to use.</param>
public void Load(TextReader input)
{
Init();
LoadFromXml(ParseXml(input));
}
internal void LoadFromXml(XmlElement root)
{
foreach (XmlNode c in root.ChildNodes)
{
var child = c as XmlElement;
if (child == null) continue; // Skip comment lines
switch (child.LocalName)
{
case "Globals":
Globals.Load(child);
// set subnets so this is independent of order
Defaults.Subnet = Globals.Subnet;
foreach (var o in Overrides.Values)
{
o.Subnet = Globals.Subnet;
}
if (Globals.SeedNodes.Count > 0)
{
primaryNode = Globals.SeedNodes[0];
}
break;
case "Defaults":
Defaults.Load(child);
Defaults.Subnet = Globals.Subnet;
break;
case "Override":
overrideXml[child.GetAttribute("Node")] = WriteXml(child);
break;
}
}
CalculateOverrides();
}
private static string WriteXml(XmlElement element)
{
using(var sw = new StringWriter())
{
using(var xw = XmlWriter.Create(sw))
{
element.WriteTo(xw);
xw.Flush();
return sw.ToString();
}
}
}
private void CalculateOverrides()
{
if (Globals.LivenessEnabled &&
Globals.LivenessType == GlobalConfiguration.LivenessProviderType.NotSpecified)
{
if (Globals.UseSqlSystemStore)
{
Globals.LivenessType = GlobalConfiguration.LivenessProviderType.SqlServer;
}
else if (Globals.UseAzureSystemStore)
{
Globals.LivenessType = GlobalConfiguration.LivenessProviderType.AzureTable;
}
else if (Globals.UseZooKeeperSystemStore)
{
Globals.LivenessType = GlobalConfiguration.LivenessProviderType.ZooKeeper;
}
else
{
Globals.LivenessType = GlobalConfiguration.LivenessProviderType.MembershipTableGrain;
}
}
if (Globals.UseMockReminderTable)
{
Globals.SetReminderServiceType(GlobalConfiguration.ReminderServiceProviderType.MockTable);
}
else if (Globals.ReminderServiceType == GlobalConfiguration.ReminderServiceProviderType.NotSpecified)
{
if (Globals.UseSqlSystemStore)
{
Globals.SetReminderServiceType(GlobalConfiguration.ReminderServiceProviderType.SqlServer);
}
else if (Globals.UseAzureSystemStore)
{
Globals.SetReminderServiceType(GlobalConfiguration.ReminderServiceProviderType.AzureTable);
}
else if (Globals.UseZooKeeperSystemStore)
{
Globals.SetReminderServiceType(GlobalConfiguration.ReminderServiceProviderType.Disabled);
}
else
{
Globals.SetReminderServiceType(GlobalConfiguration.ReminderServiceProviderType.ReminderTableGrain);
}
}
foreach (var p in overrideXml)
{
var n = new NodeConfiguration(Defaults);
n.Load(ParseXml(new StringReader(p.Value)));
InitNodeSettingsFromGlobals(n);
Overrides[n.SiloName] = n;
}
}
private void InitNodeSettingsFromGlobals(NodeConfiguration n)
{
if (n.Endpoint.Equals(this.PrimaryNode)) n.IsPrimaryNode = true;
if (Globals.SeedNodes.Contains(n.Endpoint)) n.IsSeedNode = true;
}
public void LoadFromFile(string fileName)
{
using (TextReader input = File.OpenText(fileName))
{
Load(input);
SourceFile = fileName;
}
}
/// <summary>
/// Obtains the configuration for a given silo.
/// </summary>
/// <param name="siloName">Silo name.</param>
/// <param name="siloNode">NodeConfiguration associated with the specified silo.</param>
/// <returns>true if node was found</returns>
public bool TryGetNodeConfigurationForSilo(string siloName, out NodeConfiguration siloNode)
{
return Overrides.TryGetValue(siloName, out siloNode);
}
/// <summary>
/// Creates a configuration node for a given silo.
/// </summary>
/// <param name="siloName">Silo name.</param>
/// <returns>NodeConfiguration associated with the specified silo.</returns>
public NodeConfiguration CreateNodeConfigurationForSilo(string siloName)
{
var siloNode = new NodeConfiguration(Defaults) { SiloName = siloName };
InitNodeSettingsFromGlobals(siloNode);
Overrides[siloName] = siloNode;
return siloNode;
}
/// <summary>
/// Creates a node config for the specified silo if one does not exist. Returns existing node if one already exists
/// </summary>
/// <param name="siloName">Silo name.</param>
/// <returns>NodeConfiguration associated with the specified silo.</returns>
public NodeConfiguration GetOrCreateNodeConfigurationForSilo(string siloName)
{
NodeConfiguration siloNode;
return !TryGetNodeConfigurationForSilo(siloName, out siloNode) ? CreateNodeConfigurationForSilo(siloName) : siloNode;
}
private void SetPrimaryNode(IPEndPoint primary)
{
primaryNode = primary;
foreach (NodeConfiguration node in Overrides.Values)
{
if (node.Endpoint.Equals(primary))
{
node.IsPrimaryNode = true;
}
}
}
/// <summary>
/// Loads the configuration from the standard paths
/// </summary>
/// <returns></returns>
public void StandardLoad()
{
string fileName = ConfigUtilities.FindConfigFile(true); // Throws FileNotFoundException
LoadFromFile(fileName);
}
/// <summary>
/// Subset of XML configuration file that is updatable at runtime
/// </summary>
private static readonly XmlElement updatableXml = ParseXml(new StringReader(@"
<OrleansConfiguration>
<Globals>
<Messaging ResponseTimeout=""?""/>
<Caching CacheSize=""?""/>
<Liveness ProbeTimeout=""?"" TableRefreshTimeout=""?"" NumMissedProbesLimit=""?""/>
</Globals>
<Defaults>
<LoadShedding Enabled=""?"" LoadLimit=""?""/>
<Tracing DefaultTraceLevel=""?"" PropagateActivityId=""?"">
<TraceLevelOverride LogPrefix=""?"" TraceLevel=""?""/>
</Tracing>
</Defaults>
</OrleansConfiguration>"));
/// <summary>
/// Updates existing configuration.
/// </summary>
/// <param name="input">The input string in XML format to use to update the existing configuration.</param>
/// <returns></returns>
public void Update(string input)
{
var xml = ParseXml(new StringReader(input));
var disallowed = new List<string>();
CheckSubtree(updatableXml, xml, "", disallowed);
if (disallowed.Count > 0)
throw new ArgumentException("Cannot update configuration with" + disallowed.ToStrings());
var dict = ToChildDictionary(xml);
XmlElement globals;
if (dict.TryGetValue("Globals", out globals))
{
Globals.Load(globals);
ConfigChanged("Globals");
foreach (var key in ToChildDictionary(globals).Keys)
{
ConfigChanged("Globals/" + key);
}
}
XmlElement defaults;
if (dict.TryGetValue("Defaults", out defaults))
{
Defaults.Load(defaults);
CalculateOverrides();
ConfigChanged("Defaults");
foreach (var key in ToChildDictionary(defaults).Keys)
{
ConfigChanged("Defaults/" + key);
}
}
}
private static void CheckSubtree(XmlElement allowed, XmlElement test, string prefix, List<string> disallowed)
{
prefix = prefix + "/" + test.LocalName;
if (allowed.LocalName != test.LocalName)
{
disallowed.Add(prefix);
return;
}
foreach (var attribute in AttributeNames(test))
{
if (! allowed.HasAttribute(attribute))
{
disallowed.Add(prefix + "/@" + attribute);
}
}
var allowedChildren = ToChildDictionary(allowed);
foreach (var t in test.ChildNodes)
{
var testChild = t as XmlElement;
if (testChild == null)
continue;
XmlElement allowedChild;
if (! allowedChildren.TryGetValue(testChild.LocalName, out allowedChild))
{
disallowed.Add(prefix + "/" + testChild.LocalName);
}
else
{
CheckSubtree(allowedChild, testChild, prefix, disallowed);
}
}
}
private static Dictionary<string, XmlElement> ToChildDictionary(XmlElement xml)
{
var result = new Dictionary<string, XmlElement>();
foreach (var c in xml.ChildNodes)
{
var child = c as XmlElement;
if (child == null)
continue;
result[child.LocalName] = child;
}
return result;
}
private static IEnumerable<string> AttributeNames(XmlElement element)
{
foreach (var a in element.Attributes)
{
var attr = a as XmlAttribute;
if (attr != null)
yield return attr.LocalName;
}
}
internal void OnConfigChange(string path, Action action, bool invokeNow = true)
{
List<Action> list;
if (listeners.TryGetValue(path, out list))
list.Add(action);
else
listeners.Add(path, new List<Action> { action });
if (invokeNow)
action();
}
internal void ConfigChanged(string path)
{
List<Action> list;
if (!listeners.TryGetValue(path, out list)) return;
foreach (var action in list)
action();
}
/// <summary>
/// Prints the current config for a given silo.
/// </summary>
/// <param name="siloName">The name of the silo to print its configuration.</param>
/// <returns></returns>
public string ToString(string siloName)
{
var sb = new StringBuilder();
sb.Append("Config File Name: ").AppendLine(string.IsNullOrEmpty(SourceFile) ? "" : Path.GetFullPath(SourceFile));
sb.Append("Host: ").AppendLine(Dns.GetHostName());
sb.Append("Start time: ").AppendLine(LogFormatter.PrintDate(DateTime.UtcNow));
sb.Append("Primary node: ").AppendLine(PrimaryNode == null ? "null" : PrimaryNode.ToString());
sb.AppendLine("Platform version info:").Append(ConfigUtilities.RuntimeVersionInfo());
sb.AppendLine("Global configuration:").Append(Globals.ToString());
NodeConfiguration nc;
if (TryGetNodeConfigurationForSilo(siloName, out nc))
{
sb.AppendLine("Silo configuration:").Append(nc);
}
sb.AppendLine();
return sb.ToString();
}
internal static async Task<IPAddress> ResolveIPAddress(string addrOrHost, byte[] subnet, AddressFamily family)
{
var loopback = (family == AddressFamily.InterNetwork) ? IPAddress.Loopback : IPAddress.IPv6Loopback;
if (addrOrHost.Equals("loopback", StringComparison.OrdinalIgnoreCase) ||
addrOrHost.Equals("localhost", StringComparison.OrdinalIgnoreCase) ||
addrOrHost.Equals("127.0.0.1", StringComparison.OrdinalIgnoreCase))
{
return loopback;
}
else if (addrOrHost == "0.0.0.0")
{
return IPAddress.Any;
}
else
{
// IF the address is an empty string, default to the local machine, but not the loopback address
if (String.IsNullOrEmpty(addrOrHost))
{
addrOrHost = Dns.GetHostName();
// If for some reason we get "localhost" back. This seems to have happened to somebody.
if (addrOrHost.Equals("localhost", StringComparison.OrdinalIgnoreCase))
return loopback;
}
var candidates = new List<IPAddress>();
IPAddress[] nodeIps = await Dns.GetHostAddressesAsync(addrOrHost);
foreach (var nodeIp in nodeIps)
{
if (nodeIp.AddressFamily != family || nodeIp.Equals(loopback)) continue;
// If the subnet does not match - we can't resolve this address.
// If subnet is not specified - pick smallest address deterministically.
if (subnet == null)
{
candidates.Add(nodeIp);
}
else
{
IPAddress ip = nodeIp;
if (subnet.Select((b, i) => ip.GetAddressBytes()[i] == b).All(x => x))
{
candidates.Add(nodeIp);
}
}
}
if (candidates.Count > 0)
{
return PickIPAddress(candidates);
}
var subnetStr = Utils.EnumerableToString(subnet, null, ".", false);
throw new ArgumentException("Hostname '" + addrOrHost + "' with subnet " + subnetStr + " and family " + family + " is not a valid IP address or DNS name");
}
}
private static IPAddress PickIPAddress(IReadOnlyList<IPAddress> candidates)
{
IPAddress chosen = null;
foreach (IPAddress addr in candidates)
{
if (chosen == null)
{
chosen = addr;
}
else
{
if(CompareIPAddresses(addr, chosen)) // pick smallest address deterministically
chosen = addr;
}
}
return chosen;
}
// returns true if lhs is "less" (in some repeatable sense) than rhs
private static bool CompareIPAddresses(IPAddress lhs, IPAddress rhs)
{
byte[] lbytes = lhs.GetAddressBytes();
byte[] rbytes = rhs.GetAddressBytes();
if (lbytes.Length != rbytes.Length) return lbytes.Length < rbytes.Length;
// compare starting from most significant octet.
// 10.68.20.21 < 10.98.05.04
for (int i = 0; i < lbytes.Length; i++)
{
if (lbytes[i] != rbytes[i])
{
return lbytes[i] < rbytes[i];
}
}
// They're equal
return false;
}
/// <summary>
/// Gets the address of the local server.
/// If there are multiple addresses in the correct family in the server's DNS record, the first will be returned.
/// </summary>
/// <returns>The server's IPv4 address.</returns>
internal static IPAddress GetLocalIPAddress(AddressFamily family = AddressFamily.InterNetwork, string interfaceName = null)
{
var loopback = (family == AddressFamily.InterNetwork) ? IPAddress.Loopback : IPAddress.IPv6Loopback;
// get list of all network interfaces
NetworkInterface[] netInterfaces = NetworkInterface.GetAllNetworkInterfaces();
var candidates = new List<IPAddress>();
// loop through interfaces
for (int i=0; i < netInterfaces.Length; i++)
{
NetworkInterface netInterface = netInterfaces[i];
if (netInterface.OperationalStatus != OperationalStatus.Up)
{
// Skip network interfaces that are not operational
continue;
}
if (!string.IsNullOrWhiteSpace(interfaceName) &&
!netInterface.Name.StartsWith(interfaceName, StringComparison.Ordinal)) continue;
bool isLoopbackInterface = (netInterface.NetworkInterfaceType == NetworkInterfaceType.Loopback);
// get list of all unicast IPs from current interface
UnicastIPAddressInformationCollection ipAddresses = netInterface.GetIPProperties().UnicastAddresses;
// loop through IP address collection
foreach (UnicastIPAddressInformation ip in ipAddresses)
{
if (ip.Address.AddressFamily == family) // Picking the first address of the requested family for now. Will need to revisit later
{
//don't pick loopback address, unless we were asked for a loopback interface
if(!(isLoopbackInterface && ip.Address.Equals(loopback)))
{
candidates.Add(ip.Address); // collect all candidates.
}
}
}
}
if (candidates.Count > 0) return PickIPAddress(candidates);
throw new OrleansException("Failed to get a local IP address.");
}
private static XmlElement ParseXml(TextReader input)
{
var doc = new XmlDocument();
var xmlReader = XmlReader.Create(input);
doc.Load(xmlReader);
return doc.DocumentElement;
}
/// <summary>
/// Returns a prepopulated ClusterConfiguration object for a primary local silo (for testing)
/// </summary>
/// <param name="siloPort">TCP port for silo to silo communication</param>
/// <param name="gatewayPort">Client gateway TCP port</param>
/// <returns>ClusterConfiguration object that can be passed to Silo or SiloHost classes for initialization</returns>
public static ClusterConfiguration LocalhostPrimarySilo(int siloPort = 22222, int gatewayPort = 40000)
{
var config = new ClusterConfiguration();
var siloAddress = new IPEndPoint(IPAddress.Loopback, siloPort);
config.Globals.LivenessType = GlobalConfiguration.LivenessProviderType.MembershipTableGrain;
config.Globals.SeedNodes.Add(siloAddress);
config.Globals.ReminderServiceType = GlobalConfiguration.ReminderServiceProviderType.ReminderTableGrain;
config.Defaults.HostNameOrIPAddress = "localhost";
config.Defaults.Port = siloPort;
config.Defaults.ProxyGatewayEndpoint = new IPEndPoint(IPAddress.Loopback, gatewayPort);
config.PrimaryNode = siloAddress;
return config;
}
}
}
| |
namespace EIDSS.Reports.Document.Veterinary.AvianInvestigation
{
partial class SampleReport
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(SampleReport));
this.Detail = new DevExpress.XtraReports.UI.DetailBand();
this.xrTable2 = new DevExpress.XtraReports.UI.XRTable();
this.xrTableRow2 = new DevExpress.XtraReports.UI.XRTableRow();
this.xrTableCell2 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell9 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell12 = new DevExpress.XtraReports.UI.XRTableCell();
this.PageHeader = new DevExpress.XtraReports.UI.PageHeaderBand();
this.xrTable1 = new DevExpress.XtraReports.UI.XRTable();
this.xrTableRow1 = new DevExpress.XtraReports.UI.XRTableRow();
this.xrTableCell4 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell1 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell7 = new DevExpress.XtraReports.UI.XRTableCell();
this.PageFooter = new DevExpress.XtraReports.UI.PageFooterBand();
this.ReportHeader = new DevExpress.XtraReports.UI.ReportHeaderBand();
this.xrLabel1 = new DevExpress.XtraReports.UI.XRLabel();
this.sampleDataSet1 = new EIDSS.Reports.Document.Veterinary.AvianInvestigation.SampleDataSet();
this.sp_rep_VET_SamplesCollectionAvianTableAdapter = new EIDSS.Reports.Document.Veterinary.AvianInvestigation.SampleDataSetTableAdapters.sp_rep_VET_SamplesCollectionAvianTableAdapter();
this.topMarginBand1 = new DevExpress.XtraReports.UI.TopMarginBand();
this.bottomMarginBand1 = new DevExpress.XtraReports.UI.BottomMarginBand();
((System.ComponentModel.ISupportInitialize)(this.xrTable2)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.xrTable1)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.sampleDataSet1)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this)).BeginInit();
//
// Detail
//
this.Detail.Borders = ((DevExpress.XtraPrinting.BorderSide)(((DevExpress.XtraPrinting.BorderSide.Left | DevExpress.XtraPrinting.BorderSide.Right)
| DevExpress.XtraPrinting.BorderSide.Bottom)));
this.Detail.Controls.AddRange(new DevExpress.XtraReports.UI.XRControl[] {
this.xrTable2});
resources.ApplyResources(this.Detail, "Detail");
this.Detail.Name = "Detail";
this.Detail.Padding = new DevExpress.XtraPrinting.PaddingInfo(2, 2, 0, 0, 100F);
this.Detail.StylePriority.UseBorders = false;
this.Detail.StylePriority.UsePadding = false;
this.Detail.StylePriority.UseTextAlignment = false;
//
// xrTable2
//
resources.ApplyResources(this.xrTable2, "xrTable2");
this.xrTable2.Name = "xrTable2";
this.xrTable2.Rows.AddRange(new DevExpress.XtraReports.UI.XRTableRow[] {
this.xrTableRow2});
//
// xrTableRow2
//
this.xrTableRow2.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] {
this.xrTableCell2,
this.xrTableCell9,
this.xrTableCell12});
this.xrTableRow2.Name = "xrTableRow2";
this.xrTableRow2.Weight = 1;
//
// xrTableCell2
//
this.xrTableCell2.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepVetSamplesCollectionAvian.SpeciesName")});
this.xrTableCell2.Name = "xrTableCell2";
this.xrTableCell2.Weight = 0.99935483870967745;
//
// xrTableCell9
//
this.xrTableCell9.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepVetSamplesCollectionAvian.strFieldBarcode")});
this.xrTableCell9.Name = "xrTableCell9";
this.xrTableCell9.Weight = 0.99935483870967723;
//
// xrTableCell12
//
this.xrTableCell12.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepVetSamplesCollectionAvian.SpecimenType")});
this.xrTableCell12.Name = "xrTableCell12";
this.xrTableCell12.Weight = 1.0012903225806451;
//
// PageHeader
//
this.PageHeader.Controls.AddRange(new DevExpress.XtraReports.UI.XRControl[] {
this.xrTable1});
resources.ApplyResources(this.PageHeader, "PageHeader");
this.PageHeader.Name = "PageHeader";
this.PageHeader.Padding = new DevExpress.XtraPrinting.PaddingInfo(2, 2, 0, 0, 100F);
this.PageHeader.StylePriority.UseFont = false;
this.PageHeader.StylePriority.UsePadding = false;
this.PageHeader.StylePriority.UseTextAlignment = false;
//
// xrTable1
//
resources.ApplyResources(this.xrTable1, "xrTable1");
this.xrTable1.Name = "xrTable1";
this.xrTable1.Rows.AddRange(new DevExpress.XtraReports.UI.XRTableRow[] {
this.xrTableRow1});
//
// xrTableRow1
//
this.xrTableRow1.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] {
this.xrTableCell4,
this.xrTableCell1,
this.xrTableCell7});
this.xrTableRow1.Name = "xrTableRow1";
this.xrTableRow1.Weight = 1;
//
// xrTableCell4
//
this.xrTableCell4.Name = "xrTableCell4";
resources.ApplyResources(this.xrTableCell4, "xrTableCell4");
this.xrTableCell4.Weight = 0.99935483870967756;
//
// xrTableCell1
//
this.xrTableCell1.Name = "xrTableCell1";
resources.ApplyResources(this.xrTableCell1, "xrTableCell1");
this.xrTableCell1.Weight = 0.99935483870967745;
//
// xrTableCell7
//
this.xrTableCell7.Name = "xrTableCell7";
resources.ApplyResources(this.xrTableCell7, "xrTableCell7");
this.xrTableCell7.Weight = 1.0012903225806451;
//
// PageFooter
//
resources.ApplyResources(this.PageFooter, "PageFooter");
this.PageFooter.Name = "PageFooter";
this.PageFooter.Padding = new DevExpress.XtraPrinting.PaddingInfo(0, 0, 0, 0, 100F);
//
// ReportHeader
//
this.ReportHeader.Controls.AddRange(new DevExpress.XtraReports.UI.XRControl[] {
this.xrLabel1});
resources.ApplyResources(this.ReportHeader, "ReportHeader");
this.ReportHeader.Name = "ReportHeader";
//
// xrLabel1
//
this.xrLabel1.Borders = DevExpress.XtraPrinting.BorderSide.Bottom;
resources.ApplyResources(this.xrLabel1, "xrLabel1");
this.xrLabel1.Name = "xrLabel1";
this.xrLabel1.Padding = new DevExpress.XtraPrinting.PaddingInfo(2, 2, 0, 0, 100F);
this.xrLabel1.StylePriority.UseBorders = false;
this.xrLabel1.StylePriority.UseFont = false;
this.xrLabel1.StylePriority.UseTextAlignment = false;
//
// sampleDataSet1
//
this.sampleDataSet1.DataSetName = "SampleDataSet";
this.sampleDataSet1.SchemaSerializationMode = System.Data.SchemaSerializationMode.IncludeSchema;
//
// sp_rep_VET_SamplesCollectionAvianTableAdapter
//
this.sp_rep_VET_SamplesCollectionAvianTableAdapter.ClearBeforeFill = true;
//
// topMarginBand1
//
resources.ApplyResources(this.topMarginBand1, "topMarginBand1");
this.topMarginBand1.Name = "topMarginBand1";
//
// bottomMarginBand1
//
resources.ApplyResources(this.bottomMarginBand1, "bottomMarginBand1");
this.bottomMarginBand1.Name = "bottomMarginBand1";
//
// SampleReport
//
this.Bands.AddRange(new DevExpress.XtraReports.UI.Band[] {
this.Detail,
this.PageHeader,
this.PageFooter,
this.ReportHeader,
this.topMarginBand1,
this.bottomMarginBand1});
this.Borders = ((DevExpress.XtraPrinting.BorderSide)((((DevExpress.XtraPrinting.BorderSide.Left | DevExpress.XtraPrinting.BorderSide.Top)
| DevExpress.XtraPrinting.BorderSide.Right)
| DevExpress.XtraPrinting.BorderSide.Bottom)));
this.DataAdapter = this.sp_rep_VET_SamplesCollectionAvianTableAdapter;
this.DataMember = "spRepVetSamplesCollectionAvian";
this.DataSource = this.sampleDataSet1;
this.ExportOptions.Xls.SheetName = resources.GetString("SampleReport.ExportOptions.Xls.SheetName");
this.ExportOptions.Xlsx.SheetName = resources.GetString("SampleReport.ExportOptions.Xlsx.SheetName");
resources.ApplyResources(this, "$this");
this.Padding = new DevExpress.XtraPrinting.PaddingInfo(2, 2, 0, 0, 100F);
this.Version = "10.1";
((System.ComponentModel.ISupportInitialize)(this.xrTable2)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.xrTable1)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.sampleDataSet1)).EndInit();
((System.ComponentModel.ISupportInitialize)(this)).EndInit();
}
#endregion
private DevExpress.XtraReports.UI.DetailBand Detail;
private DevExpress.XtraReports.UI.PageHeaderBand PageHeader;
private DevExpress.XtraReports.UI.PageFooterBand PageFooter;
private DevExpress.XtraReports.UI.ReportHeaderBand ReportHeader;
private DevExpress.XtraReports.UI.XRLabel xrLabel1;
private DevExpress.XtraReports.UI.XRTable xrTable1;
private DevExpress.XtraReports.UI.XRTableRow xrTableRow1;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell4;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell1;
private DevExpress.XtraReports.UI.XRTable xrTable2;
private DevExpress.XtraReports.UI.XRTableRow xrTableRow2;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell2;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell9;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell12;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell7;
private SampleDataSet sampleDataSet1;
private EIDSS.Reports.Document.Veterinary.AvianInvestigation.SampleDataSetTableAdapters.sp_rep_VET_SamplesCollectionAvianTableAdapter sp_rep_VET_SamplesCollectionAvianTableAdapter;
private DevExpress.XtraReports.UI.TopMarginBand topMarginBand1;
private DevExpress.XtraReports.UI.BottomMarginBand bottomMarginBand1;
}
}
| |
using System;
using System.Data;
using System.Data.SqlClient;
using Csla;
using Csla.Data;
using System.Configuration;
using System.IO;
using System.ComponentModel;
using System.Collections.Generic;
using Csla.Validation;
namespace Northwind.CSLA.Library
{
/// <summary>
/// Employee Generated by MyGeneration using the CSLA Object Mapping template
/// </summary>
[Serializable()]
[TypeConverter(typeof(EmployeeConverter))]
public partial class Employee : BusinessBase<Employee>, IDisposable, IVEHasBrokenRules
{
#region Refresh
private List<Employee> _RefreshEmployees = new List<Employee>();
private List<EmployeeEmployeeTerritory> _RefreshEmployeeEmployeeTerritories = new List<EmployeeEmployeeTerritory>();
private List<EmployeeOrder> _RefreshEmployeeOrders = new List<EmployeeOrder>();
private void AddToRefreshList(List<Employee> refreshEmployees, List<EmployeeEmployeeTerritory> refreshEmployeeEmployeeTerritories, List<EmployeeOrder> refreshEmployeeOrders)
{
if (IsDirty)
refreshEmployees.Add(this);
if (_ChildEmployees != null && _ChildEmployees.IsDirty)
{
foreach (Employee tmp in _ChildEmployees)
{
tmp.AddToRefreshList(refreshEmployees, refreshEmployeeEmployeeTerritories, refreshEmployeeOrders);
}
}
if (_EmployeeEmployeeTerritories != null && _EmployeeEmployeeTerritories.IsDirty)
{
foreach (EmployeeEmployeeTerritory tmp in _EmployeeEmployeeTerritories)
{
if(tmp.IsDirty)refreshEmployeeEmployeeTerritories.Add(tmp);
}
}
if (_EmployeeOrders != null && _EmployeeOrders.IsDirty)
{
foreach (EmployeeOrder tmp in _EmployeeOrders)
{
if(tmp.IsDirty)refreshEmployeeOrders.Add(tmp);
}
}
}
private void BuildRefreshList()
{
_RefreshEmployees = new List<Employee>();
_RefreshEmployeeEmployeeTerritories = new List<EmployeeEmployeeTerritory>();
_RefreshEmployeeOrders = new List<EmployeeOrder>();
AddToRefreshList(_RefreshEmployees, _RefreshEmployeeEmployeeTerritories, _RefreshEmployeeOrders);
}
private void ProcessRefreshList()
{
foreach (Employee tmp in _RefreshEmployees)
{
EmployeeInfo.Refresh(tmp);
}
foreach (EmployeeEmployeeTerritory tmp in _RefreshEmployeeEmployeeTerritories)
{
EmployeeTerritoryInfo.Refresh(this, tmp);
}
foreach (EmployeeOrder tmp in _RefreshEmployeeOrders)
{
OrderInfo.Refresh(tmp);
}
}
#endregion
#region Collection
protected static List<Employee> _AllList = new List<Employee>();
private static Dictionary<string, Employee> _AllByPrimaryKey = new Dictionary<string, Employee>();
private static void ConvertListToDictionary()
{
List<Employee> remove = new List<Employee>();
foreach (Employee tmp in _AllList)
{
_AllByPrimaryKey[tmp.EmployeeID.ToString()]=tmp; // Primary Key
remove.Add(tmp);
}
foreach (Employee tmp in remove)
_AllList.Remove(tmp);
}
public static Employee GetExistingByPrimaryKey(int employeeID)
{
ConvertListToDictionary();
string key = employeeID.ToString();
if (_AllByPrimaryKey.ContainsKey(key)) return _AllByPrimaryKey[key];
return null;
}
#endregion
#region Business Methods
private string _ErrorMessage = string.Empty;
public string ErrorMessage
{
get { return _ErrorMessage; }
}
private static int _nextEmployeeID = -1;
public static int NextEmployeeID
{
get { return _nextEmployeeID--; }
}
private int _EmployeeID;
[System.ComponentModel.DataObjectField(true, true)]
public int EmployeeID
{
[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
get
{
CanReadProperty(true);
return _EmployeeID;
}
}
private string _LastName = string.Empty;
public string LastName
{
[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
get
{
CanReadProperty(true);
return _LastName;
}
[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
set
{
CanWriteProperty(true);
if (value == null) value = string.Empty;
if (_LastName != value)
{
_LastName = value;
PropertyHasChanged();
}
}
}
private string _FirstName = string.Empty;
public string FirstName
{
[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
get
{
CanReadProperty(true);
return _FirstName;
}
[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
set
{
CanWriteProperty(true);
if (value == null) value = string.Empty;
if (_FirstName != value)
{
_FirstName = value;
PropertyHasChanged();
}
}
}
private string _Title = string.Empty;
public string Title
{
[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
get
{
CanReadProperty(true);
return _Title;
}
[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
set
{
CanWriteProperty(true);
if (value == null) value = string.Empty;
if (_Title != value)
{
_Title = value;
PropertyHasChanged();
}
}
}
private string _TitleOfCourtesy = string.Empty;
public string TitleOfCourtesy
{
[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
get
{
CanReadProperty(true);
return _TitleOfCourtesy;
}
[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
set
{
CanWriteProperty(true);
if (value == null) value = string.Empty;
if (_TitleOfCourtesy != value)
{
_TitleOfCourtesy = value;
PropertyHasChanged();
}
}
}
private string _BirthDate = string.Empty;
public string BirthDate
{
[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
get
{
CanReadProperty(true);
return _BirthDate;
}
[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
set
{
CanWriteProperty(true);
if (value == null) value = string.Empty;
_BirthDate = value;
try
{
SmartDate tmp = new SmartDate(value);
if (_BirthDate != tmp.ToString())
{
_BirthDate = tmp.ToString();
// TODO: Any Cross Property Validation
}
}
catch
{
}
PropertyHasChanged();
}
}
private string _HireDate = string.Empty;
public string HireDate
{
[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
get
{
CanReadProperty(true);
return _HireDate;
}
[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
set
{
CanWriteProperty(true);
if (value == null) value = string.Empty;
_HireDate = value;
try
{
SmartDate tmp = new SmartDate(value);
if (_HireDate != tmp.ToString())
{
_HireDate = tmp.ToString();
// TODO: Any Cross Property Validation
}
}
catch
{
}
PropertyHasChanged();
}
}
private string _Address = string.Empty;
public string Address
{
[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
get
{
CanReadProperty(true);
return _Address;
}
[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
set
{
CanWriteProperty(true);
if (value == null) value = string.Empty;
if (_Address != value)
{
_Address = value;
PropertyHasChanged();
}
}
}
private string _City = string.Empty;
public string City
{
[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
get
{
CanReadProperty(true);
return _City;
}
[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
set
{
CanWriteProperty(true);
if (value == null) value = string.Empty;
if (_City != value)
{
_City = value;
PropertyHasChanged();
}
}
}
private string _Region = string.Empty;
public string Region
{
[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
get
{
CanReadProperty(true);
return _Region;
}
[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
set
{
CanWriteProperty(true);
if (value == null) value = string.Empty;
if (_Region != value)
{
_Region = value;
PropertyHasChanged();
}
}
}
private string _PostalCode = string.Empty;
public string PostalCode
{
[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
get
{
CanReadProperty(true);
return _PostalCode;
}
[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
set
{
CanWriteProperty(true);
if (value == null) value = string.Empty;
if (_PostalCode != value)
{
_PostalCode = value;
PropertyHasChanged();
}
}
}
private string _Country = string.Empty;
public string Country
{
[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
get
{
CanReadProperty(true);
return _Country;
}
[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
set
{
CanWriteProperty(true);
if (value == null) value = string.Empty;
if (_Country != value)
{
_Country = value;
PropertyHasChanged();
}
}
}
private string _HomePhone = string.Empty;
public string HomePhone
{
[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
get
{
CanReadProperty(true);
return _HomePhone;
}
[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
set
{
CanWriteProperty(true);
if (value == null) value = string.Empty;
if (_HomePhone != value)
{
_HomePhone = value;
PropertyHasChanged();
}
}
}
private string _Extension = string.Empty;
public string Extension
{
[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
get
{
CanReadProperty(true);
return _Extension;
}
[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
set
{
CanWriteProperty(true);
if (value == null) value = string.Empty;
if (_Extension != value)
{
_Extension = value;
PropertyHasChanged();
}
}
}
private byte[] _Photo;
public byte[] Photo
{
[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
get
{
CanReadProperty(true);
return _Photo;
}
[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
set
{
CanWriteProperty(true);
if (_Photo != value)
{
_Photo = value;
PropertyHasChanged();
}
}
}
private string _Notes = string.Empty;
public string Notes
{
[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
get
{
CanReadProperty(true);
return _Notes;
}
[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
set
{
CanWriteProperty(true);
if (value == null) value = string.Empty;
if (_Notes != value)
{
_Notes = value;
PropertyHasChanged();
}
}
}
private int? _ReportsTo;
public int? ReportsTo
{
[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
get
{
CanReadProperty(true);
if (_MyParent != null) _ReportsTo = _MyParent.EmployeeID;
return _ReportsTo;
}
}
private Employee _MyParent;
public Employee MyParent
{
[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
get
{
CanReadProperty(true);
if (_MyParent == null && _ReportsTo != null) _MyParent = Employee.Get((int)_ReportsTo);
return _MyParent;
}
[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
set
{
CanWriteProperty(true);
if (_MyParent != value)
{
_MyParent = value;
_ReportsTo = (value == null ? null : (int?) value.EmployeeID);
PropertyHasChanged();
}
}
}
private string _PhotoPath = string.Empty;
public string PhotoPath
{
[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
get
{
CanReadProperty(true);
return _PhotoPath;
}
[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
set
{
CanWriteProperty(true);
if (value == null) value = string.Empty;
if (_PhotoPath != value)
{
_PhotoPath = value;
PropertyHasChanged();
}
}
}
private int _ChildEmployeeCount = 0;
/// <summary>
/// Count of ChildEmployees for this Employee
/// </summary>
public int ChildEmployeeCount
{
[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
get
{
CanReadProperty(true);
return _ChildEmployeeCount;
}
}
private ChildEmployees _ChildEmployees = null;
/// <summary>
/// Related Field
/// </summary>
[TypeConverter(typeof(ChildEmployeesConverter))]
public ChildEmployees ChildEmployees
{
[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
get
{
CanReadProperty(true);
if(_ChildEmployeeCount > 0 && _ChildEmployees == null)
_ChildEmployees = ChildEmployees.GetByReportsTo(EmployeeID);
else if(_ChildEmployees == null)
_ChildEmployees = ChildEmployees.New();
return _ChildEmployees;
}
}
private int _EmployeeEmployeeTerritoryCount = 0;
/// <summary>
/// Count of EmployeeEmployeeTerritories for this Employee
/// </summary>
public int EmployeeEmployeeTerritoryCount
{
[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
get
{
CanReadProperty(true);
return _EmployeeEmployeeTerritoryCount;
}
}
private EmployeeEmployeeTerritories _EmployeeEmployeeTerritories = null;
/// <summary>
/// Related Field
/// </summary>
[TypeConverter(typeof(EmployeeEmployeeTerritoriesConverter))]
public EmployeeEmployeeTerritories EmployeeEmployeeTerritories
{
[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
get
{
CanReadProperty(true);
if(_EmployeeEmployeeTerritoryCount > 0 && _EmployeeEmployeeTerritories == null)
_EmployeeEmployeeTerritories = EmployeeEmployeeTerritories.GetByEmployeeID(EmployeeID);
else if(_EmployeeEmployeeTerritories == null)
_EmployeeEmployeeTerritories = EmployeeEmployeeTerritories.New();
return _EmployeeEmployeeTerritories;
}
}
private int _EmployeeOrderCount = 0;
/// <summary>
/// Count of EmployeeOrders for this Employee
/// </summary>
public int EmployeeOrderCount
{
[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
get
{
CanReadProperty(true);
return _EmployeeOrderCount;
}
}
private EmployeeOrders _EmployeeOrders = null;
/// <summary>
/// Related Field
/// </summary>
[TypeConverter(typeof(EmployeeOrdersConverter))]
public EmployeeOrders EmployeeOrders
{
[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
get
{
CanReadProperty(true);
if(_EmployeeOrderCount > 0 && _EmployeeOrders == null)
_EmployeeOrders = EmployeeOrders.GetByEmployeeID(EmployeeID);
else if(_EmployeeOrders == null)
_EmployeeOrders = EmployeeOrders.New();
return _EmployeeOrders;
}
}
public override bool IsDirty
{
get { return base.IsDirty || (_ChildEmployees == null? false : _ChildEmployees.IsDirty) || (_EmployeeEmployeeTerritories == null? false : _EmployeeEmployeeTerritories.IsDirty) || (_EmployeeOrders == null? false : _EmployeeOrders.IsDirty); }
}
public override bool IsValid
{
get { return (IsNew && !IsDirty ? true : base.IsValid) && (_ChildEmployees == null? true : _ChildEmployees.IsValid) && (_EmployeeEmployeeTerritories == null? true : _EmployeeEmployeeTerritories.IsValid) && (_EmployeeOrders == null? true : _EmployeeOrders.IsValid); }
}
// TODO: Replace base Employee.ToString function as necessary
/// <summary>
/// Overrides Base ToString
/// </summary>
/// <returns>A string representation of current Employee</returns>
//public override string ToString()
//{
// return base.ToString();
//}
// TODO: Check Employee.GetIdValue to assure that the ID returned is unique
/// <summary>
/// Overrides Base GetIdValue - Used internally by CSLA to determine equality
/// </summary>
/// <returns>A Unique ID for the current Employee</returns>
protected override object GetIdValue()
{
return _EmployeeID;
}
#endregion
#region ValidationRules
[NonSerialized]
private bool _CheckingBrokenRules=false;
public IVEHasBrokenRules HasBrokenRules
{
get {
if(_CheckingBrokenRules)return null;
if ((IsDirty || !IsNew) && BrokenRulesCollection.Count > 0) return this;
try
{
_CheckingBrokenRules=true;
IVEHasBrokenRules hasBrokenRules = null;
if (_EmployeeOrders != null && (hasBrokenRules = _EmployeeOrders.HasBrokenRules) != null) return hasBrokenRules;
if (_ChildEmployees != null && (hasBrokenRules = _ChildEmployees.HasBrokenRules) != null) return hasBrokenRules;
if (_EmployeeEmployeeTerritories != null && (hasBrokenRules = _EmployeeEmployeeTerritories.HasBrokenRules) != null) return hasBrokenRules;
return hasBrokenRules;
}
finally
{
_CheckingBrokenRules=false;
}
}
}
public BrokenRulesCollection BrokenRules
{
get
{
IVEHasBrokenRules hasBrokenRules = HasBrokenRules;
if (this.Equals(hasBrokenRules)) return BrokenRulesCollection;
return (hasBrokenRules != null ? hasBrokenRules.BrokenRules : null);
}
}
protected override void AddBusinessRules()
{
ValidationRules.AddRule(
Csla.Validation.CommonRules.StringRequired, "LastName");
ValidationRules.AddRule(
Csla.Validation.CommonRules.StringMaxLength,
new Csla.Validation.CommonRules.MaxLengthRuleArgs("LastName", 20));
ValidationRules.AddRule(
Csla.Validation.CommonRules.StringRequired, "FirstName");
ValidationRules.AddRule(
Csla.Validation.CommonRules.StringMaxLength,
new Csla.Validation.CommonRules.MaxLengthRuleArgs("FirstName", 10));
ValidationRules.AddRule(
Csla.Validation.CommonRules.StringMaxLength,
new Csla.Validation.CommonRules.MaxLengthRuleArgs("Title", 30));
ValidationRules.AddRule(
Csla.Validation.CommonRules.StringMaxLength,
new Csla.Validation.CommonRules.MaxLengthRuleArgs("TitleOfCourtesy", 25));
ValidationRules.AddRule<Employee>(BirthDateValid, "BirthDate");
ValidationRules.AddRule<Employee>(HireDateValid, "HireDate");
ValidationRules.AddRule(
Csla.Validation.CommonRules.StringMaxLength,
new Csla.Validation.CommonRules.MaxLengthRuleArgs("Address", 60));
ValidationRules.AddRule(
Csla.Validation.CommonRules.StringMaxLength,
new Csla.Validation.CommonRules.MaxLengthRuleArgs("City", 15));
ValidationRules.AddRule(
Csla.Validation.CommonRules.StringMaxLength,
new Csla.Validation.CommonRules.MaxLengthRuleArgs("Region", 15));
ValidationRules.AddRule(
Csla.Validation.CommonRules.StringMaxLength,
new Csla.Validation.CommonRules.MaxLengthRuleArgs("PostalCode", 10));
ValidationRules.AddRule(
Csla.Validation.CommonRules.StringMaxLength,
new Csla.Validation.CommonRules.MaxLengthRuleArgs("Country", 15));
ValidationRules.AddRule(
Csla.Validation.CommonRules.StringMaxLength,
new Csla.Validation.CommonRules.MaxLengthRuleArgs("HomePhone", 24));
ValidationRules.AddRule(
Csla.Validation.CommonRules.StringMaxLength,
new Csla.Validation.CommonRules.MaxLengthRuleArgs("Extension", 4));
ValidationRules.AddRule(
Csla.Validation.CommonRules.StringMaxLength,
new Csla.Validation.CommonRules.MaxLengthRuleArgs("Notes", 1073741823));
ValidationRules.AddRule(
Csla.Validation.CommonRules.StringMaxLength,
new Csla.Validation.CommonRules.MaxLengthRuleArgs("PhotoPath", 255));
//ValidationRules.AddDependantProperty("x", "y");
_EmployeeExtension.AddValidationRules(ValidationRules);
// TODO: Add other validation rules
}
protected override void AddInstanceBusinessRules()
{
_EmployeeExtension.AddInstanceValidationRules(ValidationRules);
// TODO: Add other validation rules
}
private static bool BirthDateValid(Employee target, Csla.Validation.RuleArgs e)
{
try
{
DateTime tmp = SmartDate.StringToDate(target._BirthDate);
}
catch
{
e.Description = "Invalid Date";
return false;
}
return true;
}
private static bool HireDateValid(Employee target, Csla.Validation.RuleArgs e)
{
try
{
DateTime tmp = SmartDate.StringToDate(target._HireDate);
}
catch
{
e.Description = "Invalid Date";
return false;
}
return true;
}
// Sample data comparison validation rule
//private bool StartDateGTEndDate(object target, Csla.Validation.RuleArgs e)
//{
// if (_started > _ended)
// {
// e.Description = "Start date can't be after end date";
// return false;
// }
// else
// return true;
//}
#endregion
#region Authorization Rules
protected override void AddAuthorizationRules()
{
//TODO: Who can read/write which fields
//AuthorizationRules.AllowRead(EmployeeID, "<Role(s)>");
//AuthorizationRules.AllowRead(LastName, "<Role(s)>");
//AuthorizationRules.AllowRead(FirstName, "<Role(s)>");
//AuthorizationRules.AllowRead(Title, "<Role(s)>");
//AuthorizationRules.AllowRead(TitleOfCourtesy, "<Role(s)>");
//AuthorizationRules.AllowRead(BirthDate, "<Role(s)>");
//AuthorizationRules.AllowRead(HireDate, "<Role(s)>");
//AuthorizationRules.AllowRead(Address, "<Role(s)>");
//AuthorizationRules.AllowRead(City, "<Role(s)>");
//AuthorizationRules.AllowRead(Region, "<Role(s)>");
//AuthorizationRules.AllowRead(PostalCode, "<Role(s)>");
//AuthorizationRules.AllowRead(Country, "<Role(s)>");
//AuthorizationRules.AllowRead(HomePhone, "<Role(s)>");
//AuthorizationRules.AllowRead(Extension, "<Role(s)>");
//AuthorizationRules.AllowRead(Photo, "<Role(s)>");
//AuthorizationRules.AllowRead(Notes, "<Role(s)>");
//AuthorizationRules.AllowRead(ReportsTo, "<Role(s)>");
//AuthorizationRules.AllowRead(PhotoPath, "<Role(s)>");
//AuthorizationRules.AllowWrite(LastName, "<Role(s)>");
//AuthorizationRules.AllowWrite(FirstName, "<Role(s)>");
//AuthorizationRules.AllowWrite(Title, "<Role(s)>");
//AuthorizationRules.AllowWrite(TitleOfCourtesy, "<Role(s)>");
//AuthorizationRules.AllowWrite(BirthDate, "<Role(s)>");
//AuthorizationRules.AllowWrite(HireDate, "<Role(s)>");
//AuthorizationRules.AllowWrite(Address, "<Role(s)>");
//AuthorizationRules.AllowWrite(City, "<Role(s)>");
//AuthorizationRules.AllowWrite(Region, "<Role(s)>");
//AuthorizationRules.AllowWrite(PostalCode, "<Role(s)>");
//AuthorizationRules.AllowWrite(Country, "<Role(s)>");
//AuthorizationRules.AllowWrite(HomePhone, "<Role(s)>");
//AuthorizationRules.AllowWrite(Extension, "<Role(s)>");
//AuthorizationRules.AllowWrite(Photo, "<Role(s)>");
//AuthorizationRules.AllowWrite(Notes, "<Role(s)>");
//AuthorizationRules.AllowWrite(ReportsTo, "<Role(s)>");
//AuthorizationRules.AllowWrite(PhotoPath, "<Role(s)>");
_EmployeeExtension.AddAuthorizationRules(AuthorizationRules);
}
protected override void AddInstanceAuthorizationRules()
{
//TODO: Who can read/write which fields
_EmployeeExtension.AddInstanceAuthorizationRules(AuthorizationRules);
}
public static bool CanAddObject()
{
// TODO: Can Add Authorization
//return Csla.ApplicationContext.User.IsInRole("ProjectManager");
return true;
}
public static bool CanGetObject()
{
// TODO: CanGet Authorization
return true;
}
public static bool CanDeleteObject()
{
// TODO: CanDelete Authorization
//bool result = false;
//if (Csla.ApplicationContext.User.IsInRole("ProjectManager"))result = true;
//if (Csla.ApplicationContext.User.IsInRole("Administrator"))result = true;
//return result;
return true;
}
public static bool CanEditObject()
{
// TODO: CanEdit Authorization
//return Csla.ApplicationContext.User.IsInRole("ProjectManager");
return true;
}
#endregion
#region Factory Methods
public int CurrentEditLevel
{ get { return EditLevel; } }
protected Employee()
{/* require use of factory methods */
_AllList.Add(this);
}
public void Dispose()
{
_AllList.Remove(this);
_AllByPrimaryKey.Remove(EmployeeID.ToString());
}
public static Employee New()
{
if (!CanAddObject())
throw new System.Security.SecurityException("User not authorized to add a Employee");
try
{
return DataPortal.Create<Employee>();
}
catch (Exception ex)
{
throw new DbCslaException("Error on Employee.New", ex);
}
}
public static Employee New(string lastName, string firstName)
{
Employee tmp = Employee.New();
tmp.LastName = lastName;
tmp.FirstName = firstName;
return tmp;
}
public static Employee New(string lastName, string firstName, string title, string titleOfCourtesy, string birthDate, string hireDate, string address, string city, string region, string postalCode, string country, string homePhone, string extension, byte[] photo, string notes, Employee myParent, string photoPath)
{
Employee tmp = Employee.New();
tmp.LastName = lastName;
tmp.FirstName = firstName;
tmp.Title = title;
tmp.TitleOfCourtesy = titleOfCourtesy;
tmp.BirthDate = birthDate;
tmp.HireDate = hireDate;
tmp.Address = address;
tmp.City = city;
tmp.Region = region;
tmp.PostalCode = postalCode;
tmp.Country = country;
tmp.HomePhone = homePhone;
tmp.Extension = extension;
tmp.Photo = photo;
tmp.Notes = notes;
tmp.MyParent = myParent;
tmp.PhotoPath = photoPath;
return tmp;
}
public static Employee MakeEmployee(string lastName, string firstName, string title, string titleOfCourtesy, string birthDate, string hireDate, string address, string city, string region, string postalCode, string country, string homePhone, string extension, byte[] photo, string notes, Employee myParent, string photoPath)
{
Employee tmp = Employee.New(lastName, firstName, title, titleOfCourtesy, birthDate, hireDate, address, city, region, postalCode, country, homePhone, extension, photo, notes, myParent, photoPath);
if (tmp.IsSavable)
tmp = tmp.Save();
else
{
Csla.Validation.BrokenRulesCollection brc = tmp.ValidationRules.GetBrokenRules();
tmp._ErrorMessage = "Failed Validation:";
foreach (Csla.Validation.BrokenRule br in brc)
{
tmp._ErrorMessage += "\r\n\tFailure: " + br.RuleName;
}
}
return tmp;
}
public static Employee Get(int employeeID)
{
if (!CanGetObject())
throw new System.Security.SecurityException("User not authorized to view a Employee");
try
{
Employee tmp = GetExistingByPrimaryKey(employeeID);
if (tmp == null)
{
tmp = DataPortal.Fetch<Employee>(new PKCriteria(employeeID));
_AllList.Add(tmp);
}
if (tmp.ErrorMessage == "No Record Found") tmp = null;
return tmp;
}
catch (Exception ex)
{
throw new DbCslaException("Error on Employee.Get", ex);
}
}
public static Employee Get(SafeDataReader dr, Employee parent)
{
if (dr.Read()) return new Employee(dr, parent);
return null;
}
internal Employee(SafeDataReader dr)
{
ReadData(dr);
}
private Employee(SafeDataReader dr, Employee parent)
{
ReadData(dr);
MarkAsChild();
}
public static void Delete(int employeeID)
{
if (!CanDeleteObject())
throw new System.Security.SecurityException("User not authorized to remove a Employee");
try
{
DataPortal.Delete(new PKCriteria(employeeID));
}
catch (Exception ex)
{
throw new DbCslaException("Error on Employee.Delete", ex);
}
}
public override Employee Save()
{
if (IsDeleted && !CanDeleteObject())
throw new System.Security.SecurityException("User not authorized to remove a Employee");
else if (IsNew && !CanAddObject())
throw new System.Security.SecurityException("User not authorized to add a Employee");
else if (!CanEditObject())
throw new System.Security.SecurityException("User not authorized to update a Employee");
try
{
BuildRefreshList();
Employee employee = base.Save();
_AllList.Add(employee);//Refresh the item in AllList
ProcessRefreshList();
return employee;
}
catch (Exception ex)
{
throw new DbCslaException("Error on CSLA Save", ex);
}
}
#endregion
#region Data Access Portal
[Serializable()]
protected class PKCriteria
{
private int _EmployeeID;
public int EmployeeID
{ get { return _EmployeeID; } }
public PKCriteria(int employeeID)
{
_EmployeeID = employeeID;
}
}
// TODO: If Create needs to access DB - It should not be marked RunLocal
[RunLocal()]
private new void DataPortal_Create()
{
_EmployeeID = NextEmployeeID;
// Database Defaults
// TODO: Add any defaults that are necessary
ValidationRules.CheckRules();
}
private void ReadData(SafeDataReader dr)
{
Database.LogInfo("Employee.ReadData", GetHashCode());
try
{
_EmployeeID = dr.GetInt32("EmployeeID");
_LastName = dr.GetString("LastName");
_FirstName = dr.GetString("FirstName");
_Title = dr.GetString("Title");
_TitleOfCourtesy = dr.GetString("TitleOfCourtesy");
_BirthDate = dr.GetSmartDate("BirthDate").Text;
_HireDate = dr.GetSmartDate("HireDate").Text;
_Address = dr.GetString("Address");
_City = dr.GetString("City");
_Region = dr.GetString("Region");
_PostalCode = dr.GetString("PostalCode");
_Country = dr.GetString("Country");
_HomePhone = dr.GetString("HomePhone");
_Extension = dr.GetString("Extension");
_Photo = (byte[])dr.GetValue("Photo");
_Notes = dr.GetString("Notes");
_ReportsTo = (int?)dr.GetValue("ReportsTo");
_PhotoPath = dr.GetString("PhotoPath");
_ChildEmployeeCount = dr.GetInt32("ChildCount");
_EmployeeEmployeeTerritoryCount = dr.GetInt32("EmployeeTerritoryCount");
_EmployeeOrderCount = dr.GetInt32("OrderCount");
MarkOld();
}
catch (Exception ex)
{
Database.LogException("Employee.ReadData", ex);
_ErrorMessage = ex.Message;
throw new DbCslaException("Employee.ReadData", ex);
}
}
private void DataPortal_Fetch(PKCriteria criteria)
{
Database.LogInfo("Employee.DataPortal_Fetch", GetHashCode());
try
{
using (SqlConnection cn = Database.Northwind_SqlConnection)
{
ApplicationContext.LocalContext["cn"] = cn;
using (SqlCommand cm = cn.CreateCommand())
{
cm.CommandType = CommandType.StoredProcedure;
cm.CommandText = "getEmployee";
cm.Parameters.AddWithValue("@EmployeeID", criteria.EmployeeID);
using (SafeDataReader dr = new SafeDataReader(cm.ExecuteReader()))
{
if (!dr.Read())
{
_ErrorMessage = "No Record Found";
return;
}
ReadData(dr);
// load child objects
dr.NextResult();
_EmployeeEmployeeTerritories = EmployeeEmployeeTerritories.Get(dr);
// load child objects
dr.NextResult();
_EmployeeOrders = EmployeeOrders.Get(dr);
}
}
// removing of item only needed for local data portal
if (ApplicationContext.ExecutionLocation == ApplicationContext.ExecutionLocations.Client)
ApplicationContext.LocalContext.Remove("cn");
}
}
catch (Exception ex)
{
Database.LogException("Employee.DataPortal_Fetch", ex);
_ErrorMessage = ex.Message;
throw new DbCslaException("Employee.DataPortal_Fetch", ex);
}
}
[Transactional(TransactionalTypes.TransactionScope)]
protected override void DataPortal_Insert()
{
try
{
using (SqlConnection cn = Database.Northwind_SqlConnection)
{
ApplicationContext.LocalContext["cn"] = cn;
SQLInsert();
// removing of item only needed for local data portal
if (ApplicationContext.ExecutionLocation == ApplicationContext.ExecutionLocations.Client)
ApplicationContext.LocalContext.Remove("cn");
}
}
catch (Exception ex)
{
Database.LogException("Employee.DataPortal_Insert", ex);
_ErrorMessage = ex.Message;
throw new DbCslaException("Employee.DataPortal_Insert", ex);
}
finally
{
Database.LogInfo("Employee.DataPortal_Insert", GetHashCode());
}
}
[Transactional(TransactionalTypes.TransactionScope)]
internal void SQLInsert()
{
if (!this.IsDirty) return;
try
{
SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"];
using (SqlCommand cm = cn.CreateCommand())
{
cm.CommandType = CommandType.StoredProcedure;
cm.CommandText = "addEmployee";
// Input All Fields - Except Calculated Columns
cm.Parameters.AddWithValue("@LastName", _LastName);
cm.Parameters.AddWithValue("@FirstName", _FirstName);
cm.Parameters.AddWithValue("@Title", _Title);
cm.Parameters.AddWithValue("@TitleOfCourtesy", _TitleOfCourtesy);
cm.Parameters.AddWithValue("@BirthDate", new SmartDate(_BirthDate).DBValue);
cm.Parameters.AddWithValue("@HireDate", new SmartDate(_HireDate).DBValue);
cm.Parameters.AddWithValue("@Address", _Address);
cm.Parameters.AddWithValue("@City", _City);
cm.Parameters.AddWithValue("@Region", _Region);
cm.Parameters.AddWithValue("@PostalCode", _PostalCode);
cm.Parameters.AddWithValue("@Country", _Country);
cm.Parameters.AddWithValue("@HomePhone", _HomePhone);
cm.Parameters.AddWithValue("@Extension", _Extension);
cm.Parameters.AddWithValue("@Photo", _Photo);
cm.Parameters.AddWithValue("@Notes", _Notes);
cm.Parameters.AddWithValue("@ReportsTo", ReportsTo);
cm.Parameters.AddWithValue("@PhotoPath", _PhotoPath);
// Output Calculated Columns
SqlParameter param_EmployeeID = new SqlParameter("@newEmployeeID", SqlDbType.Int);
param_EmployeeID.Direction = ParameterDirection.Output;
cm.Parameters.Add(param_EmployeeID);
// TODO: Define any additional output parameters
cm.ExecuteNonQuery();
// Save all values being returned from the Procedure
_EmployeeID = (int)cm.Parameters["@newEmployeeID"].Value;
}
MarkOld();
// update child objects
if (_EmployeeOrders != null) _EmployeeOrders.Update(this);
if (_ChildEmployees != null) _ChildEmployees.Update(this);
if (_EmployeeEmployeeTerritories != null) _EmployeeEmployeeTerritories.Update(this);
Database.LogInfo("Employee.SQLInsert", GetHashCode());
}
catch (Exception ex)
{
Database.LogException("Employee.SQLInsert", ex);
_ErrorMessage = ex.Message;
throw new DbCslaException("Employee.SQLInsert", ex);
}
}
[Transactional(TransactionalTypes.TransactionScope)]
public static void Add(SqlConnection cn, ref int employeeID, string lastName, string firstName, string title, string titleOfCourtesy, SmartDate birthDate, SmartDate hireDate, string address, string city, string region, string postalCode, string country, string homePhone, string extension, byte[] photo, string notes, Employee myParent, string photoPath)
{
Database.LogInfo("Employee.Add", 0);
try
{
using (SqlCommand cm = cn.CreateCommand())
{
cm.CommandType = CommandType.StoredProcedure;
cm.CommandText = "addEmployee";
// Input All Fields - Except Calculated Columns
cm.Parameters.AddWithValue("@LastName", lastName);
cm.Parameters.AddWithValue("@FirstName", firstName);
cm.Parameters.AddWithValue("@Title", title);
cm.Parameters.AddWithValue("@TitleOfCourtesy", titleOfCourtesy);
cm.Parameters.AddWithValue("@BirthDate", birthDate.DBValue);
cm.Parameters.AddWithValue("@HireDate", hireDate.DBValue);
cm.Parameters.AddWithValue("@Address", address);
cm.Parameters.AddWithValue("@City", city);
cm.Parameters.AddWithValue("@Region", region);
cm.Parameters.AddWithValue("@PostalCode", postalCode);
cm.Parameters.AddWithValue("@Country", country);
cm.Parameters.AddWithValue("@HomePhone", homePhone);
cm.Parameters.AddWithValue("@Extension", extension);
cm.Parameters.AddWithValue("@Photo", photo);
cm.Parameters.AddWithValue("@Notes", notes);
if(myParent != null)cm.Parameters.AddWithValue("@ReportsTo", myParent.EmployeeID);
cm.Parameters.AddWithValue("@PhotoPath", photoPath);
// Output Calculated Columns
SqlParameter param_EmployeeID = new SqlParameter("@newEmployeeID", SqlDbType.Int);
param_EmployeeID.Direction = ParameterDirection.Output;
cm.Parameters.Add(param_EmployeeID);
// TODO: Define any additional output parameters
cm.ExecuteNonQuery();
// Save all values being returned from the Procedure
employeeID = (int)cm.Parameters["@newEmployeeID"].Value;
// No Timestamp value to return
}
}
catch (Exception ex)
{
Database.LogException("Employee.Add", ex);
throw new DbCslaException("Employee.Add", ex);
}
}
[Transactional(TransactionalTypes.TransactionScope)]
protected override void DataPortal_Update()
{
if (!IsDirty) return; // If not dirty - nothing to do
Database.LogInfo("Employee.DataPortal_Update", GetHashCode());
try
{
using (SqlConnection cn = Database.Northwind_SqlConnection)
{
ApplicationContext.LocalContext["cn"] = cn;
SQLUpdate();
// removing of item only needed for local data portal
if (ApplicationContext.ExecutionLocation == ApplicationContext.ExecutionLocations.Client)
ApplicationContext.LocalContext.Remove("cn");
}
}
catch (Exception ex)
{
Database.LogException("Employee.DataPortal_Update", ex);
_ErrorMessage = ex.Message;
if (!ex.Message.EndsWith("has been edited by another user.")) throw ex;
}
}
[Transactional(TransactionalTypes.TransactionScope)]
internal void SQLUpdate()
{
if (!IsDirty) return; // If not dirty - nothing to do
Database.LogInfo("Employee.SQLUpdate", GetHashCode());
try
{
SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"];
if (base.IsDirty)
{
using (SqlCommand cm = cn.CreateCommand())
{
cm.CommandType = CommandType.StoredProcedure;
cm.CommandText = "updateEmployee";
// All Fields including Calculated Fields
cm.Parameters.AddWithValue("@EmployeeID", _EmployeeID);
cm.Parameters.AddWithValue("@LastName", _LastName);
cm.Parameters.AddWithValue("@FirstName", _FirstName);
cm.Parameters.AddWithValue("@Title", _Title);
cm.Parameters.AddWithValue("@TitleOfCourtesy", _TitleOfCourtesy);
cm.Parameters.AddWithValue("@BirthDate", new SmartDate(_BirthDate).DBValue);
cm.Parameters.AddWithValue("@HireDate", new SmartDate(_HireDate).DBValue);
cm.Parameters.AddWithValue("@Address", _Address);
cm.Parameters.AddWithValue("@City", _City);
cm.Parameters.AddWithValue("@Region", _Region);
cm.Parameters.AddWithValue("@PostalCode", _PostalCode);
cm.Parameters.AddWithValue("@Country", _Country);
cm.Parameters.AddWithValue("@HomePhone", _HomePhone);
cm.Parameters.AddWithValue("@Extension", _Extension);
cm.Parameters.AddWithValue("@Photo", _Photo);
cm.Parameters.AddWithValue("@Notes", _Notes);
cm.Parameters.AddWithValue("@ReportsTo", ReportsTo);
cm.Parameters.AddWithValue("@PhotoPath", _PhotoPath);
// Output Calculated Columns
// TODO: Define any additional output parameters
cm.ExecuteNonQuery();
// Save all values being returned from the Procedure
}
}
MarkOld();
// use the open connection to update child objects
if (_EmployeeOrders != null) _EmployeeOrders.Update(this);
if (_ChildEmployees != null) _ChildEmployees.Update(this);
if (_EmployeeEmployeeTerritories != null) _EmployeeEmployeeTerritories.Update(this);
}
catch (Exception ex)
{
Database.LogException("Employee.SQLUpdate", ex);
_ErrorMessage = ex.Message;
if (!ex.Message.EndsWith("has been edited by another user.")) throw ex;
}
}
internal void Update()
{
if (!this.IsDirty) return;
if (base.IsDirty)
{
SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"];
if (IsNew)
Employee.Add(cn, ref _EmployeeID, _LastName, _FirstName, _Title, _TitleOfCourtesy, new SmartDate(_BirthDate), new SmartDate(_HireDate), _Address, _City, _Region, _PostalCode, _Country, _HomePhone, _Extension, _Photo, _Notes, _MyParent, _PhotoPath);
else
Employee.Update(cn, ref _EmployeeID, _LastName, _FirstName, _Title, _TitleOfCourtesy, new SmartDate(_BirthDate), new SmartDate(_HireDate), _Address, _City, _Region, _PostalCode, _Country, _HomePhone, _Extension, _Photo, _Notes, _MyParent, _PhotoPath);
MarkOld();
}
if (_EmployeeOrders != null) _EmployeeOrders.Update(this);
if (_ChildEmployees != null) _ChildEmployees.Update(this);
if (_EmployeeEmployeeTerritories != null) _EmployeeEmployeeTerritories.Update(this);
}
[Transactional(TransactionalTypes.TransactionScope)]
public static void Update(SqlConnection cn, ref int employeeID, string lastName, string firstName, string title, string titleOfCourtesy, SmartDate birthDate, SmartDate hireDate, string address, string city, string region, string postalCode, string country, string homePhone, string extension, byte[] photo, string notes, Employee myParent, string photoPath)
{
Database.LogInfo("Employee.Update", 0);
try
{
using (SqlCommand cm = cn.CreateCommand())
{
cm.CommandType = CommandType.StoredProcedure;
cm.CommandText = "updateEmployee";
// Input All Fields - Except Calculated Columns
cm.Parameters.AddWithValue("@EmployeeID", employeeID);
cm.Parameters.AddWithValue("@LastName", lastName);
cm.Parameters.AddWithValue("@FirstName", firstName);
cm.Parameters.AddWithValue("@Title", title);
cm.Parameters.AddWithValue("@TitleOfCourtesy", titleOfCourtesy);
cm.Parameters.AddWithValue("@BirthDate", birthDate.DBValue);
cm.Parameters.AddWithValue("@HireDate", hireDate.DBValue);
cm.Parameters.AddWithValue("@Address", address);
cm.Parameters.AddWithValue("@City", city);
cm.Parameters.AddWithValue("@Region", region);
cm.Parameters.AddWithValue("@PostalCode", postalCode);
cm.Parameters.AddWithValue("@Country", country);
cm.Parameters.AddWithValue("@HomePhone", homePhone);
cm.Parameters.AddWithValue("@Extension", extension);
cm.Parameters.AddWithValue("@Photo", photo);
cm.Parameters.AddWithValue("@Notes", notes);
if(myParent != null)cm.Parameters.AddWithValue("@ReportsTo", myParent.EmployeeID);
cm.Parameters.AddWithValue("@PhotoPath", photoPath);
// Output Calculated Columns
// TODO: Define any additional output parameters
cm.ExecuteNonQuery();
// Save all values being returned from the Procedure
// No Timestamp value to return
}
}
catch (Exception ex)
{
Database.LogException("Employee.Update", ex);
throw new DbCslaException("Employee.Update", ex);
}
}
[Transactional(TransactionalTypes.TransactionScope)]
protected override void DataPortal_DeleteSelf()
{
DataPortal_Delete(new PKCriteria(_EmployeeID));
}
[Transactional(TransactionalTypes.TransactionScope)]
private void DataPortal_Delete(PKCriteria criteria)
{
Database.LogInfo("Employee.DataPortal_Delete", GetHashCode());
try
{
using (SqlConnection cn = Database.Northwind_SqlConnection)
{
using (SqlCommand cm = cn.CreateCommand())
{
cm.CommandType = CommandType.StoredProcedure;
cm.CommandText = "deleteEmployee";
cm.Parameters.AddWithValue("@EmployeeID", criteria.EmployeeID);
cm.ExecuteNonQuery();
}
}
}
catch (Exception ex)
{
Database.LogException("Employee.DataPortal_Delete", ex);
_ErrorMessage = ex.Message;
throw new DbCslaException("Employee.DataPortal_Delete", ex);
}
}
[Transactional(TransactionalTypes.TransactionScope)]
public static void Remove(SqlConnection cn, int employeeID)
{
Database.LogInfo("Employee.Remove", 0);
try
{
using (SqlCommand cm = cn.CreateCommand())
{
cm.CommandType = CommandType.StoredProcedure;
cm.CommandText = "deleteEmployee";
// Input PK Fields
cm.Parameters.AddWithValue("@EmployeeID", employeeID);
// TODO: Define any additional output parameters
cm.ExecuteNonQuery();
}
}
catch (Exception ex)
{
Database.LogException("Employee.Remove", ex);
throw new DbCslaException("Employee.Remove", ex);
}
}
#endregion
#region Exists
public static bool Exists(int employeeID)
{
ExistsCommand result;
try
{
result = DataPortal.Execute<ExistsCommand>(new ExistsCommand(employeeID));
return result.Exists;
}
catch (Exception ex)
{
throw new DbCslaException("Error on Employee.Exists", ex);
}
}
[Serializable()]
private class ExistsCommand : CommandBase
{
private int _EmployeeID;
private bool _exists;
public bool Exists
{
get { return _exists; }
}
public ExistsCommand(int employeeID)
{
_EmployeeID = employeeID;
}
protected override void DataPortal_Execute()
{
Database.LogInfo("Employee.DataPortal_Execute", GetHashCode());
try
{
using (SqlConnection cn = Database.Northwind_SqlConnection)
{
cn.Open();
using (SqlCommand cm = cn.CreateCommand())
{
cm.CommandType = CommandType.StoredProcedure;
cm.CommandText = "existsEmployee";
cm.Parameters.AddWithValue("@EmployeeID", _EmployeeID);
int count = (int)cm.ExecuteScalar();
_exists = (count > 0);
}
}
}
catch (Exception ex)
{
Database.LogException("Employee.DataPortal_Execute", ex);
throw new DbCslaException("Employee.DataPortal_Execute", ex);
}
}
}
#endregion
// Standard Default Code
#region extension
EmployeeExtension _EmployeeExtension = new EmployeeExtension();
[Serializable()]
partial class EmployeeExtension : extensionBase
{
}
[Serializable()]
class extensionBase
{
// Default Values
// Authorization Rules
public virtual void AddAuthorizationRules(Csla.Security.AuthorizationRules rules)
{
// Needs to be overriden to add new authorization rules
}
// Instance Authorization Rules
public virtual void AddInstanceAuthorizationRules(Csla.Security.AuthorizationRules rules)
{
// Needs to be overriden to add new authorization rules
}
// Validation Rules
public virtual void AddValidationRules(Csla.Validation.ValidationRules rules)
{
// Needs to be overriden to add new validation rules
}
// InstanceValidation Rules
public virtual void AddInstanceValidationRules(Csla.Validation.ValidationRules rules)
{
// Needs to be overriden to add new validation rules
}
}
#endregion
} // Class
#region Converter
internal class EmployeeConverter : ExpandableObjectConverter
{
public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType)
{
if (destType == typeof(string) && value is Employee)
{
// Return the ToString value
return ((Employee)value).ToString();
}
return base.ConvertTo(context, culture, value, destType);
}
}
#endregion
} // Namespace
//// The following is a sample Extension File. You can use it to create EmployeeExt.cs
//using System;
//using System.Collections.Generic;
//using System.Text;
//using Csla;
//namespace Northwind.CSLA.Library
//{
// public partial class Employee
// {
// partial class EmployeeExtension : extensionBase
// {
// // TODO: Override automatic defaults
// public new void AddAuthorizationRules(Csla.Security.AuthorizationRules rules)
// {
// //rules.AllowRead(Dbid, "<Role(s)>");
// }
// public new void AddInstanceAuthorizationRules(Csla.Security.AuthorizationRules rules)
// {
// //rules.AllowInstanceRead(Dbid, "<Role(s)>");
// }
// public new void AddValidationRules(Csla.Validation.ValidationRules rules)
// {
// rules.AddRule(
// Csla.Validation.CommonRules.StringMaxLength,
// new Csla.Validation.CommonRules.MaxLengthRuleArgs("Name", 100));
// }
// public new void AddInstanceValidationRules(Csla.Validation.ValidationRules rules)
// {
// rules.AddInstanceRule(/* Instance Validation Rule */);
// }
// }
// }
//}
| |
// 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.Data.Common;
using System.Diagnostics;
using System.IO;
using System.Runtime.InteropServices;
using System.Text;
using Xunit;
namespace System.Data.SqlClient.ManualTesting.Tests
{
[Trait("connection", "tcp")]
public class MultipleResultsTest
{
private StringBuilder _globalBuilder = new StringBuilder();
private StringBuilder _outputBuilder;
private string[] _outputFilter;
[CheckConnStrSetupFact]
public void TestMain()
{
Assert.True(RunTestCoreAndCompareWithBaseline());
}
private void RunTest()
{
MultipleErrorHandling(new SqlConnection((new SqlConnectionStringBuilder(DataTestUtility.TcpConnStr) { MultipleActiveResultSets = true }).ConnectionString));
}
private void MultipleErrorHandling(DbConnection connection)
{
try
{
Console.WriteLine("MultipleErrorHandling {0}", connection.GetType().Name);
Type expectedException = null;
if (connection is SqlConnection)
{
((SqlConnection)connection).InfoMessage += delegate (object sender, SqlInfoMessageEventArgs args)
{
Console.WriteLine("*** SQL CONNECTION INFO MESSAGE : {0} ****", args.Message);
};
expectedException = typeof(SqlException);
}
connection.Open();
using (DbCommand command = connection.CreateCommand())
{
command.CommandText =
"PRINT N'0';\n" +
"SELECT num = 1, str = 'ABC';\n" +
"PRINT N'1';\n" +
"RAISERROR('Error 1', 15, 1);\n" +
"PRINT N'3';\n" +
"SELECT num = 2, str = 'ABC';\n" +
"PRINT N'4';\n" +
"RAISERROR('Error 2', 15, 1);\n" +
"PRINT N'5';\n" +
"SELECT num = 3, str = 'ABC';\n" +
"PRINT N'6';\n" +
"RAISERROR('Error 3', 15, 1);\n" +
"PRINT N'7';\n" +
"SELECT num = 4, str = 'ABC';\n" +
"PRINT N'8';\n" +
"RAISERROR('Error 4', 15, 1);\n" +
"PRINT N'9';\n" +
"SELECT num = 5, str = 'ABC';\n" +
"PRINT N'10';\n" +
"RAISERROR('Error 5', 15, 1);\n" +
"PRINT N'11';\n";
try
{
Console.WriteLine("**** ExecuteNonQuery *****");
command.ExecuteNonQuery();
}
catch (Exception e)
{
PrintException(expectedException, e);
}
try
{
Console.WriteLine("**** ExecuteScalar ****");
command.ExecuteScalar();
}
catch (Exception e)
{
PrintException(expectedException, e);
}
try
{
Console.WriteLine("**** ExecuteReader ****");
using (DbDataReader reader = command.ExecuteReader())
{
bool moreResults = true;
do
{
try
{
Console.WriteLine("NextResult");
moreResults = reader.NextResult();
}
catch (Exception e)
{
PrintException(expectedException, e);
}
} while (moreResults);
}
}
catch (Exception e)
{
PrintException(null, e);
}
}
}
catch (Exception e)
{
PrintException(null, e);
}
try
{
connection.Dispose();
}
catch (Exception e)
{
PrintException(null, e);
}
}
private bool RunTestCoreAndCompareWithBaseline()
{
string outputPath = "MultipleResultsTest.out";
string baselinePath = @"ProviderAgnostic\MultipleResultsTest\MultipleResultsTest.bsl";
var fstream = new FileStream(outputPath, FileMode.Create, FileAccess.Write, FileShare.Read);
var swriter = new StreamWriter(fstream, Encoding.UTF8);
// Convert all string writes of '\n' to '\r\n' so output files can be 'text' not 'binary'
var twriter = new CarriageReturnLineFeedReplacer(swriter);
Console.SetOut(twriter); // "redirect" Console.Out
// Run Test
RunTest();
Console.Out.Flush();
Console.Out.Dispose();
// Recover the standard output stream
StreamWriter standardOutput = new StreamWriter(Console.OpenStandardOutput());
standardOutput.AutoFlush = true;
Console.SetOut(standardOutput);
// Compare output file
var comparisonResult = FindDiffFromBaseline(baselinePath, outputPath);
if (string.IsNullOrEmpty(comparisonResult))
{
return true;
}
Console.WriteLine("Test Failed!");
Console.WriteLine("Please compare baseline : {0} with output :{1}", Path.GetFullPath(baselinePath), Path.GetFullPath(outputPath));
Console.WriteLine("Comparison Results : ");
Console.WriteLine(comparisonResult);
return false;
}
private void PrintException(Type expected, Exception e, params string[] values)
{
try
{
Debug.Assert(null != e, "PrintException: null exception");
_globalBuilder.Length = 0;
_globalBuilder.Append(e.GetType().Name).Append(": ");
if (e is COMException)
{
_globalBuilder.Append("0x").Append((((COMException)e).HResult).ToString("X8"));
if (expected != e.GetType())
{
_globalBuilder.Append(": ").Append(e.ToString());
}
}
else
{
_globalBuilder.Append(e.Message);
}
AssemblyFilter(_globalBuilder);
Console.WriteLine(_globalBuilder.ToString());
if (expected != e.GetType())
{
Console.WriteLine(e.StackTrace);
}
if (null != values)
{
foreach (string value in values)
{
Console.WriteLine(value);
}
}
if (null != e.InnerException)
{
PrintException(e.InnerException.GetType(), e.InnerException);
}
Console.Out.Flush();
}
catch (Exception f)
{
Console.WriteLine(f);
}
}
private string FindDiffFromBaseline(string baselinePath, string outputPath)
{
var expectedLines = File.ReadAllLines(baselinePath);
var outputLines = File.ReadAllLines(outputPath);
var comparisonSb = new StringBuilder();
// Start compare results
var expectedLength = expectedLines.Length;
var outputLength = outputLines.Length;
var findDiffLength = Math.Min(expectedLength, outputLength);
// Find diff for each lines
for (var lineNo = 0; lineNo < findDiffLength; lineNo++)
{
if (!expectedLines[lineNo].Equals(outputLines[lineNo]))
{
comparisonSb.AppendFormat("** DIFF at line {0} \n", lineNo);
comparisonSb.AppendFormat("A : {0} \n", outputLines[lineNo]);
comparisonSb.AppendFormat("E : {0} \n", expectedLines[lineNo]);
}
}
var startIndex = findDiffLength - 1;
if (startIndex < 0) startIndex = 0;
if (findDiffLength < expectedLength)
{
comparisonSb.AppendFormat("** MISSING \n");
for (var lineNo = startIndex; lineNo < expectedLength; lineNo++)
{
comparisonSb.AppendFormat("{0} : {1}", lineNo, expectedLines[lineNo]);
}
}
if (findDiffLength < outputLength)
{
comparisonSb.AppendFormat("** EXTRA \n");
for (var lineNo = startIndex; lineNo < outputLength; lineNo++)
{
comparisonSb.AppendFormat("{0} : {1}", lineNo, outputLines[lineNo]);
}
}
return comparisonSb.ToString();
}
private string AssemblyFilter(StreamWriter writer)
{
if (null == _outputBuilder)
{
_outputBuilder = new StringBuilder();
}
_outputBuilder.Length = 0;
byte[] utf8 = ((MemoryStream)writer.BaseStream).ToArray();
string value = System.Text.Encoding.UTF8.GetString(utf8, 3, utf8.Length - 3); // skip 0xEF, 0xBB, 0xBF
_outputBuilder.Append(value);
AssemblyFilter(_outputBuilder);
return _outputBuilder.ToString();
}
private void AssemblyFilter(StringBuilder builder)
{
string[] filter = _outputFilter;
if (null == filter)
{
filter = new string[5];
string tmp = typeof(System.Guid).AssemblyQualifiedName;
filter[0] = tmp.Substring(tmp.IndexOf(','));
filter[1] = filter[0].Replace("mscorlib", "System");
filter[2] = filter[0].Replace("mscorlib", "System.Data");
filter[3] = filter[0].Replace("mscorlib", "System.Data.OracleClient");
filter[4] = filter[0].Replace("mscorlib", "System.Xml");
_outputFilter = filter;
}
for (int i = 0; i < filter.Length; ++i)
{
builder.Replace(filter[i], "");
}
}
/// <summary>
/// special wrapper for the text writer to replace single "\n" with "\n"
/// </summary>
private sealed class CarriageReturnLineFeedReplacer : TextWriter
{
private TextWriter _output;
private int _lineFeedCount;
private bool _hasCarriageReturn;
internal CarriageReturnLineFeedReplacer(TextWriter output)
{
if (output == null)
throw new ArgumentNullException("output");
_output = output;
}
public int LineFeedCount
{
get { return _lineFeedCount; }
}
public override Encoding Encoding
{
get { return _output.Encoding; }
}
public override IFormatProvider FormatProvider
{
get { return _output.FormatProvider; }
}
public override string NewLine
{
get { return _output.NewLine; }
set { _output.NewLine = value; }
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
((IDisposable)_output).Dispose();
}
_output = null;
}
public override void Flush()
{
_output.Flush();
}
public override void Write(char value)
{
if ('\n' == value)
{
_lineFeedCount++;
if (!_hasCarriageReturn)
{ // X'\n'Y -> X'\r\n'Y
_output.Write('\r');
}
}
_hasCarriageReturn = '\r' == value;
_output.Write(value);
}
}
}
}
| |
/// This code was generated by
/// \ / _ _ _| _ _
/// | (_)\/(_)(_|\/| |(/_ v1.0.0
/// / /
using System;
using System.Collections.Generic;
using Twilio.Base;
using Twilio.Converters;
namespace Twilio.Rest.Serverless.V1.Service.Environment
{
/// <summary>
/// PLEASE NOTE that this class contains beta products that are subject to change. Use them with caution.
///
/// Retrieve a list of all Variables.
/// </summary>
public class ReadVariableOptions : ReadOptions<VariableResource>
{
/// <summary>
/// The SID of the Service to read the Variable resources from
/// </summary>
public string PathServiceSid { get; }
/// <summary>
/// The SID of the Environment with the Variable resources to read
/// </summary>
public string PathEnvironmentSid { get; }
/// <summary>
/// Construct a new ReadVariableOptions
/// </summary>
/// <param name="pathServiceSid"> The SID of the Service to read the Variable resources from </param>
/// <param name="pathEnvironmentSid"> The SID of the Environment with the Variable resources to read </param>
public ReadVariableOptions(string pathServiceSid, string pathEnvironmentSid)
{
PathServiceSid = pathServiceSid;
PathEnvironmentSid = pathEnvironmentSid;
}
/// <summary>
/// Generate the necessary parameters
/// </summary>
public override List<KeyValuePair<string, string>> GetParams()
{
var p = new List<KeyValuePair<string, string>>();
if (PageSize != null)
{
p.Add(new KeyValuePair<string, string>("PageSize", PageSize.ToString()));
}
return p;
}
}
/// <summary>
/// PLEASE NOTE that this class contains beta products that are subject to change. Use them with caution.
///
/// Retrieve a specific Variable.
/// </summary>
public class FetchVariableOptions : IOptions<VariableResource>
{
/// <summary>
/// The SID of the Service to fetch the Variable resource from
/// </summary>
public string PathServiceSid { get; }
/// <summary>
/// The SID of the Environment with the Variable resource to fetch
/// </summary>
public string PathEnvironmentSid { get; }
/// <summary>
/// The SID of the Variable resource to fetch
/// </summary>
public string PathSid { get; }
/// <summary>
/// Construct a new FetchVariableOptions
/// </summary>
/// <param name="pathServiceSid"> The SID of the Service to fetch the Variable resource from </param>
/// <param name="pathEnvironmentSid"> The SID of the Environment with the Variable resource to fetch </param>
/// <param name="pathSid"> The SID of the Variable resource to fetch </param>
public FetchVariableOptions(string pathServiceSid, string pathEnvironmentSid, string pathSid)
{
PathServiceSid = pathServiceSid;
PathEnvironmentSid = pathEnvironmentSid;
PathSid = pathSid;
}
/// <summary>
/// Generate the necessary parameters
/// </summary>
public List<KeyValuePair<string, string>> GetParams()
{
var p = new List<KeyValuePair<string, string>>();
return p;
}
}
/// <summary>
/// PLEASE NOTE that this class contains beta products that are subject to change. Use them with caution.
///
/// Create a new Variable.
/// </summary>
public class CreateVariableOptions : IOptions<VariableResource>
{
/// <summary>
/// The SID of the Service to create the Variable resource under
/// </summary>
public string PathServiceSid { get; }
/// <summary>
/// The SID of the Environment in which the Variable exists
/// </summary>
public string PathEnvironmentSid { get; }
/// <summary>
/// A string by which the Variable resource can be referenced
/// </summary>
public string Key { get; }
/// <summary>
/// A string that contains the actual value of the Variable
/// </summary>
public string Value { get; }
/// <summary>
/// Construct a new CreateVariableOptions
/// </summary>
/// <param name="pathServiceSid"> The SID of the Service to create the Variable resource under </param>
/// <param name="pathEnvironmentSid"> The SID of the Environment in which the Variable exists </param>
/// <param name="key"> A string by which the Variable resource can be referenced </param>
/// <param name="value"> A string that contains the actual value of the Variable </param>
public CreateVariableOptions(string pathServiceSid, string pathEnvironmentSid, string key, string value)
{
PathServiceSid = pathServiceSid;
PathEnvironmentSid = pathEnvironmentSid;
Key = key;
Value = value;
}
/// <summary>
/// Generate the necessary parameters
/// </summary>
public List<KeyValuePair<string, string>> GetParams()
{
var p = new List<KeyValuePair<string, string>>();
if (Key != null)
{
p.Add(new KeyValuePair<string, string>("Key", Key));
}
if (Value != null)
{
p.Add(new KeyValuePair<string, string>("Value", Value));
}
return p;
}
}
/// <summary>
/// PLEASE NOTE that this class contains beta products that are subject to change. Use them with caution.
///
/// Update a specific Variable.
/// </summary>
public class UpdateVariableOptions : IOptions<VariableResource>
{
/// <summary>
/// The SID of the Service to update the Variable resource under
/// </summary>
public string PathServiceSid { get; }
/// <summary>
/// The SID of the Environment with the Variable resource to update
/// </summary>
public string PathEnvironmentSid { get; }
/// <summary>
/// The SID of the Variable resource to update
/// </summary>
public string PathSid { get; }
/// <summary>
/// A string by which the Variable resource can be referenced
/// </summary>
public string Key { get; set; }
/// <summary>
/// A string that contains the actual value of the Variable
/// </summary>
public string Value { get; set; }
/// <summary>
/// Construct a new UpdateVariableOptions
/// </summary>
/// <param name="pathServiceSid"> The SID of the Service to update the Variable resource under </param>
/// <param name="pathEnvironmentSid"> The SID of the Environment with the Variable resource to update </param>
/// <param name="pathSid"> The SID of the Variable resource to update </param>
public UpdateVariableOptions(string pathServiceSid, string pathEnvironmentSid, string pathSid)
{
PathServiceSid = pathServiceSid;
PathEnvironmentSid = pathEnvironmentSid;
PathSid = pathSid;
}
/// <summary>
/// Generate the necessary parameters
/// </summary>
public List<KeyValuePair<string, string>> GetParams()
{
var p = new List<KeyValuePair<string, string>>();
if (Key != null)
{
p.Add(new KeyValuePair<string, string>("Key", Key));
}
if (Value != null)
{
p.Add(new KeyValuePair<string, string>("Value", Value));
}
return p;
}
}
/// <summary>
/// PLEASE NOTE that this class contains beta products that are subject to change. Use them with caution.
///
/// Delete a specific Variable.
/// </summary>
public class DeleteVariableOptions : IOptions<VariableResource>
{
/// <summary>
/// The SID of the Service to delete the Variable resource from
/// </summary>
public string PathServiceSid { get; }
/// <summary>
/// The SID of the Environment with the Variables to delete
/// </summary>
public string PathEnvironmentSid { get; }
/// <summary>
/// The SID of the Variable resource to delete
/// </summary>
public string PathSid { get; }
/// <summary>
/// Construct a new DeleteVariableOptions
/// </summary>
/// <param name="pathServiceSid"> The SID of the Service to delete the Variable resource from </param>
/// <param name="pathEnvironmentSid"> The SID of the Environment with the Variables to delete </param>
/// <param name="pathSid"> The SID of the Variable resource to delete </param>
public DeleteVariableOptions(string pathServiceSid, string pathEnvironmentSid, string pathSid)
{
PathServiceSid = pathServiceSid;
PathEnvironmentSid = pathEnvironmentSid;
PathSid = pathSid;
}
/// <summary>
/// Generate the necessary parameters
/// </summary>
public List<KeyValuePair<string, string>> GetParams()
{
var p = new List<KeyValuePair<string, string>>();
return p;
}
}
}
| |
// #define IMITATE_BATCH_MODE //uncomment if you want to imitate batch mode behaviour in non-batch mode mode run
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using UnityEngine;
using UnityTest.IntegrationTestRunner;
namespace UnityTest
{
[Serializable]
public class TestRunner : MonoBehaviour
{
static private readonly TestResultRenderer k_ResultRenderer = new TestResultRenderer();
public TestComponent currentTest;
private List<TestResult> m_ResultList = new List<TestResult>();
private List<TestComponent> m_TestComponents;
public bool isInitializedByRunner
{
get
{
#if !IMITATE_BATCH_MODE
if (Application.isEditor && !IsBatchMode())
return true;
#endif
return false;
}
}
private double m_StartTime;
private bool m_ReadyToRun;
private AssertionComponent[] m_AssertionsToCheck;
private string m_TestMessages;
private string m_Stacktrace;
private TestState m_TestState = TestState.Running;
private TestRunnerConfigurator m_Configurator;
public TestRunnerCallbackList TestRunnerCallback = new TestRunnerCallbackList();
private IntegrationTestsProvider m_TestsProvider;
private const string k_Prefix = "IntegrationTest";
private const string k_StartedMessage = k_Prefix + " Started";
private const string k_FinishedMessage = k_Prefix + " Finished";
private const string k_TimeoutMessage = k_Prefix + " Timeout";
private const string k_FailedMessage = k_Prefix + " Failed";
private const string k_FailedExceptionMessage = k_Prefix + " Failed with exception";
private const string k_IgnoredMessage = k_Prefix + " Ignored";
private const string k_InterruptedMessage = k_Prefix + " Run interrupted";
public void Awake()
{
m_Configurator = new TestRunnerConfigurator();
if (isInitializedByRunner) return;
TestComponent.DisableAllTests();
}
public void Start()
{
if (isInitializedByRunner) return;
if (m_Configurator.sendResultsOverNetwork)
{
var nrs = m_Configurator.ResolveNetworkConnection();
if (nrs != null)
TestRunnerCallback.Add(nrs);
}
TestComponent.DestroyAllDynamicTests();
var dynamicTestTypes = TestComponent.GetTypesWithHelpAttribute(Application.loadedLevelName);
foreach (var dynamicTestType in dynamicTestTypes)
TestComponent.CreateDynamicTest(dynamicTestType);
var tests = TestComponent.FindAllTestsOnScene();
InitRunner(tests, dynamicTestTypes.Select(type => type.AssemblyQualifiedName).ToList());
}
public void InitRunner(List<TestComponent> tests, List<string> dynamicTestsToRun)
{
m_CurrentlyRegisteredLogCallback = GetLogCallbackField();
m_LogCallback = LogHandler;
Application.RegisterLogCallback(m_LogCallback);
// Init dynamic tests
foreach (var typeName in dynamicTestsToRun)
{
var t = Type.GetType(typeName);
if (t == null) continue;
var scriptComponents = Resources.FindObjectsOfTypeAll(t) as MonoBehaviour[];
if (scriptComponents.Length == 0)
{
Debug.LogWarning(t + " not found. Skipping.");
continue;
}
if (scriptComponents.Length > 1) Debug.LogWarning("Multiple GameObjects refer to " + typeName);
tests.Add(scriptComponents.First().GetComponent<TestComponent>());
}
// create test structure
m_TestComponents = ParseListForGroups(tests).ToList();
// create results for tests
m_ResultList = m_TestComponents.Select(component => new TestResult(component)).ToList();
// init test provider
m_TestsProvider = new IntegrationTestsProvider(m_ResultList.Select(result => result.TestComponent as ITestComponent));
m_ReadyToRun = true;
}
private static IEnumerable<TestComponent> ParseListForGroups(IEnumerable<TestComponent> tests)
{
var results = new HashSet<TestComponent>();
foreach (var testResult in tests)
{
if (testResult.IsTestGroup())
{
var childrenTestResult = testResult.gameObject.GetComponentsInChildren(typeof(TestComponent), true)
.Where(t => t != testResult)
.Cast<TestComponent>()
.ToArray();
foreach (var result in childrenTestResult)
{
if (!result.IsTestGroup())
results.Add(result);
}
continue;
}
results.Add(testResult);
}
return results;
}
public void Update()
{
if (m_ReadyToRun && Time.frameCount > 1)
{
m_ReadyToRun = false;
StartCoroutine("StateMachine");
}
LogCallbackStillRegistered();
}
public void OnDestroy()
{
if (currentTest != null)
{
var testResult = m_ResultList.Single(result => result.TestComponent == currentTest);
testResult.messages += "Test run interrupted (crash?)";
LogMessage(k_InterruptedMessage);
FinishTest(TestResult.ResultType.Failed);
}
if (currentTest != null || (m_TestsProvider != null && m_TestsProvider.AnyTestsLeft()))
{
var remainingTests = m_TestsProvider.GetRemainingTests();
TestRunnerCallback.TestRunInterrupted(remainingTests.ToList());
}
Application.RegisterLogCallback(null);
}
private void LogHandler(string condition, string stacktrace, LogType type)
{
if (!condition.StartsWith(k_StartedMessage) && !condition.StartsWith(k_FinishedMessage))
{
var msg = condition;
if (msg.StartsWith(k_Prefix)) msg = msg.Substring(k_Prefix.Length + 1);
if (currentTest != null && msg.EndsWith("(" + currentTest.name + ')')) msg = msg.Substring(0, msg.LastIndexOf('('));
m_TestMessages += msg + "\n";
}
switch (type)
{
case LogType.Exception:
{
var exceptionType = condition.Substring(0, condition.IndexOf(':'));
if (currentTest != null && currentTest.IsExceptionExpected(exceptionType))
{
m_TestMessages += exceptionType + " was expected\n";
if (currentTest.ShouldSucceedOnException())
{
m_TestState = TestState.Success;
}
}
else
{
m_TestState = TestState.Exception;
m_Stacktrace = stacktrace;
}
}
break;
case LogType.Assert:
case LogType.Error:
m_TestState = TestState.Failure;
m_Stacktrace = stacktrace;
break;
case LogType.Log:
if (m_TestState == TestState.Running && condition.StartsWith(IntegrationTest.passMessage))
{
m_TestState = TestState.Success;
}
if (condition.StartsWith(IntegrationTest.failMessage))
{
m_TestState = TestState.Failure;
}
break;
}
}
public IEnumerator StateMachine()
{
TestRunnerCallback.RunStarted(Application.platform.ToString(), m_TestComponents);
while (true)
{
if (!m_TestsProvider.AnyTestsLeft() && currentTest == null)
{
FinishTestRun();
yield break;
}
if (currentTest == null)
{
StartNewTest();
}
if (currentTest != null)
{
if (m_TestState == TestState.Running)
{
if (m_AssertionsToCheck != null && m_AssertionsToCheck.All(a => a.checksPerformed > 0))
{
IntegrationTest.Pass(currentTest.gameObject);
m_TestState = TestState.Success;
}
if (currentTest != null && Time.time > m_StartTime + currentTest.GetTimeout())
{
m_TestState = TestState.Timeout;
}
}
switch (m_TestState)
{
case TestState.Success:
LogMessage(k_FinishedMessage);
FinishTest(TestResult.ResultType.Success);
break;
case TestState.Failure:
LogMessage(k_FailedMessage);
FinishTest(TestResult.ResultType.Failed);
break;
case TestState.Exception:
LogMessage(k_FailedExceptionMessage);
FinishTest(TestResult.ResultType.FailedException);
break;
case TestState.Timeout:
LogMessage(k_TimeoutMessage);
FinishTest(TestResult.ResultType.Timeout);
break;
case TestState.Ignored:
LogMessage(k_IgnoredMessage);
FinishTest(TestResult.ResultType.Ignored);
break;
}
}
yield return null;
}
}
private void LogMessage(string message)
{
if (currentTest != null)
Debug.Log(message + " (" + currentTest.Name + ")", currentTest.gameObject);
else
Debug.Log(message);
}
private void FinishTestRun()
{
PrintResultToLog();
TestRunnerCallback.RunFinished(m_ResultList);
LoadNextLevelOrQuit();
}
private void PrintResultToLog()
{
var resultString = "";
resultString += "Passed: " + m_ResultList.Count(t => t.IsSuccess);
if (m_ResultList.Any(result => result.IsFailure))
{
resultString += " Failed: " + m_ResultList.Count(t => t.IsFailure);
Debug.Log("Failed tests: " + string.Join(", ", m_ResultList.Where(t => t.IsFailure).Select(result => result.Name).ToArray()));
}
if (m_ResultList.Any(result => result.IsIgnored))
{
resultString += " Ignored: " + m_ResultList.Count(t => t.IsIgnored);
Debug.Log("Ignored tests: " + string.Join(", ",
m_ResultList.Where(t => t.IsIgnored).Select(result => result.Name).ToArray()));
}
Debug.Log(resultString);
}
private void LoadNextLevelOrQuit()
{
if (isInitializedByRunner) return;
if (Application.loadedLevel < Application.levelCount - 1)
Application.LoadLevel(Application.loadedLevel + 1);
else
{
k_ResultRenderer.ShowResults();
if (m_Configurator.isBatchRun && m_Configurator.sendResultsOverNetwork)
Application.Quit();
}
}
public void OnGUI()
{
k_ResultRenderer.Draw();
}
private void StartNewTest()
{
m_TestMessages = "";
m_Stacktrace = "";
m_TestState = TestState.Running;
m_AssertionsToCheck = null;
m_StartTime = Time.time;
currentTest = m_TestsProvider.GetNextTest() as TestComponent;
var testResult = m_ResultList.Single(result => result.TestComponent == currentTest);
if (currentTest != null && currentTest.ShouldSucceedOnAssertions())
{
var assertionList = currentTest.gameObject.GetComponentsInChildren<AssertionComponent>().Where(a => a.enabled);
if (assertionList.Any())
m_AssertionsToCheck = assertionList.ToArray();
}
if (currentTest != null && currentTest.IsExludedOnThisPlatform())
{
m_TestState = TestState.Ignored;
Debug.Log(currentTest.gameObject.name + " is excluded on this platform");
}
// don't ignore test if user initiated it from the runner and it's the only test that is being run
if (currentTest != null
&& (currentTest.IsIgnored()
&& !(isInitializedByRunner && m_ResultList.Count == 1)))
m_TestState = TestState.Ignored;
LogMessage(k_StartedMessage);
TestRunnerCallback.TestStarted(testResult);
}
private void FinishTest(TestResult.ResultType result)
{
m_TestsProvider.FinishTest(currentTest);
var testResult = m_ResultList.Single(t => t.GameObject == currentTest.gameObject);
testResult.resultType = result;
testResult.duration = Time.time - m_StartTime;
testResult.messages = m_TestMessages;
testResult.stacktrace = m_Stacktrace;
TestRunnerCallback.TestFinished(testResult);
currentTest = null;
if (!testResult.IsSuccess
&& testResult.Executed
&& !testResult.IsIgnored) k_ResultRenderer.AddResults(Application.loadedLevelName, testResult);
}
#region Test Runner Helpers
public static TestRunner GetTestRunner()
{
TestRunner testRunnerComponent = null;
var testRunnerComponents = Resources.FindObjectsOfTypeAll(typeof(TestRunner));
if (testRunnerComponents.Count() > 1)
foreach (var t in testRunnerComponents) DestroyImmediate(((TestRunner)t).gameObject);
else if (!testRunnerComponents.Any())
testRunnerComponent = Create().GetComponent<TestRunner>();
else
testRunnerComponent = testRunnerComponents.Single() as TestRunner;
return testRunnerComponent;
}
private static GameObject Create()
{
var runner = new GameObject("TestRunner");
var component = runner.AddComponent<TestRunner>();
component.hideFlags = HideFlags.NotEditable;
Debug.Log("Created Test Runner");
return runner;
}
private static bool IsBatchMode()
{
#if !UNITY_METRO
const string internalEditorUtilityClassName = "UnityEditorInternal.InternalEditorUtility, UnityEditor, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null";
var t = Type.GetType(internalEditorUtilityClassName, false);
if (t == null) return false;
const string inBatchModeProperty = "inBatchMode";
var prop = t.GetProperty(inBatchModeProperty);
return (bool)prop.GetValue(null, null);
#else // if !UNITY_METRO
return false;
#endif // if !UNITY_METRO
}
#endregion
#region LogCallback check
private Application.LogCallback m_LogCallback;
private FieldInfo m_CurrentlyRegisteredLogCallback;
public void LogCallbackStillRegistered()
{
if (Application.platform == RuntimePlatform.OSXWebPlayer
|| Application.platform == RuntimePlatform.WindowsWebPlayer)
return;
if (m_CurrentlyRegisteredLogCallback == null) return;
var v = (Application.LogCallback)m_CurrentlyRegisteredLogCallback.GetValue(null);
if (v == m_LogCallback) return;
Debug.LogError("Log callback got changed. This may be caused by other tools using RegisterLogCallback.");
Application.RegisterLogCallback(m_LogCallback);
}
private FieldInfo GetLogCallbackField()
{
#if !UNITY_METRO
var type = typeof(Application);
var f = type.GetFields(BindingFlags.Static | BindingFlags.NonPublic).Where(p => p.Name == "s_LogCallback");
if (f.Count() != 1) return null;
return f.Single();
#else
return null;
#endif
}
#endregion
enum TestState
{
Running,
Success,
Failure,
Exception,
Timeout,
Ignored
}
}
}
| |
// Code generated by Microsoft (R) AutoRest Code Generator 1.1.0.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Petstore
{
using Models;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// Extension methods for SwaggerPetstore.
/// </summary>
public static partial class SwaggerPetstoreExtensions
{
/// <summary>
/// Fake endpoint to test byte array in body parameter for adding a new pet to
/// the store
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='body'>
/// Pet object in the form of byte array
/// </param>
public static void AddPetUsingByteArray(this ISwaggerPetstore operations, string body = default(string))
{
operations.AddPetUsingByteArrayAsync(body).GetAwaiter().GetResult();
}
/// <summary>
/// Fake endpoint to test byte array in body parameter for adding a new pet to
/// the store
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='body'>
/// Pet object in the form of byte array
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task AddPetUsingByteArrayAsync(this ISwaggerPetstore operations, string body = default(string), CancellationToken cancellationToken = default(CancellationToken))
{
(await operations.AddPetUsingByteArrayWithHttpMessagesAsync(body, null, cancellationToken).ConfigureAwait(false)).Dispose();
}
/// <summary>
/// Add a new pet to the store
/// </summary>
/// <remarks>
/// Adds a new pet to the store. You may receive an HTTP invalid input if your
/// pet is invalid.
/// </remarks>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='body'>
/// Pet object that needs to be added to the store
/// </param>
public static void AddPet(this ISwaggerPetstore operations, Pet body = default(Pet))
{
operations.AddPetAsync(body).GetAwaiter().GetResult();
}
/// <summary>
/// Add a new pet to the store
/// </summary>
/// <remarks>
/// Adds a new pet to the store. You may receive an HTTP invalid input if your
/// pet is invalid.
/// </remarks>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='body'>
/// Pet object that needs to be added to the store
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task AddPetAsync(this ISwaggerPetstore operations, Pet body = default(Pet), CancellationToken cancellationToken = default(CancellationToken))
{
(await operations.AddPetWithHttpMessagesAsync(body, null, cancellationToken).ConfigureAwait(false)).Dispose();
}
/// <summary>
/// Update an existing pet
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='body'>
/// Pet object that needs to be added to the store
/// </param>
public static void UpdatePet(this ISwaggerPetstore operations, Pet body = default(Pet))
{
operations.UpdatePetAsync(body).GetAwaiter().GetResult();
}
/// <summary>
/// Update an existing pet
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='body'>
/// Pet object that needs to be added to the store
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task UpdatePetAsync(this ISwaggerPetstore operations, Pet body = default(Pet), CancellationToken cancellationToken = default(CancellationToken))
{
(await operations.UpdatePetWithHttpMessagesAsync(body, null, cancellationToken).ConfigureAwait(false)).Dispose();
}
/// <summary>
/// Finds Pets by status
/// </summary>
/// <remarks>
/// Multiple status values can be provided with comma seperated strings
/// </remarks>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='status'>
/// Status values that need to be considered for filter
/// </param>
public static IList<Pet> FindPetsByStatus(this ISwaggerPetstore operations, IList<string> status = default(IList<string>))
{
return operations.FindPetsByStatusAsync(status).GetAwaiter().GetResult();
}
/// <summary>
/// Finds Pets by status
/// </summary>
/// <remarks>
/// Multiple status values can be provided with comma seperated strings
/// </remarks>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='status'>
/// Status values that need to be considered for filter
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IList<Pet>> FindPetsByStatusAsync(this ISwaggerPetstore operations, IList<string> status = default(IList<string>), CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.FindPetsByStatusWithHttpMessagesAsync(status, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Finds Pets by tags
/// </summary>
/// <remarks>
/// Muliple tags can be provided with comma seperated strings. Use tag1, tag2,
/// tag3 for testing.
/// </remarks>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='tags'>
/// Tags to filter by
/// </param>
public static IList<Pet> FindPetsByTags(this ISwaggerPetstore operations, IList<string> tags = default(IList<string>))
{
return operations.FindPetsByTagsAsync(tags).GetAwaiter().GetResult();
}
/// <summary>
/// Finds Pets by tags
/// </summary>
/// <remarks>
/// Muliple tags can be provided with comma seperated strings. Use tag1, tag2,
/// tag3 for testing.
/// </remarks>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='tags'>
/// Tags to filter by
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IList<Pet>> FindPetsByTagsAsync(this ISwaggerPetstore operations, IList<string> tags = default(IList<string>), CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.FindPetsByTagsWithHttpMessagesAsync(tags, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Fake endpoint to test byte array return by 'Find pet by ID'
/// </summary>
/// <remarks>
/// Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API
/// error conditions
/// </remarks>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='petId'>
/// ID of pet that needs to be fetched
/// </param>
public static string FindPetsWithByteArray(this ISwaggerPetstore operations, long petId)
{
return operations.FindPetsWithByteArrayAsync(petId).GetAwaiter().GetResult();
}
/// <summary>
/// Fake endpoint to test byte array return by 'Find pet by ID'
/// </summary>
/// <remarks>
/// Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API
/// error conditions
/// </remarks>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='petId'>
/// ID of pet that needs to be fetched
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<string> FindPetsWithByteArrayAsync(this ISwaggerPetstore operations, long petId, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.FindPetsWithByteArrayWithHttpMessagesAsync(petId, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Find pet by ID
/// </summary>
/// <remarks>
/// Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API
/// error conditions
/// </remarks>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='petId'>
/// ID of pet that needs to be fetched
/// </param>
public static Pet GetPetById(this ISwaggerPetstore operations, long petId)
{
return operations.GetPetByIdAsync(petId).GetAwaiter().GetResult();
}
/// <summary>
/// Find pet by ID
/// </summary>
/// <remarks>
/// Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API
/// error conditions
/// </remarks>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='petId'>
/// ID of pet that needs to be fetched
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<Pet> GetPetByIdAsync(this ISwaggerPetstore operations, long petId, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetPetByIdWithHttpMessagesAsync(petId, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Updates a pet in the store with form data
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='petId'>
/// ID of pet that needs to be updated
/// </param>
/// <param name='name'>
/// Updated name of the pet
/// </param>
/// <param name='status'>
/// Updated status of the pet
/// </param>
public static void UpdatePetWithForm(this ISwaggerPetstore operations, string petId, string name = default(string), string status = default(string))
{
operations.UpdatePetWithFormAsync(petId, name, status).GetAwaiter().GetResult();
}
/// <summary>
/// Updates a pet in the store with form data
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='petId'>
/// ID of pet that needs to be updated
/// </param>
/// <param name='name'>
/// Updated name of the pet
/// </param>
/// <param name='status'>
/// Updated status of the pet
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task UpdatePetWithFormAsync(this ISwaggerPetstore operations, string petId, string name = default(string), string status = default(string), CancellationToken cancellationToken = default(CancellationToken))
{
(await operations.UpdatePetWithFormWithHttpMessagesAsync(petId, name, status, null, cancellationToken).ConfigureAwait(false)).Dispose();
}
/// <summary>
/// Deletes a pet
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='petId'>
/// Pet id to delete
/// </param>
/// <param name='apiKey'>
/// </param>
public static void DeletePet(this ISwaggerPetstore operations, long petId, string apiKey = default(string))
{
operations.DeletePetAsync(petId, apiKey).GetAwaiter().GetResult();
}
/// <summary>
/// Deletes a pet
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='petId'>
/// Pet id to delete
/// </param>
/// <param name='apiKey'>
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task DeletePetAsync(this ISwaggerPetstore operations, long petId, string apiKey = default(string), CancellationToken cancellationToken = default(CancellationToken))
{
(await operations.DeletePetWithHttpMessagesAsync(petId, apiKey, null, cancellationToken).ConfigureAwait(false)).Dispose();
}
/// <summary>
/// uploads an image
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='petId'>
/// ID of pet to update
/// </param>
/// <param name='additionalMetadata'>
/// Additional data to pass to server
/// </param>
/// <param name='file'>
/// file to upload
/// </param>
public static void UploadFile(this ISwaggerPetstore operations, long petId, string additionalMetadata = default(string), Stream file = default(Stream))
{
operations.UploadFileAsync(petId, additionalMetadata, file).GetAwaiter().GetResult();
}
/// <summary>
/// uploads an image
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='petId'>
/// ID of pet to update
/// </param>
/// <param name='additionalMetadata'>
/// Additional data to pass to server
/// </param>
/// <param name='file'>
/// file to upload
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task UploadFileAsync(this ISwaggerPetstore operations, long petId, string additionalMetadata = default(string), Stream file = default(Stream), CancellationToken cancellationToken = default(CancellationToken))
{
(await operations.UploadFileWithHttpMessagesAsync(petId, additionalMetadata, file, null, cancellationToken).ConfigureAwait(false)).Dispose();
}
/// <summary>
/// Returns pet inventories by status
/// </summary>
/// <remarks>
/// Returns a map of status codes to quantities
/// </remarks>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
public static IDictionary<string, int?> GetInventory(this ISwaggerPetstore operations)
{
return operations.GetInventoryAsync().GetAwaiter().GetResult();
}
/// <summary>
/// Returns pet inventories by status
/// </summary>
/// <remarks>
/// Returns a map of status codes to quantities
/// </remarks>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IDictionary<string, int?>> GetInventoryAsync(this ISwaggerPetstore operations, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetInventoryWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Place an order for a pet
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='body'>
/// order placed for purchasing the pet
/// </param>
public static Order PlaceOrder(this ISwaggerPetstore operations, Order body = default(Order))
{
return operations.PlaceOrderAsync(body).GetAwaiter().GetResult();
}
/// <summary>
/// Place an order for a pet
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='body'>
/// order placed for purchasing the pet
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<Order> PlaceOrderAsync(this ISwaggerPetstore operations, Order body = default(Order), CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.PlaceOrderWithHttpMessagesAsync(body, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Find purchase order by ID
/// </summary>
/// <remarks>
/// For valid response try integer IDs with value <= 5 or > 10. Other
/// values will generated exceptions
/// </remarks>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='orderId'>
/// ID of pet that needs to be fetched
/// </param>
public static Order GetOrderById(this ISwaggerPetstore operations, string orderId)
{
return operations.GetOrderByIdAsync(orderId).GetAwaiter().GetResult();
}
/// <summary>
/// Find purchase order by ID
/// </summary>
/// <remarks>
/// For valid response try integer IDs with value <= 5 or > 10. Other
/// values will generated exceptions
/// </remarks>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='orderId'>
/// ID of pet that needs to be fetched
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<Order> GetOrderByIdAsync(this ISwaggerPetstore operations, string orderId, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetOrderByIdWithHttpMessagesAsync(orderId, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Delete purchase order by ID
/// </summary>
/// <remarks>
/// For valid response try integer IDs with value < 1000. Anything above
/// 1000 or nonintegers will generate API errors
/// </remarks>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='orderId'>
/// ID of the order that needs to be deleted
/// </param>
public static void DeleteOrder(this ISwaggerPetstore operations, string orderId)
{
operations.DeleteOrderAsync(orderId).GetAwaiter().GetResult();
}
/// <summary>
/// Delete purchase order by ID
/// </summary>
/// <remarks>
/// For valid response try integer IDs with value < 1000. Anything above
/// 1000 or nonintegers will generate API errors
/// </remarks>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='orderId'>
/// ID of the order that needs to be deleted
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task DeleteOrderAsync(this ISwaggerPetstore operations, string orderId, CancellationToken cancellationToken = default(CancellationToken))
{
(await operations.DeleteOrderWithHttpMessagesAsync(orderId, null, cancellationToken).ConfigureAwait(false)).Dispose();
}
/// <summary>
/// Create user
/// </summary>
/// <remarks>
/// This can only be done by the logged in user.
/// </remarks>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='body'>
/// Created user object
/// </param>
public static void CreateUser(this ISwaggerPetstore operations, User body = default(User))
{
operations.CreateUserAsync(body).GetAwaiter().GetResult();
}
/// <summary>
/// Create user
/// </summary>
/// <remarks>
/// This can only be done by the logged in user.
/// </remarks>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='body'>
/// Created user object
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task CreateUserAsync(this ISwaggerPetstore operations, User body = default(User), CancellationToken cancellationToken = default(CancellationToken))
{
(await operations.CreateUserWithHttpMessagesAsync(body, null, cancellationToken).ConfigureAwait(false)).Dispose();
}
/// <summary>
/// Creates list of users with given input array
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='body'>
/// List of user object
/// </param>
public static void CreateUsersWithArrayInput(this ISwaggerPetstore operations, IList<User> body = default(IList<User>))
{
operations.CreateUsersWithArrayInputAsync(body).GetAwaiter().GetResult();
}
/// <summary>
/// Creates list of users with given input array
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='body'>
/// List of user object
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task CreateUsersWithArrayInputAsync(this ISwaggerPetstore operations, IList<User> body = default(IList<User>), CancellationToken cancellationToken = default(CancellationToken))
{
(await operations.CreateUsersWithArrayInputWithHttpMessagesAsync(body, null, cancellationToken).ConfigureAwait(false)).Dispose();
}
/// <summary>
/// Creates list of users with given input array
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='body'>
/// List of user object
/// </param>
public static void CreateUsersWithListInput(this ISwaggerPetstore operations, IList<User> body = default(IList<User>))
{
operations.CreateUsersWithListInputAsync(body).GetAwaiter().GetResult();
}
/// <summary>
/// Creates list of users with given input array
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='body'>
/// List of user object
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task CreateUsersWithListInputAsync(this ISwaggerPetstore operations, IList<User> body = default(IList<User>), CancellationToken cancellationToken = default(CancellationToken))
{
(await operations.CreateUsersWithListInputWithHttpMessagesAsync(body, null, cancellationToken).ConfigureAwait(false)).Dispose();
}
/// <summary>
/// Logs user into the system
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='username'>
/// The user name for login
/// </param>
/// <param name='password'>
/// The password for login in clear text
/// </param>
public static string LoginUser(this ISwaggerPetstore operations, string username = default(string), string password = default(string))
{
return operations.LoginUserAsync(username, password).GetAwaiter().GetResult();
}
/// <summary>
/// Logs user into the system
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='username'>
/// The user name for login
/// </param>
/// <param name='password'>
/// The password for login in clear text
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<string> LoginUserAsync(this ISwaggerPetstore operations, string username = default(string), string password = default(string), CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.LoginUserWithHttpMessagesAsync(username, password, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Logs out current logged in user session
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
public static void LogoutUser(this ISwaggerPetstore operations)
{
operations.LogoutUserAsync().GetAwaiter().GetResult();
}
/// <summary>
/// Logs out current logged in user session
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task LogoutUserAsync(this ISwaggerPetstore operations, CancellationToken cancellationToken = default(CancellationToken))
{
(await operations.LogoutUserWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false)).Dispose();
}
/// <summary>
/// Get user by user name
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='username'>
/// The name that needs to be fetched. Use user1 for testing.
/// </param>
public static User GetUserByName(this ISwaggerPetstore operations, string username)
{
return operations.GetUserByNameAsync(username).GetAwaiter().GetResult();
}
/// <summary>
/// Get user by user name
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='username'>
/// The name that needs to be fetched. Use user1 for testing.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<User> GetUserByNameAsync(this ISwaggerPetstore operations, string username, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetUserByNameWithHttpMessagesAsync(username, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Updated user
/// </summary>
/// <remarks>
/// This can only be done by the logged in user.
/// </remarks>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='username'>
/// name that need to be deleted
/// </param>
/// <param name='body'>
/// Updated user object
/// </param>
public static void UpdateUser(this ISwaggerPetstore operations, string username, User body = default(User))
{
operations.UpdateUserAsync(username, body).GetAwaiter().GetResult();
}
/// <summary>
/// Updated user
/// </summary>
/// <remarks>
/// This can only be done by the logged in user.
/// </remarks>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='username'>
/// name that need to be deleted
/// </param>
/// <param name='body'>
/// Updated user object
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task UpdateUserAsync(this ISwaggerPetstore operations, string username, User body = default(User), CancellationToken cancellationToken = default(CancellationToken))
{
(await operations.UpdateUserWithHttpMessagesAsync(username, body, null, cancellationToken).ConfigureAwait(false)).Dispose();
}
/// <summary>
/// Delete user
/// </summary>
/// <remarks>
/// This can only be done by the logged in user.
/// </remarks>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='username'>
/// The name that needs to be deleted
/// </param>
public static void DeleteUser(this ISwaggerPetstore operations, string username)
{
operations.DeleteUserAsync(username).GetAwaiter().GetResult();
}
/// <summary>
/// Delete user
/// </summary>
/// <remarks>
/// This can only be done by the logged in user.
/// </remarks>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='username'>
/// The name that needs to be deleted
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task DeleteUserAsync(this ISwaggerPetstore operations, string username, CancellationToken cancellationToken = default(CancellationToken))
{
(await operations.DeleteUserWithHttpMessagesAsync(username, null, cancellationToken).ConfigureAwait(false)).Dispose();
}
}
}
| |
/*==============================================================================
Copyright (c) 2012-2013 Qualcomm Austria Research Center GmbH.
All Rights Reserved.
==============================================================================*/
using System;
using UnityEngine;
/// <summary>
/// This Behaviour renders the video background from the camera in Unity.
/// </summary>
public class VideoTextureBehaviour : MonoBehaviour, IVideoBackgroundEventHandler
{
#region PUBLIC_MEMBER_VARIABLES
public Camera m_Camera = null;
public int m_NumDivisions = 2;
public event Action TextureChanged;
#endregion // PUBLIC_MEMBER_VARIABLES
#region PRIVATE_MEMBER_VARIABLES
private Texture2D mTexture = null;
private QCARRenderer.VideoTextureInfo mTextureInfo;
private ScreenOrientation mScreenOrientation;
private int mScreenWidth = 0;
private int mScreenHeight = 0;
bool mVideoBgConfigChanged = false;
#endregion // PRIVATE_MEMBER_VARIABLES
#region PUBLIC_METHODS
/// <summary>
/// Get the texture object containing the video
/// </summary>
public Texture GetTexture()
{
return mTexture;
}
/// <summary>
/// Get the scale of the image width inside the texture
/// </summary>
public float GetScaleFactorX()
{
return (float)mTextureInfo.imageSize.x / (float)mTextureInfo.textureSize.x;
}
/// <summary>
/// Get the scale of the image height inside the texture
/// </summary>
public float GetScaleFactorY()
{
return (float)mTextureInfo.imageSize.y / (float)mTextureInfo.textureSize.y;
}
#endregion // PUBLIC_METHODS
#region UNITY_MONOBEHAVIOUR_METHODS
void Start()
{
// register for the OnVideoBackgroundConfigChanged event at the QCARBehaviour
QCARBehaviour qcarBehaviour = (QCARBehaviour)FindObjectOfType(typeof(QCARBehaviour));
if (qcarBehaviour)
{
qcarBehaviour.RegisterVideoBgEventHandler(this);
}
// Use the main camera if one wasn't set in the Inspector
if (m_Camera == null)
{
m_Camera = Camera.main;
}
// Ask the renderer to stop drawing the videobackground.
QCARRenderer.Instance.DrawVideoBackground = false;
}
void Update()
{
if (mVideoBgConfigChanged && QCARRenderer.Instance.IsVideoBackgroundInfoAvailable())
{
// reset the video texture:
if (mTexture != null)
Destroy(mTexture);
CreateAndSetVideoTexture();
QCARRenderer.VideoTextureInfo texInfo = QCARRenderer.Instance.GetVideoTextureInfo();
// Cache the info:
mTextureInfo = QCARRenderer.Instance.GetVideoTextureInfo(); ;
// Debug.Log("VideoTextureInfo " + texInfo.textureSize.x + " " +
// texInfo.textureSize.y + " " + texInfo.imageSize.x + " " + texInfo.imageSize.y);
// Create the video mesh
MeshFilter meshFilter = GetComponent<MeshFilter>();
if (meshFilter == null)
{
meshFilter = gameObject.AddComponent<MeshFilter>();
}
meshFilter.mesh = CreateVideoMesh(m_NumDivisions, m_NumDivisions);
// Position the video mesh
PositionVideoMesh();
if (TextureChanged != null)
TextureChanged();
mVideoBgConfigChanged = false;
}
}
void OnDestroy()
{
// unregister for the OnVideoBackgroundConfigChanged event at the QCARBehaviour
QCARBehaviour qcarBehaviour = (QCARBehaviour)FindObjectOfType(typeof(QCARBehaviour));
if (qcarBehaviour)
{
qcarBehaviour.UnregisterVideoBgEventHandler(this);
}
// Revert to default video background rendering
QCARRenderer.Instance.DrawVideoBackground = true;
// remove texture pointer
QCARRenderer.Instance.SetVideoBackgroundTexture(null);
}
#endregion // UNITY_MONOBEHAVIOUR_METHODS
#region PRIVATE_METHODS
/// <summary>
/// This creates an emtpy texture and passes its texture id to native so that the video background can be rendered into it.
/// </summary>
private void CreateAndSetVideoTexture()
{
// Create texture of size 0 that will be updated in the plugin (we allocate buffers in native code)
mTexture = new Texture2D(0, 0, TextureFormat.RGB565, false);
mTexture.filterMode = FilterMode.Bilinear;
mTexture.wrapMode = TextureWrapMode.Clamp;
// Assign texture to the renderer
renderer.material.mainTexture = mTexture;
// Set the texture to render into:
if (!QCARRenderer.Instance.SetVideoBackgroundTexture(mTexture))
{
Debug.Log("Failed to setVideoBackgroundTexture " + mTexture.GetNativeTextureID());
}
else
{
Debug.Log("Successfully setVideoBackgroundTexture " + +mTexture.GetNativeTextureID());
}
}
// Create a video mesh with the given number of rows and columns
// Minimum two rows and two columns
private Mesh CreateVideoMesh(int numRows, int numCols)
{
Mesh mesh = new Mesh();
// Build mesh:
mesh.vertices = new Vector3[numRows * numCols];
Vector3[] vertices = mesh.vertices;
for (int r = 0; r < numRows; ++r)
{
for (int c = 0; c < numCols; ++c)
{
float x = (((float)c) / (float)(numCols - 1)) - 0.5F;
float z = (1.0F - ((float)r) / (float)(numRows - 1)) - 0.5F;
vertices[r * numCols + c].x = x * 2.0F;
vertices[r * numCols + c].y = 0.0F;
vertices[r * numCols + c].z = z * 2.0F;
}
}
mesh.vertices = vertices;
// Builds triangles:
mesh.triangles = new int[numRows * numCols * 2 * 3];
int triangleIndex = 0;
// Setup UVs to match texture info:
float scaleFactorX = (float)mTextureInfo.imageSize.x / (float)mTextureInfo.textureSize.x;
float scaleFactorY = (float)mTextureInfo.imageSize.y / (float)mTextureInfo.textureSize.y;
mesh.uv = new Vector2[numRows * numCols];
int[] triangles = mesh.triangles;
Vector2[] uvs = mesh.uv;
QCARBehaviour qcarBehaviour = (QCARBehaviour)FindObjectOfType(typeof(QCARBehaviour));
for (int r = 0; r < numRows - 1; ++r)
{
for (int c = 0; c < numCols - 1; ++c)
{
// p0-p3
// |\ |
// p2-p1
int p0Index = r * numCols + c;
int p1Index = r * numCols + c + numCols + 1;
int p2Index = r * numCols + c + numCols;
int p3Index = r * numCols + c + 1;
triangles[triangleIndex++] = p0Index;
triangles[triangleIndex++] = p1Index;
triangles[triangleIndex++] = p2Index;
triangles[triangleIndex++] = p1Index;
triangles[triangleIndex++] = p0Index;
triangles[triangleIndex++] = p3Index;
uvs[p0Index] = new Vector2(((float)c) / ((float)(numCols - 1)) * scaleFactorX,
((float)r) / ((float)(numRows - 1)) * scaleFactorY);
uvs[p1Index] = new Vector2(((float)(c + 1)) / ((float)(numCols - 1)) * scaleFactorX,
((float)(r + 1)) / ((float)(numRows - 1)) * scaleFactorY);
uvs[p2Index] = new Vector2(((float)c) / ((float)(numCols - 1)) * scaleFactorX,
((float)(r + 1)) / ((float)(numRows - 1)) * scaleFactorY);
uvs[p3Index] = new Vector2(((float)(c + 1)) / ((float)(numCols - 1)) * scaleFactorX,
((float)r) / ((float)(numRows - 1)) * scaleFactorY);
// mirror UV coordinates if necessary
if (qcarBehaviour.VideoBackGroundMirrored)
{
uvs[p0Index] = new Vector2(scaleFactorX - uvs[p0Index].x, uvs[p0Index].y);
uvs[p1Index] = new Vector2(scaleFactorX - uvs[p1Index].x, uvs[p1Index].y);
uvs[p2Index] = new Vector2(scaleFactorX - uvs[p2Index].x, uvs[p2Index].y);
uvs[p3Index] = new Vector2(scaleFactorX - uvs[p3Index].x, uvs[p3Index].y);
}
}
}
mesh.triangles = triangles;
mesh.uv = uvs;
mesh.normals = new Vector3[mesh.vertices.Length];
mesh.RecalculateNormals();
return mesh;
}
// Scale and position the video mesh to fill the screen
private void PositionVideoMesh()
{
// Cache the screen orientation and size
mScreenOrientation = QCARRuntimeUtilities.ScreenOrientation;
mScreenWidth = Screen.width;
mScreenHeight = Screen.height;
// Reset the rotation so the mesh faces the camera
gameObject.transform.localRotation = Quaternion.AngleAxis(270.0f, Vector3.right);
// Adjust the rotation for the current orientation
if (mScreenOrientation == ScreenOrientation.Landscape)
{
gameObject.transform.localRotation *= Quaternion.identity;
}
else if (mScreenOrientation == ScreenOrientation.Portrait)
{
gameObject.transform.localRotation *= Quaternion.AngleAxis(90.0f, Vector3.up);
}
else if (mScreenOrientation == ScreenOrientation.LandscapeRight)
{
gameObject.transform.localRotation *= Quaternion.AngleAxis(180.0f, Vector3.up);
}
else if (mScreenOrientation == ScreenOrientation.PortraitUpsideDown)
{
gameObject.transform.localRotation *= Quaternion.AngleAxis(270.0f, Vector3.up);
}
// Scale game object for full screen video image:
// gameObject.transform.localScale = new Vector3(1, 1, 1 * (float)mTextureInfo.imageSize.y / (float)mTextureInfo.imageSize.x);
// Set the scale of the orthographic camera to match the screen size:
m_Camera.orthographic = true;
// Visible portion of the image:
float visibleHeight;
if (ShouldFitWidth())
{
// should fit width is true, so we have to adjust the horizontal autographic size so that
// the viewport covers the whole texture WIDTH.
if (QCARRuntimeUtilities.IsPortraitOrientation)
{
// in portrait mode, the background is rotated by 90 degrees. It's actual height is
// therefore 1, so we have to set the visible height so that the visible width results in 1.
visibleHeight = (mTextureInfo.imageSize.y / (float)mTextureInfo.imageSize.x) *
((float)mScreenHeight / (float)mScreenWidth);
}
else
{
// in landscape mode, we have to set the visible height to the screen ratio to
// end up with a visible width of 1.
visibleHeight = (float)mScreenHeight / (float)mScreenWidth;
}
}
else
{
// should fit width is true, so we have to adjust the horizontal autographic size so that
// the viewport covers the whole texture HEIGHT.
if (QCARRuntimeUtilities.IsPortraitOrientation)
{
// in portrait mode, texture height is 1
visibleHeight = 1.0f;
}
else
{
// in landscape mode, the texture height will be this value (see above)
visibleHeight = mTextureInfo.imageSize.y / (float)mTextureInfo.imageSize.x;
}
}
// m_Camera.orthographicSize = 1/visibleHeight;
}
// Returns true if the video mesh should be scaled to match the width of the screen
// Returns false if the video mesh should be scaled to match the height of the screen
private bool ShouldFitWidth()
{
float screenAspect = mScreenWidth / (float)mScreenHeight;
float cameraAspect;
if (QCARRuntimeUtilities.IsPortraitOrientation)
cameraAspect = mTextureInfo.imageSize.y / (float)mTextureInfo.imageSize.x;
else
cameraAspect = mTextureInfo.imageSize.x / (float)mTextureInfo.imageSize.y;
return (screenAspect >= cameraAspect);
}
#endregion // PRIVATE_METHODS
#region IVideoBackgroundEventHandler_IMPLEMENTATION
/// <summary>
/// reset the video background
/// </summary>
public void OnVideoBackgroundConfigChanged()
{
mVideoBgConfigChanged = true;
}
#endregion // IVideoBackgroundEventHandler_IMPLEMENTATION
}
| |
using Discord.API.Rest;
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using Model = Discord.API.Message;
using UserModel = Discord.API.User;
namespace Discord.Rest
{
internal static class MessageHelper
{
/// <summary>
/// Regex used to check if some text is formatted as inline code.
/// </summary>
private static readonly Regex InlineCodeRegex = new Regex(@"[^\\]?(`).+?[^\\](`)", RegexOptions.Compiled | RegexOptions.Multiline | RegexOptions.Singleline);
/// <summary>
/// Regex used to check if some text is formatted as a code block.
/// </summary>
private static readonly Regex BlockCodeRegex = new Regex(@"[^\\]?(```).+?[^\\](```)", RegexOptions.Compiled | RegexOptions.Multiline | RegexOptions.Singleline);
/// <exception cref="InvalidOperationException">Only the author of a message may modify the message.</exception>
/// <exception cref="ArgumentOutOfRangeException">Message content is too long, length must be less or equal to <see cref="DiscordConfig.MaxMessageSize"/>.</exception>
public static async Task<Model> ModifyAsync(IMessage msg, BaseDiscordClient client, Action<MessageProperties> func,
RequestOptions options)
{
var args = new MessageProperties();
func(args);
if (msg.Author.Id != client.CurrentUser.Id && (args.Content.IsSpecified || args.Embed.IsSpecified || args.AllowedMentions.IsSpecified))
throw new InvalidOperationException("Only the author of a message may modify the message content, embed, or allowed mentions.");
bool hasText = args.Content.IsSpecified ? !string.IsNullOrEmpty(args.Content.Value) : !string.IsNullOrEmpty(msg.Content);
bool hasEmbed = args.Embed.IsSpecified ? args.Embed.Value != null : msg.Embeds.Any();
if (!hasText && !hasEmbed)
Preconditions.NotNullOrEmpty(args.Content.IsSpecified ? args.Content.Value : string.Empty, nameof(args.Content));
if (args.AllowedMentions.IsSpecified)
{
AllowedMentions allowedMentions = args.AllowedMentions.Value;
Preconditions.AtMost(allowedMentions?.RoleIds?.Count ?? 0, 100, nameof(allowedMentions.RoleIds), "A max of 100 role Ids are allowed.");
Preconditions.AtMost(allowedMentions?.UserIds?.Count ?? 0, 100, nameof(allowedMentions.UserIds), "A max of 100 user Ids are allowed.");
// check that user flag and user Id list are exclusive, same with role flag and role Id list
if (allowedMentions != null && allowedMentions.AllowedTypes.HasValue)
{
if (allowedMentions.AllowedTypes.Value.HasFlag(AllowedMentionTypes.Users) &&
allowedMentions.UserIds != null && allowedMentions.UserIds.Count > 0)
{
throw new ArgumentException("The Users flag is mutually exclusive with the list of User Ids.", nameof(allowedMentions));
}
if (allowedMentions.AllowedTypes.Value.HasFlag(AllowedMentionTypes.Roles) &&
allowedMentions.RoleIds != null && allowedMentions.RoleIds.Count > 0)
{
throw new ArgumentException("The Roles flag is mutually exclusive with the list of Role Ids.", nameof(allowedMentions));
}
}
}
var apiArgs = new API.Rest.ModifyMessageParams
{
Content = args.Content,
Embed = args.Embed.IsSpecified ? args.Embed.Value.ToModel() : Optional.Create<API.Embed>(),
Flags = args.Flags.IsSpecified ? args.Flags.Value : Optional.Create<MessageFlags?>(),
AllowedMentions = args.AllowedMentions.IsSpecified ? args.AllowedMentions.Value.ToModel() : Optional.Create<API.AllowedMentions>(),
};
return await client.ApiClient.ModifyMessageAsync(msg.Channel.Id, msg.Id, apiArgs, options).ConfigureAwait(false);
}
public static Task DeleteAsync(IMessage msg, BaseDiscordClient client, RequestOptions options)
=> DeleteAsync(msg.Channel.Id, msg.Id, client, options);
public static async Task DeleteAsync(ulong channelId, ulong msgId, BaseDiscordClient client,
RequestOptions options)
{
await client.ApiClient.DeleteMessageAsync(channelId, msgId, options).ConfigureAwait(false);
}
public static async Task SuppressEmbedsAsync(IMessage msg, BaseDiscordClient client, bool suppress, RequestOptions options)
{
var apiArgs = new API.Rest.SuppressEmbedParams
{
Suppressed = suppress
};
await client.ApiClient.SuppressEmbedAsync(msg.Channel.Id, msg.Id, apiArgs, options).ConfigureAwait(false);
}
public static async Task AddReactionAsync(IMessage msg, IEmote emote, BaseDiscordClient client, RequestOptions options)
{
await client.ApiClient.AddReactionAsync(msg.Channel.Id, msg.Id, emote is Emote e ? $"{e.Name}:{e.Id}" : UrlEncode(emote.Name), options).ConfigureAwait(false);
}
public static async Task RemoveReactionAsync(IMessage msg, ulong userId, IEmote emote, BaseDiscordClient client, RequestOptions options)
{
await client.ApiClient.RemoveReactionAsync(msg.Channel.Id, msg.Id, userId, emote is Emote e ? $"{e.Name}:{e.Id}" : UrlEncode(emote.Name), options).ConfigureAwait(false);
}
public static async Task RemoveAllReactionsAsync(IMessage msg, BaseDiscordClient client, RequestOptions options)
{
await client.ApiClient.RemoveAllReactionsAsync(msg.Channel.Id, msg.Id, options).ConfigureAwait(false);
}
public static async Task RemoveAllReactionsForEmoteAsync(IMessage msg, IEmote emote, BaseDiscordClient client, RequestOptions options)
{
await client.ApiClient.RemoveAllReactionsForEmoteAsync(msg.Channel.Id, msg.Id, emote is Emote e ? $"{e.Name}:{e.Id}" : UrlEncode(emote.Name), options).ConfigureAwait(false);
}
public static IAsyncEnumerable<IReadOnlyCollection<IUser>> GetReactionUsersAsync(IMessage msg, IEmote emote,
int? limit, BaseDiscordClient client, RequestOptions options)
{
Preconditions.NotNull(emote, nameof(emote));
var emoji = (emote is Emote e ? $"{e.Name}:{e.Id}" : UrlEncode(emote.Name));
return new PagedAsyncEnumerable<IUser>(
DiscordConfig.MaxUserReactionsPerBatch,
async (info, ct) =>
{
var args = new GetReactionUsersParams
{
Limit = info.PageSize
};
if (info.Position != null)
args.AfterUserId = info.Position.Value;
var models = await client.ApiClient.GetReactionUsersAsync(msg.Channel.Id, msg.Id, emoji, args, options).ConfigureAwait(false);
return models.Select(x => RestUser.Create(client, x)).ToImmutableArray();
},
nextPage: (info, lastPage) =>
{
if (lastPage.Count != DiscordConfig.MaxUserReactionsPerBatch)
return false;
info.Position = lastPage.Max(x => x.Id);
return true;
},
count: limit
);
}
private static string UrlEncode(string text)
{
#if NET461
return System.Net.WebUtility.UrlEncode(text);
#else
return System.Web.HttpUtility.UrlEncode(text);
#endif
}
public static async Task PinAsync(IMessage msg, BaseDiscordClient client,
RequestOptions options)
{
await client.ApiClient.AddPinAsync(msg.Channel.Id, msg.Id, options).ConfigureAwait(false);
}
public static async Task UnpinAsync(IMessage msg, BaseDiscordClient client,
RequestOptions options)
{
await client.ApiClient.RemovePinAsync(msg.Channel.Id, msg.Id, options).ConfigureAwait(false);
}
public static ImmutableArray<ITag> ParseTags(string text, IMessageChannel channel, IGuild guild, IReadOnlyCollection<IUser> userMentions)
{
var tags = ImmutableArray.CreateBuilder<ITag>();
int index = 0;
var codeIndex = 0;
// checks if the tag being parsed is wrapped in code blocks
bool CheckWrappedCode()
{
// util to check if the index of a tag is within the bounds of the codeblock
bool EnclosedInBlock(Match m)
=> m.Groups[1].Index < index && index < m.Groups[2].Index;
// loop through all code blocks that are before the start of the tag
while (codeIndex < index)
{
var blockMatch = BlockCodeRegex.Match(text, codeIndex);
if (blockMatch.Success)
{
if (EnclosedInBlock(blockMatch))
return true;
// continue if the end of the current code was before the start of the tag
codeIndex += blockMatch.Groups[2].Index + blockMatch.Groups[2].Length;
if (codeIndex < index)
continue;
return false;
}
var inlineMatch = InlineCodeRegex.Match(text, codeIndex);
if (inlineMatch.Success)
{
if (EnclosedInBlock(inlineMatch))
return true;
// continue if the end of the current code was before the start of the tag
codeIndex += inlineMatch.Groups[2].Index + inlineMatch.Groups[2].Length;
if (codeIndex < index)
continue;
return false;
}
return false;
}
return false;
}
while (true)
{
index = text.IndexOf('<', index);
if (index == -1) break;
int endIndex = text.IndexOf('>', index + 1);
if (endIndex == -1) break;
if (CheckWrappedCode()) break;
string content = text.Substring(index, endIndex - index + 1);
if (MentionUtils.TryParseUser(content, out ulong id))
{
IUser mentionedUser = null;
foreach (var mention in userMentions)
{
if (mention.Id == id)
{
mentionedUser = channel?.GetUserAsync(id, CacheMode.CacheOnly).GetAwaiter().GetResult();
if (mentionedUser == null)
mentionedUser = mention;
break;
}
}
tags.Add(new Tag<IUser>(TagType.UserMention, index, content.Length, id, mentionedUser));
}
else if (MentionUtils.TryParseChannel(content, out id))
{
IChannel mentionedChannel = null;
if (guild != null)
mentionedChannel = guild.GetChannelAsync(id, CacheMode.CacheOnly).GetAwaiter().GetResult();
tags.Add(new Tag<IChannel>(TagType.ChannelMention, index, content.Length, id, mentionedChannel));
}
else if (MentionUtils.TryParseRole(content, out id))
{
IRole mentionedRole = null;
if (guild != null)
mentionedRole = guild.GetRole(id);
tags.Add(new Tag<IRole>(TagType.RoleMention, index, content.Length, id, mentionedRole));
}
else if (Emote.TryParse(content, out var emoji))
tags.Add(new Tag<Emote>(TagType.Emoji, index, content.Length, emoji.Id, emoji));
else //Bad Tag
{
index = index + 1;
continue;
}
index = endIndex + 1;
}
index = 0;
codeIndex = 0;
while (true)
{
index = text.IndexOf("@everyone", index);
if (index == -1) break;
if (CheckWrappedCode()) break;
var tagIndex = FindIndex(tags, index);
if (tagIndex.HasValue)
tags.Insert(tagIndex.Value, new Tag<IRole>(TagType.EveryoneMention, index, "@everyone".Length, 0, guild?.EveryoneRole));
index++;
}
index = 0;
codeIndex = 0;
while (true)
{
index = text.IndexOf("@here", index);
if (index == -1) break;
if (CheckWrappedCode()) break;
var tagIndex = FindIndex(tags, index);
if (tagIndex.HasValue)
tags.Insert(tagIndex.Value, new Tag<IRole>(TagType.HereMention, index, "@here".Length, 0, guild?.EveryoneRole));
index++;
}
return tags.ToImmutable();
}
private static int? FindIndex(IReadOnlyList<ITag> tags, int index)
{
int i = 0;
for (; i < tags.Count; i++)
{
var tag = tags[i];
if (index < tag.Index)
break; //Position before this tag
}
if (i > 0 && index < tags[i - 1].Index + tags[i - 1].Length)
return null; //Overlaps tag before this
return i;
}
public static ImmutableArray<ulong> FilterTagsByKey(TagType type, ImmutableArray<ITag> tags)
{
return tags
.Where(x => x.Type == type)
.Select(x => x.Key)
.ToImmutableArray();
}
public static ImmutableArray<T> FilterTagsByValue<T>(TagType type, ImmutableArray<ITag> tags)
{
return tags
.Where(x => x.Type == type)
.Select(x => (T)x.Value)
.Where(x => x != null)
.ToImmutableArray();
}
public static MessageSource GetSource(Model msg)
{
if (msg.Type != MessageType.Default && msg.Type != MessageType.Reply)
return MessageSource.System;
else if (msg.WebhookId.IsSpecified)
return MessageSource.Webhook;
else if (msg.Author.GetValueOrDefault()?.Bot.GetValueOrDefault(false) == true)
return MessageSource.Bot;
return MessageSource.User;
}
public static Task CrosspostAsync(IMessage msg, BaseDiscordClient client, RequestOptions options)
=> CrosspostAsync(msg.Channel.Id, msg.Id, client, options);
public static async Task CrosspostAsync(ulong channelId, ulong msgId, BaseDiscordClient client,
RequestOptions options)
{
await client.ApiClient.CrosspostAsync(channelId, msgId, options).ConfigureAwait(false);
}
public static IUser GetAuthor(BaseDiscordClient client, IGuild guild, UserModel model, ulong? webhookId)
{
IUser author = null;
if (guild != null)
author = guild.GetUserAsync(model.Id, CacheMode.CacheOnly).Result;
if (author == null)
author = RestUser.Create(client, guild, model, webhookId);
return author;
}
}
}
| |
using Lucene.Net.Documents;
using Lucene.Net.Index.Extensions;
using NUnit.Framework;
using System.Collections.Generic;
using JCG = J2N.Collections.Generic;
using Assert = Lucene.Net.TestFramework.Assert;
namespace Lucene.Net.Search.Spans
{
/*
* 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 Directory = Lucene.Net.Store.Directory;
using Document = Documents.Document;
using Field = Field;
using IndexReader = Lucene.Net.Index.IndexReader;
using LuceneTestCase = Lucene.Net.Util.LuceneTestCase;
using MockAnalyzer = Lucene.Net.Analysis.MockAnalyzer;
using RandomIndexWriter = Lucene.Net.Index.RandomIndexWriter;
using Term = Lucene.Net.Index.Term;
using TFIDFSimilarity = Lucene.Net.Search.Similarities.TFIDFSimilarity;
[TestFixture]
public class TestFieldMaskingSpanQuery : LuceneTestCase
{
protected internal static Document Doc(Field[] fields)
{
Document doc = new Document();
for (int i = 0; i < fields.Length; i++)
{
doc.Add(fields[i]);
}
return doc;
}
protected internal Field GetField(string name, string value)
{
return NewTextField(name, value, Field.Store.NO);
}
protected internal static IndexSearcher searcher;
protected internal static Directory directory;
protected internal static IndexReader reader;
/// <summary>
/// LUCENENET specific
/// Is non-static because NewIndexWriterConfig is no longer static.
/// </summary>
[OneTimeSetUp]
public override void BeforeClass()
{
base.BeforeClass();
directory = NewDirectory();
RandomIndexWriter writer = new RandomIndexWriter(Random, directory, NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random)).SetMergePolicy(NewLogMergePolicy()));
writer.AddDocument(Doc(new Field[] { GetField("id", "0"), GetField("gender", "male"), GetField("first", "james"), GetField("last", "jones") }));
writer.AddDocument(Doc(new Field[] { GetField("id", "1"), GetField("gender", "male"), GetField("first", "james"), GetField("last", "smith"), GetField("gender", "female"), GetField("first", "sally"), GetField("last", "jones") }));
writer.AddDocument(Doc(new Field[] { GetField("id", "2"), GetField("gender", "female"), GetField("first", "greta"), GetField("last", "jones"), GetField("gender", "female"), GetField("first", "sally"), GetField("last", "smith"), GetField("gender", "male"), GetField("first", "james"), GetField("last", "jones") }));
writer.AddDocument(Doc(new Field[] { GetField("id", "3"), GetField("gender", "female"), GetField("first", "lisa"), GetField("last", "jones"), GetField("gender", "male"), GetField("first", "bob"), GetField("last", "costas") }));
writer.AddDocument(Doc(new Field[] { GetField("id", "4"), GetField("gender", "female"), GetField("first", "sally"), GetField("last", "smith"), GetField("gender", "female"), GetField("first", "linda"), GetField("last", "dixit"), GetField("gender", "male"), GetField("first", "bubba"), GetField("last", "jones") }));
reader = writer.GetReader();
writer.Dispose();
searcher = NewSearcher(reader);
}
[OneTimeTearDown]
public override void AfterClass()
{
searcher = null;
reader.Dispose();
reader = null;
directory.Dispose();
directory = null;
base.AfterClass();
}
protected internal virtual void Check(SpanQuery q, int[] docs)
{
CheckHits.CheckHitCollector(
#if FEATURE_INSTANCE_TESTDATA_INITIALIZATION
this,
#endif
Random, q, null, searcher, docs);
}
[Test]
public virtual void TestRewrite0()
{
SpanQuery q = new FieldMaskingSpanQuery(new SpanTermQuery(new Term("last", "sally")), "first");
q.Boost = 8.7654321f;
SpanQuery qr = (SpanQuery)searcher.Rewrite(q);
QueryUtils.CheckEqual(q, qr);
ISet<Term> terms = new JCG.HashSet<Term>();
qr.ExtractTerms(terms);
Assert.AreEqual(1, terms.Count);
}
[Test]
public virtual void TestRewrite1()
{
// mask an anon SpanQuery class that rewrites to something else.
SpanQuery q = new FieldMaskingSpanQuery(new SpanTermQueryAnonymousInnerClassHelper(this, new Term("last", "sally")), "first");
SpanQuery qr = (SpanQuery)searcher.Rewrite(q);
QueryUtils.CheckUnequal(q, qr);
ISet<Term> terms = new JCG.HashSet<Term>();
qr.ExtractTerms(terms);
Assert.AreEqual(2, terms.Count);
}
private class SpanTermQueryAnonymousInnerClassHelper : SpanTermQuery
{
private readonly TestFieldMaskingSpanQuery outerInstance;
public SpanTermQueryAnonymousInnerClassHelper(TestFieldMaskingSpanQuery outerInstance, Term term)
: base(term)
{
this.outerInstance = outerInstance;
}
public override Query Rewrite(IndexReader reader)
{
return new SpanOrQuery(new SpanTermQuery(new Term("first", "sally")), new SpanTermQuery(new Term("first", "james")));
}
}
[Test]
public virtual void TestRewrite2()
{
SpanQuery q1 = new SpanTermQuery(new Term("last", "smith"));
SpanQuery q2 = new SpanTermQuery(new Term("last", "jones"));
SpanQuery q = new SpanNearQuery(new SpanQuery[] { q1, new FieldMaskingSpanQuery(q2, "last") }, 1, true);
Query qr = searcher.Rewrite(q);
QueryUtils.CheckEqual(q, qr);
ISet<Term> set = new JCG.HashSet<Term>();
qr.ExtractTerms(set);
Assert.AreEqual(2, set.Count);
}
[Test]
public virtual void TestEquality1()
{
SpanQuery q1 = new FieldMaskingSpanQuery(new SpanTermQuery(new Term("last", "sally")), "first");
SpanQuery q2 = new FieldMaskingSpanQuery(new SpanTermQuery(new Term("last", "sally")), "first");
SpanQuery q3 = new FieldMaskingSpanQuery(new SpanTermQuery(new Term("last", "sally")), "XXXXX");
SpanQuery q4 = new FieldMaskingSpanQuery(new SpanTermQuery(new Term("last", "XXXXX")), "first");
SpanQuery q5 = new FieldMaskingSpanQuery(new SpanTermQuery(new Term("xXXX", "sally")), "first");
QueryUtils.CheckEqual(q1, q2);
QueryUtils.CheckUnequal(q1, q3);
QueryUtils.CheckUnequal(q1, q4);
QueryUtils.CheckUnequal(q1, q5);
SpanQuery qA = new FieldMaskingSpanQuery(new SpanTermQuery(new Term("last", "sally")), "first");
qA.Boost = 9f;
SpanQuery qB = new FieldMaskingSpanQuery(new SpanTermQuery(new Term("last", "sally")), "first");
QueryUtils.CheckUnequal(qA, qB);
qB.Boost = 9f;
QueryUtils.CheckEqual(qA, qB);
}
[Test]
public virtual void TestNoop0()
{
SpanQuery q1 = new SpanTermQuery(new Term("last", "sally"));
SpanQuery q = new FieldMaskingSpanQuery(q1, "first");
Check(q, new int[] { }); // :EMPTY:
}
[Test]
public virtual void TestNoop1()
{
SpanQuery q1 = new SpanTermQuery(new Term("last", "smith"));
SpanQuery q2 = new SpanTermQuery(new Term("last", "jones"));
SpanQuery q = new SpanNearQuery(new SpanQuery[] { q1, new FieldMaskingSpanQuery(q2, "last") }, 0, true);
Check(q, new int[] { 1, 2 });
q = new SpanNearQuery(new SpanQuery[] { new FieldMaskingSpanQuery(q1, "last"), new FieldMaskingSpanQuery(q2, "last") }, 0, true);
Check(q, new int[] { 1, 2 });
}
[Test]
public virtual void TestSimple1()
{
SpanQuery q1 = new SpanTermQuery(new Term("first", "james"));
SpanQuery q2 = new SpanTermQuery(new Term("last", "jones"));
SpanQuery q = new SpanNearQuery(new SpanQuery[] { q1, new FieldMaskingSpanQuery(q2, "first") }, -1, false);
Check(q, new int[] { 0, 2 });
q = new SpanNearQuery(new SpanQuery[] { new FieldMaskingSpanQuery(q2, "first"), q1 }, -1, false);
Check(q, new int[] { 0, 2 });
q = new SpanNearQuery(new SpanQuery[] { q2, new FieldMaskingSpanQuery(q1, "last") }, -1, false);
Check(q, new int[] { 0, 2 });
q = new SpanNearQuery(new SpanQuery[] { new FieldMaskingSpanQuery(q1, "last"), q2 }, -1, false);
Check(q, new int[] { 0, 2 });
}
[Test]
public virtual void TestSimple2()
{
AssumeTrue("Broken scoring: LUCENE-3723", searcher.Similarity is TFIDFSimilarity);
SpanQuery q1 = new SpanTermQuery(new Term("gender", "female"));
SpanQuery q2 = new SpanTermQuery(new Term("last", "smith"));
SpanQuery q = new SpanNearQuery(new SpanQuery[] { q1, new FieldMaskingSpanQuery(q2, "gender") }, -1, false);
Check(q, new int[] { 2, 4 });
q = new SpanNearQuery(new SpanQuery[] { new FieldMaskingSpanQuery(q1, "id"), new FieldMaskingSpanQuery(q2, "id") }, -1, false);
Check(q, new int[] { 2, 4 });
}
[Test]
public virtual void TestSpans0()
{
SpanQuery q1 = new SpanTermQuery(new Term("gender", "female"));
SpanQuery q2 = new SpanTermQuery(new Term("first", "james"));
SpanQuery q = new SpanOrQuery(q1, new FieldMaskingSpanQuery(q2, "gender"));
Check(q, new int[] { 0, 1, 2, 3, 4 });
Spans span = MultiSpansWrapper.Wrap(searcher.TopReaderContext, q);
Assert.AreEqual(true, span.MoveNext());
Assert.AreEqual(s(0, 0, 1), s(span));
Assert.AreEqual(true, span.MoveNext());
Assert.AreEqual(s(1, 0, 1), s(span));
Assert.AreEqual(true, span.MoveNext());
Assert.AreEqual(s(1, 1, 2), s(span));
Assert.AreEqual(true, span.MoveNext());
Assert.AreEqual(s(2, 0, 1), s(span));
Assert.AreEqual(true, span.MoveNext());
Assert.AreEqual(s(2, 1, 2), s(span));
Assert.AreEqual(true, span.MoveNext());
Assert.AreEqual(s(2, 2, 3), s(span));
Assert.AreEqual(true, span.MoveNext());
Assert.AreEqual(s(3, 0, 1), s(span));
Assert.AreEqual(true, span.MoveNext());
Assert.AreEqual(s(4, 0, 1), s(span));
Assert.AreEqual(true, span.MoveNext());
Assert.AreEqual(s(4, 1, 2), s(span));
Assert.AreEqual(false, span.MoveNext());
}
[Test]
public virtual void TestSpans1()
{
SpanQuery q1 = new SpanTermQuery(new Term("first", "sally"));
SpanQuery q2 = new SpanTermQuery(new Term("first", "james"));
SpanQuery qA = new SpanOrQuery(q1, q2);
SpanQuery qB = new FieldMaskingSpanQuery(qA, "id");
Check(qA, new int[] { 0, 1, 2, 4 });
Check(qB, new int[] { 0, 1, 2, 4 });
Spans spanA = MultiSpansWrapper.Wrap(searcher.TopReaderContext, qA);
Spans spanB = MultiSpansWrapper.Wrap(searcher.TopReaderContext, qB);
while (spanA.MoveNext())
{
Assert.IsTrue(spanB.MoveNext(), "spanB not still going");
Assert.AreEqual(s(spanA), s(spanB), "spanA not equal spanB");
}
Assert.IsTrue(!(spanB.MoveNext()), "spanB still going even tough spanA is done");
}
[Test]
public virtual void TestSpans2()
{
AssumeTrue("Broken scoring: LUCENE-3723", searcher.Similarity is TFIDFSimilarity);
SpanQuery qA1 = new SpanTermQuery(new Term("gender", "female"));
SpanQuery qA2 = new SpanTermQuery(new Term("first", "james"));
SpanQuery qA = new SpanOrQuery(qA1, new FieldMaskingSpanQuery(qA2, "gender"));
SpanQuery qB = new SpanTermQuery(new Term("last", "jones"));
SpanQuery q = new SpanNearQuery(new SpanQuery[] { new FieldMaskingSpanQuery(qA, "id"), new FieldMaskingSpanQuery(qB, "id") }, -1, false);
Check(q, new int[] { 0, 1, 2, 3 });
Spans span = MultiSpansWrapper.Wrap(searcher.TopReaderContext, q);
Assert.AreEqual(true, span.MoveNext());
Assert.AreEqual(s(0, 0, 1), s(span));
Assert.AreEqual(true, span.MoveNext());
Assert.AreEqual(s(1, 1, 2), s(span));
Assert.AreEqual(true, span.MoveNext());
Assert.AreEqual(s(2, 0, 1), s(span));
Assert.AreEqual(true, span.MoveNext());
Assert.AreEqual(s(2, 2, 3), s(span));
Assert.AreEqual(true, span.MoveNext());
Assert.AreEqual(s(3, 0, 1), s(span));
Assert.AreEqual(false, span.MoveNext());
}
public virtual string s(Spans span)
{
return s(span.Doc, span.Start, span.End);
}
public virtual string s(int doc, int start, int end)
{
return "s(" + doc + "," + start + "," + end + ")";
}
}
}
| |
using Microsoft.IdentityModel;
using Microsoft.IdentityModel.S2S.Protocols.OAuth2;
using Microsoft.IdentityModel.S2S.Tokens;
using Microsoft.SharePoint.Client;
using Microsoft.SharePoint.Client.EventReceivers;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Globalization;
using System.IdentityModel.Selectors;
using System.IdentityModel.Tokens;
using System.IO;
using System.Linq;
using System.Net;
using System.Security.Cryptography.X509Certificates;
using System.Security.Principal;
using System.ServiceModel;
using System.Text;
using System.Web;
using System.Web.Configuration;
using System.Web.Script.Serialization;
using AudienceRestriction = Microsoft.IdentityModel.Tokens.AudienceRestriction;
using AudienceUriValidationFailedException = Microsoft.IdentityModel.Tokens.AudienceUriValidationFailedException;
using SecurityTokenHandlerConfiguration = Microsoft.IdentityModel.Tokens.SecurityTokenHandlerConfiguration;
using X509SigningCredentials = Microsoft.IdentityModel.SecurityTokenService.X509SigningCredentials;
namespace BusinessApps.HelpDesk
{
public static class TokenHelper
{
#region public fields
/// <summary>
/// SharePoint principal.
/// </summary>
public const string SharePointPrincipal = "00000003-0000-0ff1-ce00-000000000000";
/// <summary>
/// Lifetime of HighTrust access token, 12 hours.
/// </summary>
public static readonly TimeSpan HighTrustAccessTokenLifetime = TimeSpan.FromHours(12.0);
#endregion public fields
#region public methods
/// <summary>
/// Retrieves the context token string from the specified request by looking for well-known parameter names in the
/// POSTed form parameters and the querystring. Returns null if no context token is found.
/// </summary>
/// <param name="request">HttpRequest in which to look for a context token</param>
/// <returns>The context token string</returns>
public static string GetContextTokenFromRequest(HttpRequest request)
{
return GetContextTokenFromRequest(new HttpRequestWrapper(request));
}
/// <summary>
/// Retrieves the context token string from the specified request by looking for well-known parameter names in the
/// POSTed form parameters and the querystring. Returns null if no context token is found.
/// </summary>
/// <param name="request">HttpRequest in which to look for a context token</param>
/// <returns>The context token string</returns>
public static string GetContextTokenFromRequest(HttpRequestBase request)
{
string[] paramNames = { "AppContext", "AppContextToken", "AccessToken", "SPAppToken" };
foreach (string paramName in paramNames)
{
if (!string.IsNullOrEmpty(request.Form[paramName]))
{
return request.Form[paramName];
}
if (!string.IsNullOrEmpty(request.QueryString[paramName]))
{
return request.QueryString[paramName];
}
}
return null;
}
/// <summary>
/// Validate that a specified context token string is intended for this application based on the parameters
/// specified in web.config. Parameters used from web.config used for validation include ClientId,
/// HostedAppHostNameOverride, HostedAppHostName, ClientSecret, and Realm (if it is specified). If HostedAppHostNameOverride is present,
/// it will be used for validation. Otherwise, if the <paramref name="appHostName"/> is not
/// null, it is used for validation instead of the web.config's HostedAppHostName. If the token is invalid, an
/// exception is thrown. If the token is valid, TokenHelper's static STS metadata url is updated based on the token contents
/// and a JsonWebSecurityToken based on the context token is returned.
/// </summary>
/// <param name="contextTokenString">The context token to validate</param>
/// <param name="appHostName">The URL authority, consisting of Domain Name System (DNS) host name or IP address and the port number, to use for token audience validation.
/// If null, HostedAppHostName web.config setting is used instead. HostedAppHostNameOverride web.config setting, if present, will be used
/// for validation instead of <paramref name="appHostName"/> .</param>
/// <returns>A JsonWebSecurityToken based on the context token.</returns>
public static SharePointContextToken ReadAndValidateContextToken(string contextTokenString, string appHostName = null)
{
JsonWebSecurityTokenHandler tokenHandler = CreateJsonWebSecurityTokenHandler();
SecurityToken securityToken = tokenHandler.ReadToken(contextTokenString);
JsonWebSecurityToken jsonToken = securityToken as JsonWebSecurityToken;
SharePointContextToken token = SharePointContextToken.Create(jsonToken);
string stsAuthority = (new Uri(token.SecurityTokenServiceUri)).Authority;
int firstDot = stsAuthority.IndexOf('.');
GlobalEndPointPrefix = stsAuthority.Substring(0, firstDot);
AcsHostUrl = stsAuthority.Substring(firstDot + 1);
tokenHandler.ValidateToken(jsonToken);
string[] acceptableAudiences;
if (!String.IsNullOrEmpty(HostedAppHostNameOverride))
{
acceptableAudiences = HostedAppHostNameOverride.Split(';');
}
else if (appHostName == null)
{
acceptableAudiences = new[] { HostedAppHostName };
}
else
{
acceptableAudiences = new[] { appHostName };
}
bool validationSuccessful = false;
string realm = Realm ?? token.Realm;
foreach (var audience in acceptableAudiences)
{
string principal = GetFormattedPrincipal(ClientId, audience, realm);
if (StringComparer.OrdinalIgnoreCase.Equals(token.Audience, principal))
{
validationSuccessful = true;
break;
}
}
if (!validationSuccessful)
{
throw new AudienceUriValidationFailedException(
String.Format(CultureInfo.CurrentCulture,
"\"{0}\" is not the intended audience \"{1}\"", String.Join(";", acceptableAudiences), token.Audience));
}
return token;
}
/// <summary>
/// Retrieves an access token from ACS to call the source of the specified context token at the specified
/// targetHost. The targetHost must be registered for the principal that sent the context token.
/// </summary>
/// <param name="contextToken">Context token issued by the intended access token audience</param>
/// <param name="targetHost">Url authority of the target principal</param>
/// <returns>An access token with an audience matching the context token's source</returns>
public static OAuth2AccessTokenResponse GetAccessToken(SharePointContextToken contextToken, string targetHost)
{
string targetPrincipalName = contextToken.TargetPrincipalName;
// Extract the refreshToken from the context token
string refreshToken = contextToken.RefreshToken;
if (String.IsNullOrEmpty(refreshToken))
{
return null;
}
string targetRealm = Realm ?? contextToken.Realm;
return GetAccessToken(refreshToken,
targetPrincipalName,
targetHost,
targetRealm);
}
/// <summary>
/// Uses the specified authorization code to retrieve an access token from ACS to call the specified principal
/// at the specified targetHost. The targetHost must be registered for target principal. If specified realm is
/// null, the "Realm" setting in web.config will be used instead.
/// </summary>
/// <param name="authorizationCode">Authorization code to exchange for access token</param>
/// <param name="targetPrincipalName">Name of the target principal to retrieve an access token for</param>
/// <param name="targetHost">Url authority of the target principal</param>
/// <param name="targetRealm">Realm to use for the access token's nameid and audience</param>
/// <param name="redirectUri">Redirect URI registerd for this app</param>
/// <returns>An access token with an audience of the target principal</returns>
public static OAuth2AccessTokenResponse GetAccessToken(
string authorizationCode,
string targetPrincipalName,
string targetHost,
string targetRealm,
Uri redirectUri)
{
if (targetRealm == null)
{
targetRealm = Realm;
}
string resource = GetFormattedPrincipal(targetPrincipalName, targetHost, targetRealm);
string clientId = GetFormattedPrincipal(ClientId, null, targetRealm);
// Create request for token. The RedirectUri is null here. This will fail if redirect uri is registered
OAuth2AccessTokenRequest oauth2Request =
OAuth2MessageFactory.CreateAccessTokenRequestWithAuthorizationCode(
clientId,
ClientSecret,
authorizationCode,
redirectUri,
resource);
// Get token
OAuth2S2SClient client = new OAuth2S2SClient();
OAuth2AccessTokenResponse oauth2Response;
try
{
oauth2Response =
client.Issue(AcsMetadataParser.GetStsUrl(targetRealm), oauth2Request) as OAuth2AccessTokenResponse;
}
catch (WebException wex)
{
using (StreamReader sr = new StreamReader(wex.Response.GetResponseStream()))
{
string responseText = sr.ReadToEnd();
throw new WebException(wex.Message + " - " + responseText, wex);
}
}
return oauth2Response;
}
/// <summary>
/// Uses the specified refresh token to retrieve an access token from ACS to call the specified principal
/// at the specified targetHost. The targetHost must be registered for target principal. If specified realm is
/// null, the "Realm" setting in web.config will be used instead.
/// </summary>
/// <param name="refreshToken">Refresh token to exchange for access token</param>
/// <param name="targetPrincipalName">Name of the target principal to retrieve an access token for</param>
/// <param name="targetHost">Url authority of the target principal</param>
/// <param name="targetRealm">Realm to use for the access token's nameid and audience</param>
/// <returns>An access token with an audience of the target principal</returns>
public static OAuth2AccessTokenResponse GetAccessToken(
string refreshToken,
string targetPrincipalName,
string targetHost,
string targetRealm)
{
if (targetRealm == null)
{
targetRealm = Realm;
}
string resource = GetFormattedPrincipal(targetPrincipalName, targetHost, targetRealm);
string clientId = GetFormattedPrincipal(ClientId, null, targetRealm);
OAuth2AccessTokenRequest oauth2Request = OAuth2MessageFactory.CreateAccessTokenRequestWithRefreshToken(clientId, ClientSecret, refreshToken, resource);
// Get token
OAuth2S2SClient client = new OAuth2S2SClient();
OAuth2AccessTokenResponse oauth2Response;
try
{
oauth2Response =
client.Issue(AcsMetadataParser.GetStsUrl(targetRealm), oauth2Request) as OAuth2AccessTokenResponse;
}
catch (WebException wex)
{
using (StreamReader sr = new StreamReader(wex.Response.GetResponseStream()))
{
string responseText = sr.ReadToEnd();
throw new WebException(wex.Message + " - " + responseText, wex);
}
}
return oauth2Response;
}
/// <summary>
/// Retrieves an app-only access token from ACS to call the specified principal
/// at the specified targetHost. The targetHost must be registered for target principal. If specified realm is
/// null, the "Realm" setting in web.config will be used instead.
/// </summary>
/// <param name="targetPrincipalName">Name of the target principal to retrieve an access token for</param>
/// <param name="targetHost">Url authority of the target principal</param>
/// <param name="targetRealm">Realm to use for the access token's nameid and audience</param>
/// <returns>An access token with an audience of the target principal</returns>
public static OAuth2AccessTokenResponse GetAppOnlyAccessToken(
string targetPrincipalName,
string targetHost,
string targetRealm)
{
if (targetRealm == null)
{
targetRealm = Realm;
}
string resource = GetFormattedPrincipal(targetPrincipalName, targetHost, targetRealm);
string clientId = GetFormattedPrincipal(ClientId, HostedAppHostName, targetRealm);
OAuth2AccessTokenRequest oauth2Request = OAuth2MessageFactory.CreateAccessTokenRequestWithClientCredentials(clientId, ClientSecret, resource);
oauth2Request.Resource = resource;
// Get token
OAuth2S2SClient client = new OAuth2S2SClient();
OAuth2AccessTokenResponse oauth2Response;
try
{
oauth2Response =
client.Issue(AcsMetadataParser.GetStsUrl(targetRealm), oauth2Request) as OAuth2AccessTokenResponse;
}
catch (WebException wex)
{
using (StreamReader sr = new StreamReader(wex.Response.GetResponseStream()))
{
string responseText = sr.ReadToEnd();
throw new WebException(wex.Message + " - " + responseText, wex);
}
}
return oauth2Response;
}
/// <summary>
/// Creates a client context based on the properties of a remote event receiver
/// </summary>
/// <param name="properties">Properties of a remote event receiver</param>
/// <returns>A ClientContext ready to call the web where the event originated</returns>
public static ClientContext CreateRemoteEventReceiverClientContext(SPRemoteEventProperties properties)
{
Uri sharepointUrl;
if (properties.ListEventProperties != null)
{
sharepointUrl = new Uri(properties.ListEventProperties.WebUrl);
}
else if (properties.ItemEventProperties != null)
{
sharepointUrl = new Uri(properties.ItemEventProperties.WebUrl);
}
else if (properties.WebEventProperties != null)
{
sharepointUrl = new Uri(properties.WebEventProperties.FullUrl);
}
else
{
return null;
}
if (IsHighTrustApp())
{
return GetS2SClientContextWithWindowsIdentity(sharepointUrl, null);
}
return CreateAcsClientContextForUrl(properties, sharepointUrl);
}
/// <summary>
/// Creates a client context based on the properties of an app event
/// </summary>
/// <param name="properties">Properties of an app event</param>
/// <param name="useAppWeb">True to target the app web, false to target the host web</param>
/// <returns>A ClientContext ready to call the app web or the parent web</returns>
public static ClientContext CreateAppEventClientContext(SPRemoteEventProperties properties, bool useAppWeb)
{
if (properties.AppEventProperties == null)
{
return null;
}
Uri sharepointUrl = useAppWeb ? properties.AppEventProperties.AppWebFullUrl : properties.AppEventProperties.HostWebFullUrl;
if (IsHighTrustApp())
{
return GetS2SClientContextWithWindowsIdentity(sharepointUrl, null);
}
return CreateAcsClientContextForUrl(properties, sharepointUrl);
}
/// <summary>
/// Retrieves an access token from ACS using the specified authorization code, and uses that access token to
/// create a client context
/// </summary>
/// <param name="targetUrl">Url of the target SharePoint site</param>
/// <param name="authorizationCode">Authorization code to use when retrieving the access token from ACS</param>
/// <param name="redirectUri">Redirect URI registerd for this app</param>
/// <returns>A ClientContext ready to call targetUrl with a valid access token</returns>
public static ClientContext GetClientContextWithAuthorizationCode(
string targetUrl,
string authorizationCode,
Uri redirectUri)
{
return GetClientContextWithAuthorizationCode(targetUrl, SharePointPrincipal, authorizationCode, GetRealmFromTargetUrl(new Uri(targetUrl)), redirectUri);
}
/// <summary>
/// Retrieves an access token from ACS using the specified authorization code, and uses that access token to
/// create a client context
/// </summary>
/// <param name="targetUrl">Url of the target SharePoint site</param>
/// <param name="targetPrincipalName">Name of the target SharePoint principal</param>
/// <param name="authorizationCode">Authorization code to use when retrieving the access token from ACS</param>
/// <param name="targetRealm">Realm to use for the access token's nameid and audience</param>
/// <param name="redirectUri">Redirect URI registerd for this app</param>
/// <returns>A ClientContext ready to call targetUrl with a valid access token</returns>
public static ClientContext GetClientContextWithAuthorizationCode(
string targetUrl,
string targetPrincipalName,
string authorizationCode,
string targetRealm,
Uri redirectUri)
{
Uri targetUri = new Uri(targetUrl);
string accessToken =
GetAccessToken(authorizationCode, targetPrincipalName, targetUri.Authority, targetRealm, redirectUri).AccessToken;
return GetClientContextWithAccessToken(targetUrl, accessToken);
}
/// <summary>
/// Uses the specified access token to create a client context
/// </summary>
/// <param name="targetUrl">Url of the target SharePoint site</param>
/// <param name="accessToken">Access token to be used when calling the specified targetUrl</param>
/// <returns>A ClientContext ready to call targetUrl with the specified access token</returns>
public static ClientContext GetClientContextWithAccessToken(string targetUrl, string accessToken)
{
ClientContext clientContext = new ClientContext(targetUrl);
clientContext.AuthenticationMode = ClientAuthenticationMode.Anonymous;
clientContext.FormDigestHandlingEnabled = false;
clientContext.ExecutingWebRequest +=
delegate(object oSender, WebRequestEventArgs webRequestEventArgs)
{
webRequestEventArgs.WebRequestExecutor.RequestHeaders["Authorization"] =
"Bearer " + accessToken;
};
return clientContext;
}
/// <summary>
/// Retrieves an access token from ACS using the specified context token, and uses that access token to create
/// a client context
/// </summary>
/// <param name="targetUrl">Url of the target SharePoint site</param>
/// <param name="contextTokenString">Context token received from the target SharePoint site</param>
/// <param name="appHostUrl">Url authority of the hosted app. If this is null, the value in the HostedAppHostName
/// of web.config will be used instead</param>
/// <returns>A ClientContext ready to call targetUrl with a valid access token</returns>
public static ClientContext GetClientContextWithContextToken(
string targetUrl,
string contextTokenString,
string appHostUrl)
{
SharePointContextToken contextToken = ReadAndValidateContextToken(contextTokenString, appHostUrl);
Uri targetUri = new Uri(targetUrl);
string accessToken = GetAccessToken(contextToken, targetUri.Authority).AccessToken;
return GetClientContextWithAccessToken(targetUrl, accessToken);
}
/// <summary>
/// Returns the SharePoint url to which the app should redirect the browser to request consent and get back
/// an authorization code.
/// </summary>
/// <param name="contextUrl">Absolute Url of the SharePoint site</param>
/// <param name="scope">Space-delimited permissions to request from the SharePoint site in "shorthand" format
/// (e.g. "Web.Read Site.Write")</param>
/// <returns>Url of the SharePoint site's OAuth authorization page</returns>
public static string GetAuthorizationUrl(string contextUrl, string scope)
{
return string.Format(
"{0}{1}?IsDlg=1&client_id={2}&scope={3}&response_type=code",
EnsureTrailingSlash(contextUrl),
AuthorizationPage,
ClientId,
scope);
}
/// <summary>
/// Returns the SharePoint url to which the app should redirect the browser to request consent and get back
/// an authorization code.
/// </summary>
/// <param name="contextUrl">Absolute Url of the SharePoint site</param>
/// <param name="scope">Space-delimited permissions to request from the SharePoint site in "shorthand" format
/// (e.g. "Web.Read Site.Write")</param>
/// <param name="redirectUri">Uri to which SharePoint should redirect the browser to after consent is
/// granted</param>
/// <returns>Url of the SharePoint site's OAuth authorization page</returns>
public static string GetAuthorizationUrl(string contextUrl, string scope, string redirectUri)
{
return string.Format(
"{0}{1}?IsDlg=1&client_id={2}&scope={3}&response_type=code&redirect_uri={4}",
EnsureTrailingSlash(contextUrl),
AuthorizationPage,
ClientId,
scope,
redirectUri);
}
/// <summary>
/// Returns the SharePoint url to which the app should redirect the browser to request a new context token.
/// </summary>
/// <param name="contextUrl">Absolute Url of the SharePoint site</param>
/// <param name="redirectUri">Uri to which SharePoint should redirect the browser to with a context token</param>
/// <returns>Url of the SharePoint site's context token redirect page</returns>
public static string GetAppContextTokenRequestUrl(string contextUrl, string redirectUri)
{
return string.Format(
"{0}{1}?client_id={2}&redirect_uri={3}",
EnsureTrailingSlash(contextUrl),
RedirectPage,
ClientId,
redirectUri);
}
/// <summary>
/// Retrieves an S2S access token signed by the application's private certificate on behalf of the specified
/// WindowsIdentity and intended for the SharePoint at the targetApplicationUri. If no Realm is specified in
/// web.config, an auth challenge will be issued to the targetApplicationUri to discover it.
/// </summary>
/// <param name="targetApplicationUri">Url of the target SharePoint site</param>
/// <param name="identity">Windows identity of the user on whose behalf to create the access token</param>
/// <returns>An access token with an audience of the target principal</returns>
public static string GetS2SAccessTokenWithWindowsIdentity(
Uri targetApplicationUri,
WindowsIdentity identity)
{
string realm = string.IsNullOrEmpty(Realm) ? GetRealmFromTargetUrl(targetApplicationUri) : Realm;
JsonWebTokenClaim[] claims = identity != null ? GetClaimsWithWindowsIdentity(identity) : null;
return GetS2SAccessTokenWithClaims(targetApplicationUri.Authority, realm, claims);
}
/// <summary>
/// Retrieves an S2S client context with an access token signed by the application's private certificate on
/// behalf of the specified WindowsIdentity and intended for application at the targetApplicationUri using the
/// targetRealm. If no Realm is specified in web.config, an auth challenge will be issued to the
/// targetApplicationUri to discover it.
/// </summary>
/// <param name="targetApplicationUri">Url of the target SharePoint site</param>
/// <param name="identity">Windows identity of the user on whose behalf to create the access token</param>
/// <returns>A ClientContext using an access token with an audience of the target application</returns>
public static ClientContext GetS2SClientContextWithWindowsIdentity(
Uri targetApplicationUri,
WindowsIdentity identity)
{
string realm = string.IsNullOrEmpty(Realm) ? GetRealmFromTargetUrl(targetApplicationUri) : Realm;
JsonWebTokenClaim[] claims = identity != null ? GetClaimsWithWindowsIdentity(identity) : null;
string accessToken = GetS2SAccessTokenWithClaims(targetApplicationUri.Authority, realm, claims);
return GetClientContextWithAccessToken(targetApplicationUri.ToString(), accessToken);
}
/// <summary>
/// Get authentication realm from SharePoint
/// </summary>
/// <param name="targetApplicationUri">Url of the target SharePoint site</param>
/// <returns>String representation of the realm GUID</returns>
public static string GetRealmFromTargetUrl(Uri targetApplicationUri)
{
WebRequest request = WebRequest.Create(targetApplicationUri + "/_vti_bin/client.svc");
request.Headers.Add("Authorization: Bearer ");
try
{
using (request.GetResponse())
{
}
}
catch (WebException e)
{
if (e.Response == null)
{
return null;
}
string bearerResponseHeader = e.Response.Headers["WWW-Authenticate"];
if (string.IsNullOrEmpty(bearerResponseHeader))
{
return null;
}
const string bearer = "Bearer realm=\"";
int bearerIndex = bearerResponseHeader.IndexOf(bearer, StringComparison.Ordinal);
if (bearerIndex < 0)
{
return null;
}
int realmIndex = bearerIndex + bearer.Length;
if (bearerResponseHeader.Length >= realmIndex + 36)
{
string targetRealm = bearerResponseHeader.Substring(realmIndex, 36);
Guid realmGuid;
if (Guid.TryParse(targetRealm, out realmGuid))
{
return targetRealm;
}
}
}
return null;
}
/// <summary>
/// Determines if this is a high trust app.
/// </summary>
/// <returns>True if this is a high trust app.</returns>
public static bool IsHighTrustApp()
{
return SigningCredentials != null;
}
/// <summary>
/// Ensures that the specified URL ends with '/' if it is not null or empty.
/// </summary>
/// <param name="url">The url.</param>
/// <returns>The url ending with '/' if it is not null or empty.</returns>
public static string EnsureTrailingSlash(string url)
{
if (!string.IsNullOrEmpty(url) && url[url.Length - 1] != '/')
{
return url + "/";
}
return url;
}
#endregion
#region private fields
//
// Configuration Constants
//
private const string AuthorizationPage = "_layouts/15/OAuthAuthorize.aspx";
private const string RedirectPage = "_layouts/15/AppRedirect.aspx";
private const string AcsPrincipalName = "00000001-0000-0000-c000-000000000000";
private const string AcsMetadataEndPointRelativeUrl = "metadata/json/1";
private const string S2SProtocol = "OAuth2";
private const string DelegationIssuance = "DelegationIssuance1.0";
private const string NameIdentifierClaimType = JsonWebTokenConstants.ReservedClaims.NameIdentifier;
private const string TrustedForImpersonationClaimType = "trustedfordelegation";
private const string ActorTokenClaimType = JsonWebTokenConstants.ReservedClaims.ActorToken;
//
// Environment Constants
//
private static string GlobalEndPointPrefix = "accounts";
private static string AcsHostUrl = "accesscontrol.windows.net";
//
// Hosted app configuration
//
private static readonly string ClientId = string.IsNullOrEmpty(WebConfigurationManager.AppSettings.Get("ClientId")) ? WebConfigurationManager.AppSettings.Get("HostedAppName") : WebConfigurationManager.AppSettings.Get("ClientId");
private static readonly string IssuerId = string.IsNullOrEmpty(WebConfigurationManager.AppSettings.Get("IssuerId")) ? ClientId : WebConfigurationManager.AppSettings.Get("IssuerId");
private static readonly string HostedAppHostNameOverride = WebConfigurationManager.AppSettings.Get("HostedAppHostNameOverride");
private static readonly string HostedAppHostName = WebConfigurationManager.AppSettings.Get("HostedAppHostName");
private static readonly string ClientSecret = string.IsNullOrEmpty(WebConfigurationManager.AppSettings.Get("ClientSecret")) ? WebConfigurationManager.AppSettings.Get("HostedAppSigningKey") : WebConfigurationManager.AppSettings.Get("ClientSecret");
private static readonly string SecondaryClientSecret = WebConfigurationManager.AppSettings.Get("SecondaryClientSecret");
private static readonly string Realm = WebConfigurationManager.AppSettings.Get("Realm");
private static readonly string ServiceNamespace = WebConfigurationManager.AppSettings.Get("Realm");
private static readonly string ClientSigningCertificatePath = WebConfigurationManager.AppSettings.Get("ClientSigningCertificatePath");
private static readonly string ClientSigningCertificatePassword = WebConfigurationManager.AppSettings.Get("ClientSigningCertificatePassword");
private static readonly X509Certificate2 ClientCertificate = (string.IsNullOrEmpty(ClientSigningCertificatePath) || string.IsNullOrEmpty(ClientSigningCertificatePassword)) ? null : new X509Certificate2(ClientSigningCertificatePath, ClientSigningCertificatePassword);
private static readonly X509SigningCredentials SigningCredentials = (ClientCertificate == null) ? null : new X509SigningCredentials(ClientCertificate, SecurityAlgorithms.RsaSha256Signature, SecurityAlgorithms.Sha256Digest);
#endregion
#region private methods
private static ClientContext CreateAcsClientContextForUrl(SPRemoteEventProperties properties, Uri sharepointUrl)
{
string contextTokenString = properties.ContextToken;
if (String.IsNullOrEmpty(contextTokenString))
{
return null;
}
SharePointContextToken contextToken = ReadAndValidateContextToken(contextTokenString, OperationContext.Current.IncomingMessageHeaders.To.Host);
string accessToken = GetAccessToken(contextToken, sharepointUrl.Authority).AccessToken;
return GetClientContextWithAccessToken(sharepointUrl.ToString(), accessToken);
}
private static string GetAcsMetadataEndpointUrl()
{
return Path.Combine(GetAcsGlobalEndpointUrl(), AcsMetadataEndPointRelativeUrl);
}
private static string GetFormattedPrincipal(string principalName, string hostName, string realm)
{
if (!String.IsNullOrEmpty(hostName))
{
return String.Format(CultureInfo.InvariantCulture, "{0}/{1}@{2}", principalName, hostName, realm);
}
return String.Format(CultureInfo.InvariantCulture, "{0}@{1}", principalName, realm);
}
private static string GetAcsPrincipalName(string realm)
{
return GetFormattedPrincipal(AcsPrincipalName, new Uri(GetAcsGlobalEndpointUrl()).Host, realm);
}
private static string GetAcsGlobalEndpointUrl()
{
return String.Format(CultureInfo.InvariantCulture, "https://{0}.{1}/", GlobalEndPointPrefix, AcsHostUrl);
}
private static JsonWebSecurityTokenHandler CreateJsonWebSecurityTokenHandler()
{
JsonWebSecurityTokenHandler handler = new JsonWebSecurityTokenHandler();
handler.Configuration = new SecurityTokenHandlerConfiguration();
handler.Configuration.AudienceRestriction = new AudienceRestriction(AudienceUriMode.Never);
handler.Configuration.CertificateValidator = X509CertificateValidator.None;
List<byte[]> securityKeys = new List<byte[]>();
securityKeys.Add(Convert.FromBase64String(ClientSecret));
if (!string.IsNullOrEmpty(SecondaryClientSecret))
{
securityKeys.Add(Convert.FromBase64String(SecondaryClientSecret));
}
List<SecurityToken> securityTokens = new List<SecurityToken>();
securityTokens.Add(new MultipleSymmetricKeySecurityToken(securityKeys));
handler.Configuration.IssuerTokenResolver =
SecurityTokenResolver.CreateDefaultSecurityTokenResolver(
new ReadOnlyCollection<SecurityToken>(securityTokens),
false);
SymmetricKeyIssuerNameRegistry issuerNameRegistry = new SymmetricKeyIssuerNameRegistry();
foreach (byte[] securitykey in securityKeys)
{
issuerNameRegistry.AddTrustedIssuer(securitykey, GetAcsPrincipalName(ServiceNamespace));
}
handler.Configuration.IssuerNameRegistry = issuerNameRegistry;
return handler;
}
private static string GetS2SAccessTokenWithClaims(
string targetApplicationHostName,
string targetRealm,
IEnumerable<JsonWebTokenClaim> claims)
{
return IssueToken(
ClientId,
IssuerId,
targetRealm,
SharePointPrincipal,
targetRealm,
targetApplicationHostName,
true,
claims,
claims == null);
}
private static JsonWebTokenClaim[] GetClaimsWithWindowsIdentity(WindowsIdentity identity)
{
JsonWebTokenClaim[] claims = new JsonWebTokenClaim[]
{
new JsonWebTokenClaim(NameIdentifierClaimType, identity.User.Value.ToLower()),
new JsonWebTokenClaim("nii", "urn:office:idp:activedirectory")
};
return claims;
}
private static string IssueToken(
string sourceApplication,
string issuerApplication,
string sourceRealm,
string targetApplication,
string targetRealm,
string targetApplicationHostName,
bool trustedForDelegation,
IEnumerable<JsonWebTokenClaim> claims,
bool appOnly = false)
{
if (null == SigningCredentials)
{
throw new InvalidOperationException("SigningCredentials was not initialized");
}
#region Actor token
string issuer = string.IsNullOrEmpty(sourceRealm) ? issuerApplication : string.Format("{0}@{1}", issuerApplication, sourceRealm);
string nameid = string.IsNullOrEmpty(sourceRealm) ? sourceApplication : string.Format("{0}@{1}", sourceApplication, sourceRealm);
string audience = string.Format("{0}/{1}@{2}", targetApplication, targetApplicationHostName, targetRealm);
List<JsonWebTokenClaim> actorClaims = new List<JsonWebTokenClaim>();
actorClaims.Add(new JsonWebTokenClaim(JsonWebTokenConstants.ReservedClaims.NameIdentifier, nameid));
if (trustedForDelegation && !appOnly)
{
actorClaims.Add(new JsonWebTokenClaim(TrustedForImpersonationClaimType, "true"));
}
// Create token
JsonWebSecurityToken actorToken = new JsonWebSecurityToken(
issuer: issuer,
audience: audience,
validFrom: DateTime.UtcNow,
validTo: DateTime.UtcNow.Add(HighTrustAccessTokenLifetime),
signingCredentials: SigningCredentials,
claims: actorClaims);
string actorTokenString = new JsonWebSecurityTokenHandler().WriteTokenAsString(actorToken);
if (appOnly)
{
// App-only token is the same as actor token for delegated case
return actorTokenString;
}
#endregion Actor token
#region Outer token
List<JsonWebTokenClaim> outerClaims = null == claims ? new List<JsonWebTokenClaim>() : new List<JsonWebTokenClaim>(claims);
outerClaims.Add(new JsonWebTokenClaim(ActorTokenClaimType, actorTokenString));
JsonWebSecurityToken jsonToken = new JsonWebSecurityToken(
nameid, // outer token issuer should match actor token nameid
audience,
DateTime.UtcNow,
DateTime.UtcNow.Add(HighTrustAccessTokenLifetime),
outerClaims);
string accessToken = new JsonWebSecurityTokenHandler().WriteTokenAsString(jsonToken);
#endregion Outer token
return accessToken;
}
#endregion
#region AcsMetadataParser
// This class is used to get MetaData document from the global STS endpoint. It contains
// methods to parse the MetaData document and get endpoints and STS certificate.
public static class AcsMetadataParser
{
public static X509Certificate2 GetAcsSigningCert(string realm)
{
JsonMetadataDocument document = GetMetadataDocument(realm);
if (null != document.keys && document.keys.Count > 0)
{
JsonKey signingKey = document.keys[0];
if (null != signingKey && null != signingKey.keyValue)
{
return new X509Certificate2(Encoding.UTF8.GetBytes(signingKey.keyValue.value));
}
}
throw new Exception("Metadata document does not contain ACS signing certificate.");
}
public static string GetDelegationServiceUrl(string realm)
{
JsonMetadataDocument document = GetMetadataDocument(realm);
JsonEndpoint delegationEndpoint = document.endpoints.SingleOrDefault(e => e.protocol == DelegationIssuance);
if (null != delegationEndpoint)
{
return delegationEndpoint.location;
}
throw new Exception("Metadata document does not contain Delegation Service endpoint Url");
}
private static JsonMetadataDocument GetMetadataDocument(string realm)
{
string acsMetadataEndpointUrlWithRealm = String.Format(CultureInfo.InvariantCulture, "{0}?realm={1}",
GetAcsMetadataEndpointUrl(),
realm);
byte[] acsMetadata;
using (WebClient webClient = new WebClient())
{
acsMetadata = webClient.DownloadData(acsMetadataEndpointUrlWithRealm);
}
string jsonResponseString = Encoding.UTF8.GetString(acsMetadata);
JavaScriptSerializer serializer = new JavaScriptSerializer();
JsonMetadataDocument document = serializer.Deserialize<JsonMetadataDocument>(jsonResponseString);
if (null == document)
{
throw new Exception("No metadata document found at the global endpoint " + acsMetadataEndpointUrlWithRealm);
}
return document;
}
public static string GetStsUrl(string realm)
{
JsonMetadataDocument document = GetMetadataDocument(realm);
JsonEndpoint s2sEndpoint = document.endpoints.SingleOrDefault(e => e.protocol == S2SProtocol);
if (null != s2sEndpoint)
{
return s2sEndpoint.location;
}
throw new Exception("Metadata document does not contain STS endpoint url");
}
private class JsonMetadataDocument
{
public string serviceName { get; set; }
public List<JsonEndpoint> endpoints { get; set; }
public List<JsonKey> keys { get; set; }
}
private class JsonEndpoint
{
public string location { get; set; }
public string protocol { get; set; }
public string usage { get; set; }
}
private class JsonKeyValue
{
public string type { get; set; }
public string value { get; set; }
}
private class JsonKey
{
public string usage { get; set; }
public JsonKeyValue keyValue { get; set; }
}
}
#endregion
}
/// <summary>
/// A JsonWebSecurityToken generated by SharePoint to authenticate to a 3rd party application and allow callbacks using a refresh token
/// </summary>
public class SharePointContextToken : JsonWebSecurityToken
{
public static SharePointContextToken Create(JsonWebSecurityToken contextToken)
{
return new SharePointContextToken(contextToken.Issuer, contextToken.Audience, contextToken.ValidFrom, contextToken.ValidTo, contextToken.Claims);
}
public SharePointContextToken(string issuer, string audience, DateTime validFrom, DateTime validTo, IEnumerable<JsonWebTokenClaim> claims)
: base(issuer, audience, validFrom, validTo, claims)
{
}
public SharePointContextToken(string issuer, string audience, DateTime validFrom, DateTime validTo, IEnumerable<JsonWebTokenClaim> claims, SecurityToken issuerToken, JsonWebSecurityToken actorToken)
: base(issuer, audience, validFrom, validTo, claims, issuerToken, actorToken)
{
}
public SharePointContextToken(string issuer, string audience, DateTime validFrom, DateTime validTo, IEnumerable<JsonWebTokenClaim> claims, SigningCredentials signingCredentials)
: base(issuer, audience, validFrom, validTo, claims, signingCredentials)
{
}
public string NameId
{
get
{
return GetClaimValue(this, "nameid");
}
}
/// <summary>
/// The principal name portion of the context token's "appctxsender" claim
/// </summary>
public string TargetPrincipalName
{
get
{
string appctxsender = GetClaimValue(this, "appctxsender");
if (appctxsender == null)
{
return null;
}
return appctxsender.Split('@')[0];
}
}
/// <summary>
/// The context token's "refreshtoken" claim
/// </summary>
public string RefreshToken
{
get
{
return GetClaimValue(this, "refreshtoken");
}
}
/// <summary>
/// The context token's "CacheKey" claim
/// </summary>
public string CacheKey
{
get
{
string appctx = GetClaimValue(this, "appctx");
if (appctx == null)
{
return null;
}
ClientContext ctx = new ClientContext("http://tempuri.org");
Dictionary<string, object> dict = (Dictionary<string, object>)ctx.ParseObjectFromJsonString(appctx);
string cacheKey = (string)dict["CacheKey"];
return cacheKey;
}
}
/// <summary>
/// The context token's "SecurityTokenServiceUri" claim
/// </summary>
public string SecurityTokenServiceUri
{
get
{
string appctx = GetClaimValue(this, "appctx");
if (appctx == null)
{
return null;
}
ClientContext ctx = new ClientContext("http://tempuri.org");
Dictionary<string, object> dict = (Dictionary<string, object>)ctx.ParseObjectFromJsonString(appctx);
string securityTokenServiceUri = (string)dict["SecurityTokenServiceUri"];
return securityTokenServiceUri;
}
}
/// <summary>
/// The realm portion of the context token's "audience" claim
/// </summary>
public string Realm
{
get
{
string aud = Audience;
if (aud == null)
{
return null;
}
string tokenRealm = aud.Substring(aud.IndexOf('@') + 1);
return tokenRealm;
}
}
private static string GetClaimValue(JsonWebSecurityToken token, string claimType)
{
if (token == null)
{
throw new ArgumentNullException("token");
}
foreach (JsonWebTokenClaim claim in token.Claims)
{
if (StringComparer.Ordinal.Equals(claim.ClaimType, claimType))
{
return claim.Value;
}
}
return null;
}
}
/// <summary>
/// Represents a security token which contains multiple security keys that are generated using symmetric algorithms.
/// </summary>
public class MultipleSymmetricKeySecurityToken : SecurityToken
{
/// <summary>
/// Initializes a new instance of the MultipleSymmetricKeySecurityToken class.
/// </summary>
/// <param name="keys">An enumeration of Byte arrays that contain the symmetric keys.</param>
public MultipleSymmetricKeySecurityToken(IEnumerable<byte[]> keys)
: this(UniqueId.CreateUniqueId(), keys)
{
}
/// <summary>
/// Initializes a new instance of the MultipleSymmetricKeySecurityToken class.
/// </summary>
/// <param name="tokenId">The unique identifier of the security token.</param>
/// <param name="keys">An enumeration of Byte arrays that contain the symmetric keys.</param>
public MultipleSymmetricKeySecurityToken(string tokenId, IEnumerable<byte[]> keys)
{
if (keys == null)
{
throw new ArgumentNullException("keys");
}
if (String.IsNullOrEmpty(tokenId))
{
throw new ArgumentException("Value cannot be a null or empty string.", "tokenId");
}
foreach (byte[] key in keys)
{
if (key.Length <= 0)
{
throw new ArgumentException("The key length must be greater then zero.", "keys");
}
}
id = tokenId;
effectiveTime = DateTime.UtcNow;
securityKeys = CreateSymmetricSecurityKeys(keys);
}
/// <summary>
/// Gets the unique identifier of the security token.
/// </summary>
public override string Id
{
get
{
return id;
}
}
/// <summary>
/// Gets the cryptographic keys associated with the security token.
/// </summary>
public override ReadOnlyCollection<SecurityKey> SecurityKeys
{
get
{
return securityKeys.AsReadOnly();
}
}
/// <summary>
/// Gets the first instant in time at which this security token is valid.
/// </summary>
public override DateTime ValidFrom
{
get
{
return effectiveTime;
}
}
/// <summary>
/// Gets the last instant in time at which this security token is valid.
/// </summary>
public override DateTime ValidTo
{
get
{
// Never expire
return DateTime.MaxValue;
}
}
/// <summary>
/// Returns a value that indicates whether the key identifier for this instance can be resolved to the specified key identifier.
/// </summary>
/// <param name="keyIdentifierClause">A SecurityKeyIdentifierClause to compare to this instance</param>
/// <returns>true if keyIdentifierClause is a SecurityKeyIdentifierClause and it has the same unique identifier as the Id property; otherwise, false.</returns>
public override bool MatchesKeyIdentifierClause(SecurityKeyIdentifierClause keyIdentifierClause)
{
if (keyIdentifierClause == null)
{
throw new ArgumentNullException("keyIdentifierClause");
}
// Since this is a symmetric token and we do not have IDs to distinguish tokens, we just check for the
// presence of a SymmetricIssuerKeyIdentifier. The actual mapping to the issuer takes place later
// when the key is matched to the issuer.
if (keyIdentifierClause is SymmetricIssuerKeyIdentifierClause)
{
return true;
}
return base.MatchesKeyIdentifierClause(keyIdentifierClause);
}
#region private members
private List<SecurityKey> CreateSymmetricSecurityKeys(IEnumerable<byte[]> keys)
{
List<SecurityKey> symmetricKeys = new List<SecurityKey>();
foreach (byte[] key in keys)
{
symmetricKeys.Add(new InMemorySymmetricSecurityKey(key));
}
return symmetricKeys;
}
private string id;
private DateTime effectiveTime;
private List<SecurityKey> securityKeys;
#endregion
}
}
| |
//
// CompositeFormatStringParser.cs
//
// Authors:
// Simon Lindgren <simon.n.lindgren@gmail.com>
//
// Copyright (c) 2012 Simon Lindgren
//
// 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;
using System.Linq;
namespace ICSharpCode.NRefactory.Utils
{
/// <summary>
/// Composite format string parser.
/// </summary>
/// <remarks>
/// Implements a complete parser for valid strings as well as
/// error reporting and best-effort parsing for invalid strings.
/// </remarks>
public class CompositeFormatStringParser
{
public CompositeFormatStringParser ()
{
errors = new List<IFormatStringError> ();
}
/// <summary>
/// Parse the specified format string.
/// </summary>
/// <param name='format'>
/// The format string.
/// </param>
public FormatStringParseResult Parse (string format)
{
if (format == null)
throw new ArgumentNullException ("format");
var result = new FormatStringParseResult();
// Format string syntax: http://msdn.microsoft.com/en-us/library/txafckwd.aspx
int textStart = 0;
var length = format.Length;
for (int i = 0; i < length; i++) {
// Get fixed text
GetText (format, ref i);
if (i < format.Length && format [i] == '{') {
int formatItemStart = i;
int index;
int? alignment = null;
string argumentFormat = null;
var textSegmentErrors = new List<IFormatStringError>(GetErrors());
// Try to parse the parts of the format item
++i;
index = ParseIndex (format, ref i);
CheckForMissingEndBrace (format, i, length);
alignment = ParseAlignment (format, ref i, length);
CheckForMissingEndBrace (format, i, length);
argumentFormat = ParseSubFormatString (format, ref i, length);
CheckForMissingEndBrace (format, i, length);
// Check what we parsed
if (i == formatItemStart + 1 && (i == length || (i < length && format [i] != '}'))) {
// There were no format item after all, this was just an
// unescaped left brace
SetErrors(textSegmentErrors);
AddError (new DefaultFormatStringError {
Message = "Unescaped '{'",
StartLocation = formatItemStart,
EndLocation = formatItemStart + 1,
OriginalText = "{",
SuggestedReplacementText = "{{"
});
continue;
} else if (formatItemStart - textStart > 0) {
// We have parsed a format item, end the text segment
var textSegment = new TextSegment (UnEscape (format.Substring (textStart, formatItemStart - textStart)));
textSegment.Errors = textSegmentErrors;
result.Segments.Add (textSegment);
}
// Unclosed format items in fixed text gets advances i one step too far
if (i < length && format [i] != '}')
--i;
// i may actually point outside of format if there is a syntactical error
// if that happens, we want the last position
var endLocation = Math.Min (length, i + 1);
result.Segments.Add (new FormatItem (index, alignment, argumentFormat) {
StartLocation = formatItemStart,
EndLocation = endLocation,
Errors = GetErrors ()
});
ClearErrors ();
// The next potential text segment starts after this format item
textStart = i + 1;
}
}
// Handle remaining text
if (textStart < length) {
var textSegment = new TextSegment (UnEscape (format.Substring (textStart)), textStart);
textSegment.Errors = GetErrors();
result.Segments.Add (textSegment);
}
return result;
}
int ParseIndex (string format, ref int i)
{
int parsedCharacters;
int? maybeIndex = GetAndCheckNumber (format, ",:}", ref i, i, out parsedCharacters);
if (parsedCharacters == 0) {
AddError (new DefaultFormatStringError {
StartLocation = i,
EndLocation = i,
Message = "Missing index",
OriginalText = "",
SuggestedReplacementText = "0"
});
}
return maybeIndex ?? 0;
}
int? ParseAlignment(string format, ref int i, int length)
{
if (i < length && format [i] == ',') {
int alignmentBegin = i;
++i;
while (i < length && char.IsWhiteSpace(format [i]))
++i;
int parsedCharacters;
var number = GetAndCheckNumber (format, ",:}", ref i, alignmentBegin + 1, out parsedCharacters);
if (parsedCharacters == 0) {
AddError (new DefaultFormatStringError {
StartLocation = i,
EndLocation = i,
Message = "Missing alignment",
OriginalText = "",
SuggestedReplacementText = "0"
});
}
return number ?? 0;
}
return null;
}
string ParseSubFormatString(string format, ref int i, int length)
{
if (i < length && format [i] == ':') {
++i;
int begin = i;
GetText(format, ref i, "", true);
var escaped = format.Substring (begin, i - begin);
return UnEscape (escaped);
}
return null;
}
void CheckForMissingEndBrace (string format, int i, int length)
{
if (i == length) {
int j;
for (j = i - 1; format[j] == '}'; j--);
var oddEndBraceCount = (i - j) % 2 == 1;
if (oddEndBraceCount) {
AddMissingEndBraceError(i, i, "Missing '}'", "");
}
return;
}
return;
}
void GetText (string format, ref int index, string delimiters = "", bool allowEscape = false)
{
while (index < format.Length) {
if (format [index] == '{' || format[index] == '}') {
if (index + 1 < format.Length && format [index + 1] == format[index] && allowEscape)
++index;
else
break;
} else if (delimiters.Contains(format[index].ToString())) {
break;
}
++index;
};
}
int? GetNumber (string format, ref int index)
{
if (format.Length == 0) {
return null;
}
int sum = 0;
int i = index;
bool positive = format [i] != '-';
if (!positive)
++i;
int numberStartIndex = i;
while (i < format.Length && format[i] >= '0' && format[i] <= '9') {
sum = 10 * sum + format [i] - '0';
++i;
}
if (i == numberStartIndex)
return null;
index = i;
return positive ? sum : -sum;
}
int? GetAndCheckNumber (string format, string delimiters, ref int index, int numberFieldStart, out int parsedCharacters)
{
int fieldIndex = index;
GetText (format, ref fieldIndex, delimiters);
int fieldEnd = fieldIndex;
var numberText = format.Substring(index, fieldEnd - index);
parsedCharacters = numberText.Length;
int numberLength = 0;
int? number = GetNumber (numberText, ref numberLength);
var endingChar = index + numberLength;
if (numberLength != parsedCharacters && fieldEnd < format.Length && delimiters.Contains (format [fieldEnd])) {
// Not the entire number field could be parsed
// The field actually ended as intended, so set the index to the end of the field
index = fieldEnd;
var suggestedNumber = (number ?? 0).ToString ();
AddInvalidNumberFormatError (numberFieldStart, format.Substring (numberFieldStart, index - numberFieldStart), suggestedNumber);
} else if (numberLength != parsedCharacters) {
// Not the entire number field could be parsed
// The field didn't end, it was cut off so we are missing an ending brace
index = endingChar;
AddMissingEndBraceError (index, index, "Missing ending '}'", "");
} else {
index = endingChar;
}
return number;
}
public static string UnEscape (string unEscaped)
{
return unEscaped.Replace ("{{", "{").Replace ("}}", "}");
}
IList<IFormatStringError> errors;
bool hasMissingEndBrace = false;
void AddError (IFormatStringError error)
{
errors.Add (error);
}
void AddMissingEndBraceError(int start, int end, string message, string originalText)
{
// Only add a single missing end brace per format item
if (hasMissingEndBrace)
return;
AddError (new DefaultFormatStringError {
StartLocation = start,
EndLocation = end,
Message = message,
OriginalText = originalText,
SuggestedReplacementText = "}"
});
hasMissingEndBrace = true;
}
void AddInvalidNumberFormatError (int i, string number, string replacementText)
{
AddError (new DefaultFormatStringError {
StartLocation = i,
EndLocation = i + number.Length,
Message = string.Format ("Invalid number '{0}'", number),
OriginalText = number,
SuggestedReplacementText = replacementText
});
}
IList<IFormatStringError> GetErrors ()
{
return errors;
}
void SetErrors (IList<IFormatStringError> errors)
{
this.errors = errors;
}
void ClearErrors ()
{
hasMissingEndBrace = false;
errors = new List<IFormatStringError> ();
}
}
public class FormatStringParseResult
{
public FormatStringParseResult()
{
Segments = new List<IFormatStringSegment>();
}
public IList<IFormatStringSegment> Segments { get; private set; }
public bool HasErrors
{
get {
return Segments.SelectMany(segment => segment.Errors).Any();
}
}
}
}
| |
/***************************************************************************************************************************************
* Copyright (C) 2001-2012 LearnLift USA *
* Contact: Learnlift USA, 12 Greenway Plaza, Suite 1510, Houston, Texas 77046, support@memorylifter.com *
* *
* This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License *
* as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. *
* *
* This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty *
* of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. *
* *
* You should have received a copy of the GNU Lesser General Public License along with this library; if not, *
* write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA *
***************************************************************************************************************************************/
namespace MLifter.Controls.LearningWindow
{
partial class LearningWindow
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Component Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(LearningWindow));
this.splitContainerHorizontal = new System.Windows.Forms.SplitContainer();
this.tableLayoutPanelMainContent = new System.Windows.Forms.TableLayoutPanel();
this.statisticsPanel = new MLifter.Controls.LearningWindow.StatisticsPanel();
this.statusBar = new MLifter.Controls.LearningWindow.StatusBar();
this.panelLearningWindowMiddle = new System.Windows.Forms.Panel();
this.dockingButtonStack = new MLifter.Components.DockingButton();
this.gradientPanelMain = new MLifter.Components.GradientPanel();
this.tableLayoutPanelLearningWindowMiddle = new System.Windows.Forms.TableLayoutPanel();
this.splitContainerVertical = new System.Windows.Forms.SplitContainer();
this.questionPanel = new MLifter.Controls.LearningWindow.QuestionPanel();
this.answerPanel = new MLifter.Controls.LearningWindow.AnswerPanel();
this.buttonsPanelMainControl = new MLifter.Controls.LearningWindow.ButtonsPanel();
this.stackFlow = new MLifter.Controls.LearningWindow.StackFlow();
this.audioPlayerComponent = new MLifter.Controls.LearningWindow.AudioPlayerComponent(this.components);
this.userDialogComponent = new MLifter.Controls.LearningWindow.UserDialogComponent(this.components);
this.splitContainerHorizontal.Panel1.SuspendLayout();
this.splitContainerHorizontal.Panel2.SuspendLayout();
this.splitContainerHorizontal.SuspendLayout();
this.tableLayoutPanelMainContent.SuspendLayout();
this.panelLearningWindowMiddle.SuspendLayout();
this.gradientPanelMain.SuspendLayout();
this.tableLayoutPanelLearningWindowMiddle.SuspendLayout();
this.splitContainerVertical.Panel1.SuspendLayout();
this.splitContainerVertical.Panel2.SuspendLayout();
this.splitContainerVertical.SuspendLayout();
this.SuspendLayout();
//
// splitContainerHorizontal
//
resources.ApplyResources(this.splitContainerHorizontal, "splitContainerHorizontal");
this.splitContainerHorizontal.Name = "splitContainerHorizontal";
//
// splitContainerHorizontal.Panel1
//
this.splitContainerHorizontal.Panel1.Controls.Add(this.tableLayoutPanelMainContent);
//
// splitContainerHorizontal.Panel2
//
this.splitContainerHorizontal.Panel2.Controls.Add(this.stackFlow);
//
// tableLayoutPanelMainContent
//
resources.ApplyResources(this.tableLayoutPanelMainContent, "tableLayoutPanelMainContent");
this.tableLayoutPanelMainContent.Controls.Add(this.statisticsPanel, 0, 0);
this.tableLayoutPanelMainContent.Controls.Add(this.statusBar, 0, 3);
this.tableLayoutPanelMainContent.Controls.Add(this.panelLearningWindowMiddle, 0, 1);
this.tableLayoutPanelMainContent.Name = "tableLayoutPanelMainContent";
//
// statisticsPanel
//
this.statisticsPanel.BoxCards = 0;
this.statisticsPanel.BoxNo = 0;
this.statisticsPanel.BoxSize = 0;
resources.ApplyResources(this.statisticsPanel, "statisticsPanel");
this.statisticsPanel.ForeColorTitle = System.Drawing.SystemColors.ControlText;
this.statisticsPanel.Name = "statisticsPanel";
this.statisticsPanel.RightCount = 0;
this.statisticsPanel.Score = 0;
this.statisticsPanel.Timer = 10;
this.statisticsPanel.TimerVisible = true;
this.statisticsPanel.WrongCount = 0;
//
// statusBar
//
resources.ApplyResources(this.statusBar, "statusBar");
this.statusBar.ForeColor = System.Drawing.Color.Red;
this.statusBar.Name = "statusBar";
//
// panelLearningWindowMiddle
//
this.panelLearningWindowMiddle.Controls.Add(this.dockingButtonStack);
this.panelLearningWindowMiddle.Controls.Add(this.gradientPanelMain);
resources.ApplyResources(this.panelLearningWindowMiddle, "panelLearningWindowMiddle");
this.panelLearningWindowMiddle.Name = "panelLearningWindowMiddle";
//
// dockingButtonStack
//
this.dockingButtonStack.BackColor = System.Drawing.Color.Navy;
this.dockingButtonStack.DockingParent = this.gradientPanelMain;
this.dockingButtonStack.ForeColor = System.Drawing.Color.White;
resources.ApplyResources(this.dockingButtonStack, "dockingButtonStack");
this.dockingButtonStack.Name = "dockingButtonStack";
this.dockingButtonStack.PanelBorder = MLifter.Components.PanelBorder.RightSideRounded;
this.dockingButtonStack.Click += new System.EventHandler(this.dockingButtonStack_Click);
//
// gradientPanelMain
//
this.gradientPanelMain.BackColor = System.Drawing.Color.CornflowerBlue;
this.gradientPanelMain.Controls.Add(this.tableLayoutPanelLearningWindowMiddle);
resources.ApplyResources(this.gradientPanelMain, "gradientPanelMain");
this.gradientPanelMain.Gradient = null;
this.gradientPanelMain.LayoutSuspended = false;
this.gradientPanelMain.Name = "gradientPanelMain";
//
// tableLayoutPanelLearningWindowMiddle
//
resources.ApplyResources(this.tableLayoutPanelLearningWindowMiddle, "tableLayoutPanelLearningWindowMiddle");
this.tableLayoutPanelLearningWindowMiddle.Controls.Add(this.splitContainerVertical, 0, 0);
this.tableLayoutPanelLearningWindowMiddle.Controls.Add(this.buttonsPanelMainControl, 0, 1);
this.tableLayoutPanelLearningWindowMiddle.Name = "tableLayoutPanelLearningWindowMiddle";
//
// splitContainerVertical
//
this.splitContainerVertical.BackColor = System.Drawing.Color.Transparent;
resources.ApplyResources(this.splitContainerVertical, "splitContainerVertical");
this.splitContainerVertical.Name = "splitContainerVertical";
//
// splitContainerVertical.Panel1
//
this.splitContainerVertical.Panel1.BackColor = System.Drawing.Color.Transparent;
this.splitContainerVertical.Panel1.Controls.Add(this.questionPanel);
//
// splitContainerVertical.Panel2
//
this.splitContainerVertical.Panel2.Controls.Add(this.answerPanel);
//
// questionPanel
//
this.questionPanel.BackColor = System.Drawing.Color.Transparent;
resources.ApplyResources(this.questionPanel, "questionPanel");
this.questionPanel.Name = "questionPanel";
this.questionPanel.SizeChanged += new System.EventHandler(this.questionPanel_SizeChanged);
//
// answerPanel
//
this.answerPanel.BackColor = System.Drawing.Color.Transparent;
resources.ApplyResources(this.answerPanel, "answerPanel");
this.answerPanel.Name = "answerPanel";
//
// buttonsPanelMainControl
//
this.buttonsPanelMainControl.BackColor = System.Drawing.Color.Transparent;
resources.ApplyResources(this.buttonsPanelMainControl, "buttonsPanelMainControl");
this.buttonsPanelMainControl.Name = "buttonsPanelMainControl";
//
// stackFlow
//
resources.ApplyResources(this.stackFlow, "stackFlow");
this.stackFlow.Name = "stackFlow";
this.stackFlow.SizeChanged += new System.EventHandler(this.stackFlow_SizeChanged);
//
// LearningWindow
//
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Inherit;
this.BackColor = System.Drawing.SystemColors.Control;
this.Controls.Add(this.splitContainerHorizontal);
this.Name = "LearningWindow";
resources.ApplyResources(this, "$this");
this.splitContainerHorizontal.Panel1.ResumeLayout(false);
this.splitContainerHorizontal.Panel2.ResumeLayout(false);
this.splitContainerHorizontal.ResumeLayout(false);
this.tableLayoutPanelMainContent.ResumeLayout(false);
this.panelLearningWindowMiddle.ResumeLayout(false);
this.gradientPanelMain.ResumeLayout(false);
this.tableLayoutPanelLearningWindowMiddle.ResumeLayout(false);
this.splitContainerVertical.Panel1.ResumeLayout(false);
this.splitContainerVertical.Panel2.ResumeLayout(false);
this.splitContainerVertical.ResumeLayout(false);
this.ResumeLayout(false);
}
#endregion
private StatisticsPanel statisticsPanel;
private System.Windows.Forms.SplitContainer splitContainerHorizontal;
private System.Windows.Forms.SplitContainer splitContainerVertical;
private StackFlow stackFlow;
private QuestionPanel questionPanel;
private AnswerPanel answerPanel;
private AudioPlayerComponent audioPlayerComponent;
private UserDialogComponent userDialogComponent;
private StatusBar statusBar;
private ButtonsPanel buttonsPanelMainControl;
private System.Windows.Forms.TableLayoutPanel tableLayoutPanelMainContent;
private MLifter.Components.GradientPanel gradientPanelMain;
private System.Windows.Forms.TableLayoutPanel tableLayoutPanelLearningWindowMiddle;
private System.Windows.Forms.Panel panelLearningWindowMiddle;
private MLifter.Components.DockingButton dockingButtonStack;
}
}
| |
using System;
using UnityEngine;
namespace UnityStandardAssets.ImageEffects
{
[ExecuteInEditMode]
[RequireComponent (typeof(Camera))]
[AddComponentMenu ("Image Effects/Bloom and Glow/Bloom")]
public class Bloom : PostEffectsBase
{
public enum LensFlareStyle
{
Ghosting = 0,
Anamorphic = 1,
Combined = 2,
}
public enum TweakMode
{
Basic = 0,
Complex = 1,
}
public enum HDRBloomMode
{
Auto = 0,
On = 1,
Off = 2,
}
public enum BloomScreenBlendMode
{
Screen = 0,
Add = 1,
}
public enum BloomQuality
{
Cheap = 0,
High = 1,
}
public TweakMode tweakMode = 0;
public BloomScreenBlendMode screenBlendMode = BloomScreenBlendMode.Add;
public HDRBloomMode hdr = HDRBloomMode.Auto;
private bool doHdr = false;
public float sepBlurSpread = 2.5f;
public BloomQuality quality = BloomQuality.High;
public float bloomIntensity = 0.5f;
public float bloomThreshold = 0.5f;
public Color bloomThresholdColor = Color.white;
public int bloomBlurIterations = 2;
public int hollywoodFlareBlurIterations = 2;
public float flareRotation = 0.0f;
public LensFlareStyle lensflareMode = (LensFlareStyle) 1;
public float hollyStretchWidth = 2.5f;
public float lensflareIntensity = 0.0f;
public float lensflareThreshold = 0.3f;
public float lensFlareSaturation = 0.75f;
public Color flareColorA = new Color (0.4f, 0.4f, 0.8f, 0.75f);
public Color flareColorB = new Color (0.4f, 0.8f, 0.8f, 0.75f);
public Color flareColorC = new Color (0.8f, 0.4f, 0.8f, 0.75f);
public Color flareColorD = new Color (0.8f, 0.4f, 0.0f, 0.75f);
public Texture2D lensFlareVignetteMask;
public Shader lensFlareShader;
private Material lensFlareMaterial;
public Shader screenBlendShader;
private Material screenBlend;
public Shader blurAndFlaresShader;
private Material blurAndFlaresMaterial;
public Shader brightPassFilterShader;
private Material brightPassFilterMaterial;
public override bool CheckResources ()
{
CheckSupport (false);
screenBlend = CheckShaderAndCreateMaterial (screenBlendShader, screenBlend);
lensFlareMaterial = CheckShaderAndCreateMaterial(lensFlareShader,lensFlareMaterial);
blurAndFlaresMaterial = CheckShaderAndCreateMaterial (blurAndFlaresShader, blurAndFlaresMaterial);
brightPassFilterMaterial = CheckShaderAndCreateMaterial(brightPassFilterShader, brightPassFilterMaterial);
if (!isSupported)
ReportAutoDisable ();
return isSupported;
}
public void OnRenderImage (RenderTexture source, RenderTexture destination)
{
if (CheckResources()==false)
{
Graphics.Blit (source, destination);
return;
}
// screen blend is not supported when HDR is enabled (will cap values)
doHdr = false;
if (hdr == HDRBloomMode.Auto)
doHdr = source.format == RenderTextureFormat.ARGBHalf && GetComponent<Camera>().allowHDR;
else {
doHdr = hdr == HDRBloomMode.On;
}
doHdr = doHdr && supportHDRTextures;
BloomScreenBlendMode realBlendMode = screenBlendMode;
if (doHdr)
realBlendMode = BloomScreenBlendMode.Add;
var rtFormat= (doHdr) ? RenderTextureFormat.ARGBHalf : RenderTextureFormat.Default;
var rtW2= source.width/2;
var rtH2= source.height/2;
var rtW4= source.width/4;
var rtH4= source.height/4;
float widthOverHeight = (1.0f * source.width) / (1.0f * source.height);
float oneOverBaseSize = 1.0f / 512.0f;
// downsample
RenderTexture quarterRezColor = RenderTexture.GetTemporary (rtW4, rtH4, 0, rtFormat);
RenderTexture halfRezColorDown = RenderTexture.GetTemporary (rtW2, rtH2, 0, rtFormat);
if (quality > BloomQuality.Cheap) {
Graphics.Blit (source, halfRezColorDown, screenBlend, 2);
RenderTexture rtDown4 = RenderTexture.GetTemporary (rtW4, rtH4, 0, rtFormat);
Graphics.Blit (halfRezColorDown, rtDown4, screenBlend, 2);
Graphics.Blit (rtDown4, quarterRezColor, screenBlend, 6);
RenderTexture.ReleaseTemporary(rtDown4);
}
else {
Graphics.Blit (source, halfRezColorDown);
Graphics.Blit (halfRezColorDown, quarterRezColor, screenBlend, 6);
}
RenderTexture.ReleaseTemporary (halfRezColorDown);
// cut colors (thresholding)
RenderTexture secondQuarterRezColor = RenderTexture.GetTemporary (rtW4, rtH4, 0, rtFormat);
BrightFilter (bloomThreshold * bloomThresholdColor, quarterRezColor, secondQuarterRezColor);
// blurring
if (bloomBlurIterations < 1) bloomBlurIterations = 1;
else if (bloomBlurIterations > 10) bloomBlurIterations = 10;
for (int iter = 0; iter < bloomBlurIterations; iter++)
{
float spreadForPass = (1.0f + (iter * 0.25f)) * sepBlurSpread;
// vertical blur
RenderTexture blur4 = RenderTexture.GetTemporary (rtW4, rtH4, 0, rtFormat);
blurAndFlaresMaterial.SetVector ("_Offsets", new Vector4 (0.0f, spreadForPass * oneOverBaseSize, 0.0f, 0.0f));
Graphics.Blit (secondQuarterRezColor, blur4, blurAndFlaresMaterial, 4);
RenderTexture.ReleaseTemporary(secondQuarterRezColor);
secondQuarterRezColor = blur4;
// horizontal blur
blur4 = RenderTexture.GetTemporary (rtW4, rtH4, 0, rtFormat);
blurAndFlaresMaterial.SetVector ("_Offsets", new Vector4 ((spreadForPass / widthOverHeight) * oneOverBaseSize, 0.0f, 0.0f, 0.0f));
Graphics.Blit (secondQuarterRezColor, blur4, blurAndFlaresMaterial, 4);
RenderTexture.ReleaseTemporary (secondQuarterRezColor);
secondQuarterRezColor = blur4;
if (quality > BloomQuality.Cheap)
{
if (iter == 0)
{
Graphics.SetRenderTarget(quarterRezColor);
GL.Clear(false, true, Color.black); // Clear to avoid RT restore
Graphics.Blit (secondQuarterRezColor, quarterRezColor);
}
else
{
quarterRezColor.MarkRestoreExpected(); // using max blending, RT restore expected
Graphics.Blit (secondQuarterRezColor, quarterRezColor, screenBlend, 10);
}
}
}
if (quality > BloomQuality.Cheap)
{
Graphics.SetRenderTarget(secondQuarterRezColor);
GL.Clear(false, true, Color.black); // Clear to avoid RT restore
Graphics.Blit (quarterRezColor, secondQuarterRezColor, screenBlend, 6);
}
// lens flares: ghosting, anamorphic or both (ghosted anamorphic flares)
if (lensflareIntensity > Mathf.Epsilon)
{
RenderTexture rtFlares4 = RenderTexture.GetTemporary (rtW4, rtH4, 0, rtFormat);
if (lensflareMode == 0)
{
// ghosting only
BrightFilter (lensflareThreshold, secondQuarterRezColor, rtFlares4);
if (quality > BloomQuality.Cheap)
{
// smooth a little
blurAndFlaresMaterial.SetVector ("_Offsets", new Vector4 (0.0f, (1.5f) / (1.0f * quarterRezColor.height), 0.0f, 0.0f));
Graphics.SetRenderTarget(quarterRezColor);
GL.Clear(false, true, Color.black); // Clear to avoid RT restore
Graphics.Blit (rtFlares4, quarterRezColor, blurAndFlaresMaterial, 4);
blurAndFlaresMaterial.SetVector ("_Offsets", new Vector4 ((1.5f) / (1.0f * quarterRezColor.width), 0.0f, 0.0f, 0.0f));
Graphics.SetRenderTarget(rtFlares4);
GL.Clear(false, true, Color.black); // Clear to avoid RT restore
Graphics.Blit (quarterRezColor, rtFlares4, blurAndFlaresMaterial, 4);
}
// no ugly edges!
Vignette (0.975f, rtFlares4, rtFlares4);
BlendFlares (rtFlares4, secondQuarterRezColor);
}
else
{
//Vignette (0.975ff, rtFlares4, rtFlares4);
//DrawBorder(rtFlares4, screenBlend, 8);
float flareXRot = 1.0f * Mathf.Cos(flareRotation);
float flareyRot = 1.0f * Mathf.Sin(flareRotation);
float stretchWidth = (hollyStretchWidth * 1.0f / widthOverHeight) * oneOverBaseSize;
blurAndFlaresMaterial.SetVector ("_Offsets", new Vector4 (flareXRot, flareyRot, 0.0f, 0.0f));
blurAndFlaresMaterial.SetVector ("_Threshhold", new Vector4 (lensflareThreshold, 1.0f, 0.0f, 0.0f));
blurAndFlaresMaterial.SetVector ("_TintColor", new Vector4 (flareColorA.r, flareColorA.g, flareColorA.b, flareColorA.a) * flareColorA.a * lensflareIntensity);
blurAndFlaresMaterial.SetFloat ("_Saturation", lensFlareSaturation);
// "pre and cut"
quarterRezColor.DiscardContents();
Graphics.Blit (rtFlares4, quarterRezColor, blurAndFlaresMaterial, 2);
// "post"
rtFlares4.DiscardContents();
Graphics.Blit (quarterRezColor, rtFlares4, blurAndFlaresMaterial, 3);
blurAndFlaresMaterial.SetVector ("_Offsets", new Vector4 (flareXRot * stretchWidth, flareyRot * stretchWidth, 0.0f, 0.0f));
// stretch 1st
blurAndFlaresMaterial.SetFloat ("_StretchWidth", hollyStretchWidth);
quarterRezColor.DiscardContents();
Graphics.Blit (rtFlares4, quarterRezColor, blurAndFlaresMaterial, 1);
// stretch 2nd
blurAndFlaresMaterial.SetFloat ("_StretchWidth", hollyStretchWidth * 2.0f);
rtFlares4.DiscardContents();
Graphics.Blit (quarterRezColor, rtFlares4, blurAndFlaresMaterial, 1);
// stretch 3rd
blurAndFlaresMaterial.SetFloat ("_StretchWidth", hollyStretchWidth * 4.0f);
quarterRezColor.DiscardContents();
Graphics.Blit (rtFlares4, quarterRezColor, blurAndFlaresMaterial, 1);
// additional blur passes
for (int iter = 0; iter < hollywoodFlareBlurIterations; iter++)
{
stretchWidth = (hollyStretchWidth * 2.0f / widthOverHeight) * oneOverBaseSize;
blurAndFlaresMaterial.SetVector ("_Offsets", new Vector4 (stretchWidth * flareXRot, stretchWidth * flareyRot, 0.0f, 0.0f));
rtFlares4.DiscardContents();
Graphics.Blit (quarterRezColor, rtFlares4, blurAndFlaresMaterial, 4);
blurAndFlaresMaterial.SetVector ("_Offsets", new Vector4 (stretchWidth * flareXRot, stretchWidth * flareyRot, 0.0f, 0.0f));
quarterRezColor.DiscardContents();
Graphics.Blit (rtFlares4, quarterRezColor, blurAndFlaresMaterial, 4);
}
if (lensflareMode == (LensFlareStyle) 1)
// anamorphic lens flares
AddTo (1.0f, quarterRezColor, secondQuarterRezColor);
else
{
// "combined" lens flares
Vignette (1.0f, quarterRezColor, rtFlares4);
BlendFlares (rtFlares4, quarterRezColor);
AddTo (1.0f, quarterRezColor, secondQuarterRezColor);
}
}
RenderTexture.ReleaseTemporary (rtFlares4);
}
int blendPass = (int) realBlendMode;
//if (Mathf.Abs(chromaticBloom) < Mathf.Epsilon)
// blendPass += 4;
screenBlend.SetFloat ("_Intensity", bloomIntensity);
screenBlend.SetTexture ("_ColorBuffer", source);
if (quality > BloomQuality.Cheap)
{
RenderTexture halfRezColorUp = RenderTexture.GetTemporary (rtW2, rtH2, 0, rtFormat);
Graphics.Blit (secondQuarterRezColor, halfRezColorUp);
Graphics.Blit (halfRezColorUp, destination, screenBlend, blendPass);
RenderTexture.ReleaseTemporary (halfRezColorUp);
}
else
Graphics.Blit (secondQuarterRezColor, destination, screenBlend, blendPass);
RenderTexture.ReleaseTemporary (quarterRezColor);
RenderTexture.ReleaseTemporary (secondQuarterRezColor);
}
private void AddTo (float intensity_, RenderTexture from, RenderTexture to)
{
screenBlend.SetFloat ("_Intensity", intensity_);
to.MarkRestoreExpected(); // additive blending, RT restore expected
Graphics.Blit (from, to, screenBlend, 9);
}
private void BlendFlares (RenderTexture from, RenderTexture to)
{
lensFlareMaterial.SetVector ("colorA", new Vector4 (flareColorA.r, flareColorA.g, flareColorA.b, flareColorA.a) * lensflareIntensity);
lensFlareMaterial.SetVector ("colorB", new Vector4 (flareColorB.r, flareColorB.g, flareColorB.b, flareColorB.a) * lensflareIntensity);
lensFlareMaterial.SetVector ("colorC", new Vector4 (flareColorC.r, flareColorC.g, flareColorC.b, flareColorC.a) * lensflareIntensity);
lensFlareMaterial.SetVector ("colorD", new Vector4 (flareColorD.r, flareColorD.g, flareColorD.b, flareColorD.a) * lensflareIntensity);
to.MarkRestoreExpected(); // additive blending, RT restore expected
Graphics.Blit (from, to, lensFlareMaterial);
}
private void BrightFilter (float thresh, RenderTexture from, RenderTexture to)
{
brightPassFilterMaterial.SetVector ("_Threshhold", new Vector4 (thresh, thresh, thresh, thresh));
Graphics.Blit (from, to, brightPassFilterMaterial, 0);
}
private void BrightFilter (Color threshColor, RenderTexture from, RenderTexture to)
{
brightPassFilterMaterial.SetVector ("_Threshhold", threshColor);
Graphics.Blit (from, to, brightPassFilterMaterial, 1);
}
private void Vignette (float amount, RenderTexture from, RenderTexture to)
{
if (lensFlareVignetteMask)
{
screenBlend.SetTexture ("_ColorBuffer", lensFlareVignetteMask);
to.MarkRestoreExpected(); // using blending, RT restore expected
Graphics.Blit (from == to ? null : from, to, screenBlend, from == to ? 7 : 3);
}
else if (from != to)
{
Graphics.SetRenderTarget (to);
GL.Clear(false, true, Color.black); // clear destination to avoid RT restore
Graphics.Blit (from, to);
}
}
}
}
| |
#region License
/*---------------------------------------------------------------------------------*\
Distributed under the terms of an MIT-style license:
The MIT License
Copyright (c) 2006-2010 Stephen M. McKamey
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 License
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Globalization;
using System.IO;
using System.Reflection;
using System.Text;
#if !UNITY3D
using System.Xml;
#endif
#if WINDOWS_STORE
using TP = System.Reflection.TypeInfo;
#else
using TP = System.Type;
#endif
namespace Pathfinding.Serialization.JsonFx
{
/// <summary>
/// Writer for producing JSON data
/// </summary>
public class JsonWriter : IDisposable
{
#region Constants
public const string JsonMimeType = "application/json";
public const string JsonFileExtension = ".json";
private const string AnonymousTypePrefix = "<>f__AnonymousType";
private const string ErrorMaxDepth = "The maxiumum depth of {0} was exceeded. Check for cycles in object graph.";
private const string ErrorIDictionaryEnumerator = "Types which implement Generic IDictionary<TKey, TValue> must have an IEnumerator which implements IDictionaryEnumerator. ({0})";
private const BindingFlags defaultBinding = BindingFlags.Default;
private const BindingFlags allBinding = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic;
#endregion Constants
#region Fields
private readonly TextWriter Writer;
private JsonWriterSettings settings;
private int depth;
private Dictionary<object,int> previouslySerializedObjects;
#endregion Fields
#region Init
/// <summary>
/// Ctor
/// </summary>
/// <param name="output">TextWriter for writing</param>
public JsonWriter(TextWriter output)
: this(output, new JsonWriterSettings())
{
}
/// <summary>
/// Ctor
/// </summary>
/// <param name="output">TextWriter for writing</param>
/// <param name="settings">JsonWriterSettings</param>
public JsonWriter (TextWriter output, JsonWriterSettings settings)
{
if (output == null) {
throw new ArgumentNullException ("output");
}
if (settings == null) {
throw new ArgumentNullException ("settings");
}
this.Writer = output;
this.settings = settings;
this.Writer.NewLine = this.settings.NewLine;
if (settings.HandleCyclicReferences)
{
this.previouslySerializedObjects = new Dictionary<object, int> ();
}
}
/// <summary>
/// Ctor
/// </summary>
/// <param name="output">Stream for writing</param>
public JsonWriter(Stream output)
: this(output, new JsonWriterSettings())
{
}
/// <summary>
/// Ctor
/// </summary>
/// <param name="output">Stream for writing</param>
/// <param name="settings">JsonWriterSettings</param>
public JsonWriter(Stream output, JsonWriterSettings settings)
{
if (output == null)
{
throw new ArgumentNullException("output");
}
if (settings == null)
{
throw new ArgumentNullException("settings");
}
this.Writer = new StreamWriter(output, Encoding.UTF8);
this.settings = settings;
this.Writer.NewLine = this.settings.NewLine;
}
/// <summary>
/// Ctor
/// </summary>
/// <param name="output">file name for writing</param>
public JsonWriter(string outputFileName)
: this(outputFileName, new JsonWriterSettings())
{
}
/// <summary>
/// Ctor
/// </summary>
/// <param name="output">file name for writing</param>
/// <param name="settings">JsonWriterSettings</param>
public JsonWriter(string outputFileName, JsonWriterSettings settings)
{
if (outputFileName == null)
{
throw new ArgumentNullException("outputFileName");
}
if (settings == null)
{
throw new ArgumentNullException("settings");
}
Stream stream = new FileStream(outputFileName, FileMode.Create, FileAccess.Write, FileShare.Read);
this.Writer = new StreamWriter(stream, Encoding.UTF8);
this.settings = settings;
this.Writer.NewLine = this.settings.NewLine;
}
/// <summary>
/// Ctor
/// </summary>
/// <param name="output">StringBuilder for appending</param>
public JsonWriter(StringBuilder output)
: this(output, new JsonWriterSettings())
{
}
/// <summary>
/// Ctor
/// </summary>
/// <param name="output">StringBuilder for appending</param>
/// <param name="settings">JsonWriterSettings</param>
public JsonWriter(StringBuilder output, JsonWriterSettings settings)
{
if (output == null)
{
throw new ArgumentNullException("output");
}
if (settings == null)
{
throw new ArgumentNullException("settings");
}
this.Writer = new StringWriter(output, System.Globalization.CultureInfo.InvariantCulture);
this.settings = settings;
this.Writer.NewLine = this.settings.NewLine;
}
#endregion Init
#region Properties
/// <summary>
/// Gets and sets the property name used for type hinting
/// </summary>
[Obsolete("This has been deprecated in favor of JsonWriterSettings object")]
public string TypeHintName
{
get { return this.settings.TypeHintName; }
set { this.settings.TypeHintName = value; }
}
/// <summary>
/// Gets and sets if JSON will be formatted for human reading
/// </summary>
[Obsolete("This has been deprecated in favor of JsonWriterSettings object")]
public bool PrettyPrint
{
get { return this.settings.PrettyPrint; }
set { this.settings.PrettyPrint = value; }
}
/// <summary>
/// Gets and sets the string to use for indentation
/// </summary>
[Obsolete("This has been deprecated in favor of JsonWriterSettings object")]
public string Tab
{
get { return this.settings.Tab; }
set { this.settings.Tab = value; }
}
/// <summary>
/// Gets and sets the line terminator string
/// </summary>
[Obsolete("This has been deprecated in favor of JsonWriterSettings object")]
public string NewLine
{
get { return this.settings.NewLine; }
set { this.Writer.NewLine = this.settings.NewLine = value; }
}
/// <summary>
/// Gets the current nesting depth
/// </summary>
protected int Depth
{
get { return this.depth; }
}
/// <summary>
/// Gets and sets the maximum depth to be serialized
/// </summary>
[Obsolete("This has been deprecated in favor of JsonWriterSettings object")]
public int MaxDepth
{
get { return this.settings.MaxDepth; }
set { this.settings.MaxDepth = value; }
}
/// <summary>
/// Gets and sets if should use XmlSerialization Attributes
/// </summary>
/// <remarks>
/// Respects XmlIgnoreAttribute, ...
/// </remarks>
[Obsolete("This has been deprecated in favor of JsonWriterSettings object")]
public bool UseXmlSerializationAttributes
{
get { return this.settings.UseXmlSerializationAttributes; }
set { this.settings.UseXmlSerializationAttributes = value; }
}
/// <summary>
/// Gets and sets a proxy formatter to use for DateTime serialization
/// </summary>
[Obsolete("This has been deprecated in favor of JsonWriterSettings object")]
public WriteDelegate<DateTime> DateTimeSerializer
{
get { return this.settings.DateTimeSerializer; }
set { this.settings.DateTimeSerializer = value; }
}
/// <summary>
/// Gets the underlying TextWriter
/// </summary>
public TextWriter TextWriter
{
get { return this.Writer; }
}
/// <summary>
/// Gets and sets the JsonWriterSettings
/// </summary>
public JsonWriterSettings Settings
{
get { return this.settings; }
set
{
if (value == null)
{
value = new JsonWriterSettings();
}
this.settings = value;
}
}
#endregion Properties
#region Static Methods
/// <summary>
/// A helper method for serializing an object to JSON
/// </summary>
/// <param name="value"></param>
/// <returns></returns>
public static string Serialize(object value)
{
StringBuilder output = new StringBuilder();
using (JsonWriter writer = new JsonWriter(output))
{
writer.Write(value);
}
return output.ToString();
}
#endregion Static Methods
#region Public Methods
public void Write(object value)
{
this.Write(value, false);
}
protected virtual void Write(object value, bool isProperty)
{
if (isProperty && this.settings.PrettyPrint)
{
this.Writer.Write(' ');
}
if (value == null)
{
this.Writer.Write(JsonReader.LiteralNull);
return;
}
if (value is IJsonSerializable)
{
try
{
if (isProperty)
{
this.depth++;
if (this.depth > this.settings.MaxDepth)
{
throw new JsonSerializationException(String.Format(JsonWriter.ErrorMaxDepth, this.settings.MaxDepth));
}
this.WriteLine();
}
((IJsonSerializable)value).WriteJson(this);
}
finally
{
if (isProperty)
{
this.depth--;
}
}
return;
}
// must test enumerations before value types
if (value is Enum)
{
this.Write((Enum)value);
return;
}
// Type.GetTypeCode() allows us to more efficiently switch type
// plus cannot use 'is' for ValueTypes
Type type = value.GetType();
JsonConverter converter = this.Settings.GetConverter (type);
if (converter != null) {
converter.Write (this, type,value);
return;
}
switch (Type.GetTypeCode(type))
{
case TypeCode.Boolean:
{
this.Write((Boolean)value);
return;
}
case TypeCode.Byte:
{
this.Write((Byte)value);
return;
}
case TypeCode.Char:
{
this.Write((Char)value);
return;
}
case TypeCode.DateTime:
{
this.Write((DateTime)value);
return;
}
case TypeCode.DBNull:
case TypeCode.Empty:
{
this.Writer.Write(JsonReader.LiteralNull);
return;
}
case TypeCode.Decimal:
{
// From MSDN:
// Conversions from Char, SByte, Int16, Int32, Int64, Byte, UInt16, UInt32, and UInt64
// to Decimal are widening conversions that never lose information or throw exceptions.
// Conversions from Single or Double to Decimal throw an OverflowException
// if the result of the conversion is not representable as a Decimal.
this.Write((Decimal)value);
return;
}
case TypeCode.Double:
{
this.Write((Double)value);
return;
}
case TypeCode.Int16:
{
this.Write((Int16)value);
return;
}
case TypeCode.Int32:
{
this.Write((Int32)value);
return;
}
case TypeCode.Int64:
{
this.Write((Int64)value);
return;
}
case TypeCode.SByte:
{
this.Write((SByte)value);
return;
}
case TypeCode.Single:
{
this.Write((Single)value);
return;
}
case TypeCode.String:
{
this.Write((String)value);
return;
}
case TypeCode.UInt16:
{
this.Write((UInt16)value);
return;
}
case TypeCode.UInt32:
{
this.Write((UInt32)value);
return;
}
case TypeCode.UInt64:
{
this.Write((UInt64)value);
return;
}
default:
case TypeCode.Object:
{
// all others must be explicitly tested
break;
}
}
if (value is Guid)
{
this.Write((Guid)value);
return;
}
if (value is Uri)
{
this.Write((Uri)value);
return;
}
if (value is TimeSpan)
{
this.Write((TimeSpan)value);
return;
}
if (value is Version)
{
this.Write((Version)value);
return;
}
// IDictionary test must happen BEFORE IEnumerable test
// since IDictionary implements IEnumerable
if (value is IDictionary)
{
try
{
if (isProperty)
{
this.depth++;
if (this.depth > this.settings.MaxDepth)
{
throw new JsonSerializationException(String.Format(JsonWriter.ErrorMaxDepth, this.settings.MaxDepth));
}
this.WriteLine();
}
this.WriteObject((IDictionary)value);
}
finally
{
if (isProperty)
{
this.depth--;
}
}
return;
}
if (type.GetInterface(JsonReader.TypeGenericIDictionary) != null)
{
try
{
if (isProperty)
{
this.depth++;
if (this.depth > this.settings.MaxDepth)
{
throw new JsonSerializationException(String.Format(JsonWriter.ErrorMaxDepth, this.settings.MaxDepth));
}
this.WriteLine();
}
this.WriteDictionary((IEnumerable)value);
}
finally
{
if (isProperty)
{
this.depth--;
}
}
return;
}
// IDictionary test must happen BEFORE IEnumerable test
// since IDictionary implements IEnumerable
if (value is IEnumerable)
{
#if !UNITY3D
if (value is XmlNode)
{
this.Write((System.Xml.XmlNode)value);
return;
}
#endif
try
{
if (isProperty)
{
this.depth++;
if (this.depth > this.settings.MaxDepth)
{
throw new JsonSerializationException(String.Format(JsonWriter.ErrorMaxDepth, this.settings.MaxDepth));
}
this.WriteLine();
}
this.WriteArray((IEnumerable)value);
}
finally
{
if (isProperty)
{
this.depth--;
}
}
return;
}
// structs and classes
try
{
if (isProperty)
{
this.depth++;
if (this.depth > this.settings.MaxDepth)
{
throw new JsonSerializationException(String.Format(JsonWriter.ErrorMaxDepth, this.settings.MaxDepth));
}
this.WriteLine();
}
this.WriteObject(value, type,false);
}
finally
{
if (isProperty)
{
this.depth--;
}
}
}
public virtual void WriteBase64(byte[] value)
{
this.Write(Convert.ToBase64String(value));
}
public virtual void WriteHexString(byte[] value)
{
if (value == null || value.Length == 0)
{
this.Write(String.Empty);
return;
}
StringBuilder builder = new StringBuilder();
// Loop through each byte of the binary data
// and format each one as a hexadecimal string
for (int i=0; i<value.Length; i++)
{
builder.Append(value[i].ToString("x2"));
}
// the hexadecimal string
this.Write(builder.ToString());
}
public virtual void Write(DateTime value)
{
if (this.settings.DateTimeSerializer != null)
{
this.settings.DateTimeSerializer(this, value);
return;
}
switch (value.Kind)
{
case DateTimeKind.Local:
{
value = value.ToUniversalTime();
goto case DateTimeKind.Utc;
}
case DateTimeKind.Utc:
{
// UTC DateTime in ISO-8601
this.Write(String.Format("{0:s}Z", value));
break;
}
default:
{
// DateTime in ISO-8601
this.Write(String.Format("{0:s}", value));
break;
}
}
}
public virtual void Write(Guid value)
{
this.Write(value.ToString("D"));
}
public virtual void Write(Enum value)
{
string enumName = null;
Type type = value.GetType();
if (type.IsDefined(typeof(FlagsAttribute), true) && !Enum.IsDefined(type, value))
{
Enum[] flags = JsonWriter.GetFlagList(type, value);
string[] flagNames = new string[flags.Length];
for (int i=0; i<flags.Length; i++)
{
flagNames[i] = JsonNameAttribute.GetJsonName(flags[i]);
if (String.IsNullOrEmpty(flagNames[i]))
{
flagNames[i] = flags[i].ToString("f");
}
}
enumName = String.Join(", ", flagNames);
}
else
{
enumName = JsonNameAttribute.GetJsonName(value);
if (String.IsNullOrEmpty(enumName))
{
enumName = value.ToString("f");
}
}
this.Write(enumName);
}
public virtual void Write(string value)
{
if (value == null)
{
this.Writer.Write(JsonReader.LiteralNull);
return;
}
int start = 0,
length = value.Length;
this.Writer.Write(JsonReader.OperatorStringDelim);
for (int i=start; i<length; i++)
{
char ch = value[i];
if (ch <= '\u001F' ||
ch >= '\u007F' ||
ch == '<' || // improves compatibility within script blocks
ch == JsonReader.OperatorStringDelim ||
ch == JsonReader.OperatorCharEscape)
{
if (i > start)
{
this.Writer.Write(value.Substring(start, i-start));
}
start = i+1;
switch (ch)
{
case JsonReader.OperatorStringDelim:
case JsonReader.OperatorCharEscape:
{
this.Writer.Write(JsonReader.OperatorCharEscape);
this.Writer.Write(ch);
continue;
}
case '\b':
{
this.Writer.Write("\\b");
continue;
}
case '\f':
{
this.Writer.Write("\\f");
continue;
}
case '\n':
{
this.Writer.Write("\\n");
continue;
}
case '\r':
{
this.Writer.Write("\\r");
continue;
}
case '\t':
{
this.Writer.Write("\\t");
continue;
}
default:
{
if (char.IsSurrogate(ch))
{
this.Writer.Write("\\u");
this.Writer.Write(((int)ch).ToString("x4"));
continue;
}
else
{
this.Writer.Write("\\u");
this.Writer.Write(Char.ConvertToUtf32(value, i).ToString("X4"));
continue;
}
}
}
}
}
if (length > start)
{
this.Writer.Write(value.Substring(start, length-start));
}
this.Writer.Write(JsonReader.OperatorStringDelim);
}
#endregion Public Methods
#region Primative Writer Methods
public virtual void Write(bool value)
{
this.Writer.Write(value ? JsonReader.LiteralTrue : JsonReader.LiteralFalse);
}
public virtual void Write(byte value)
{
this.Writer.Write(value.ToString("g", CultureInfo.InvariantCulture));
}
public virtual void Write(sbyte value)
{
this.Writer.Write(value.ToString("g", CultureInfo.InvariantCulture));
}
public virtual void Write(short value)
{
this.Writer.Write(value.ToString("g", CultureInfo.InvariantCulture));
}
public virtual void Write(ushort value)
{
this.Writer.Write(value.ToString("g", CultureInfo.InvariantCulture));
}
public virtual void Write(int value)
{
this.Writer.Write(value.ToString("g", CultureInfo.InvariantCulture));
}
public virtual void Write(uint value)
{
if (this.InvalidIeee754(value))
{
// emit as string since Number cannot represent
this.Write(value.ToString("g", CultureInfo.InvariantCulture));
return;
}
this.Writer.Write(value.ToString("g", CultureInfo.InvariantCulture));
}
public virtual void Write(long value)
{
if (this.InvalidIeee754(value))
{
// emit as string since Number cannot represent
this.Write(value.ToString("g", CultureInfo.InvariantCulture));
return;
}
this.Writer.Write(value.ToString("g", CultureInfo.InvariantCulture));
}
public virtual void Write(ulong value)
{
if (this.InvalidIeee754(value))
{
// emit as string since Number cannot represent
this.Write(value.ToString("g", CultureInfo.InvariantCulture));
return;
}
this.Writer.Write(value.ToString("g", CultureInfo.InvariantCulture));
}
public virtual void Write(float value)
{
if (Single.IsNaN(value) || Single.IsInfinity(value))
{
this.Writer.Write(JsonReader.LiteralNull);
}
else
{
this.Writer.Write(value.ToString("r", CultureInfo.InvariantCulture));
}
}
public virtual void Write(double value)
{
if (Double.IsNaN(value) || Double.IsInfinity(value))
{
this.Writer.Write(JsonReader.LiteralNull);
}
else
{
this.Writer.Write(value.ToString("r", CultureInfo.InvariantCulture));
}
}
public virtual void Write(decimal value)
{
if (this.InvalidIeee754(value))
{
// emit as string since Number cannot represent
this.Write(value.ToString("g", CultureInfo.InvariantCulture));
return;
}
this.Writer.Write(value.ToString("g", CultureInfo.InvariantCulture));
}
public virtual void Write(char value)
{
this.Write(new String(value, 1));
}
public virtual void Write(TimeSpan value)
{
this.Write(value.Ticks);
}
public virtual void Write(Uri value)
{
this.Write(value.ToString());
}
public virtual void Write(Version value)
{
this.Write(value.ToString());
}
#if !UNITY3D
public virtual void Write(XmlNode value)
{
// TODO: auto-translate XML to JsonML
this.Write(value.OuterXml);
}
#endif
#endregion Primative Writer Methods
#region Writer Methods
protected internal virtual void WriteArray(IEnumerable value)
{
bool appendDelim = false;
this.Writer.Write(JsonReader.OperatorArrayStart);
this.depth++;
if (this.depth > this.settings.MaxDepth)
{
throw new JsonSerializationException(String.Format(JsonWriter.ErrorMaxDepth, this.settings.MaxDepth));
}
try
{
foreach (object item in value)
{
if (appendDelim)
{
this.WriteArrayItemDelim();
}
else
{
appendDelim = true;
}
this.WriteLine();
this.WriteArrayItem(item);
}
}
finally
{
this.depth--;
}
if (appendDelim)
{
this.WriteLine();
}
this.Writer.Write(JsonReader.OperatorArrayEnd);
}
protected virtual void WriteArrayItem(object item)
{
this.Write(item, false);
}
protected virtual void WriteObject(IDictionary value)
{
this.WriteDictionary((IEnumerable)value);
}
protected virtual void WriteDictionary(IEnumerable value)
{
IDictionaryEnumerator enumerator = value.GetEnumerator() as IDictionaryEnumerator;
if (enumerator == null)
{
throw new JsonSerializationException(String.Format(JsonWriter.ErrorIDictionaryEnumerator, value.GetType()));
}
bool appendDelim = false;
if (settings.HandleCyclicReferences)
{
int prevIndex = 0;
if (this.previouslySerializedObjects.TryGetValue (value, out prevIndex)) {
this.Writer.Write(JsonReader.OperatorObjectStart);
this.WriteObjectProperty("@ref", prevIndex);
this.WriteLine();
this.Writer.Write(JsonReader.OperatorObjectEnd);
return;
} else {
this.previouslySerializedObjects.Add (value, this.previouslySerializedObjects.Count);
}
}
this.Writer.Write(JsonReader.OperatorObjectStart);
this.depth++;
if (this.depth > this.settings.MaxDepth)
{
throw new JsonSerializationException(String.Format(JsonWriter.ErrorMaxDepth, this.settings.MaxDepth));
}
try
{
while (enumerator.MoveNext())
{
if (appendDelim)
{
this.WriteObjectPropertyDelim();
}
else
{
appendDelim = true;
}
this.WriteObjectProperty(Convert.ToString(enumerator.Entry.Key), enumerator.Entry.Value);
}
}
finally
{
this.depth--;
}
if (appendDelim)
{
this.WriteLine();
}
this.Writer.Write(JsonReader.OperatorObjectEnd);
}
private void WriteObjectProperty(string key, object value)
{
this.WriteLine();
this.WriteObjectPropertyName(key);
this.Writer.Write(JsonReader.OperatorNameDelim);
this.WriteObjectPropertyValue(value);
}
protected virtual void WriteObjectPropertyName(string name)
{
this.Write(name);
}
protected virtual void WriteObjectPropertyValue(object value)
{
this.Write(value, true);
}
protected virtual void WriteObject(object value, Type type, bool serializePrivate)
{
bool appendDelim = false;
if (settings.HandleCyclicReferences && !type.IsValueType)
{
int prevIndex = 0;
if (this.previouslySerializedObjects.TryGetValue (value, out prevIndex)) {
this.Writer.Write(JsonReader.OperatorObjectStart);
this.WriteObjectProperty("@ref", prevIndex);
this.WriteLine();
this.Writer.Write(JsonReader.OperatorObjectEnd);
return;
} else {
this.previouslySerializedObjects.Add (value, this.previouslySerializedObjects.Count);
}
}
this.Writer.Write(JsonReader.OperatorObjectStart);
this.depth++;
if (this.depth > this.settings.MaxDepth)
{
throw new JsonSerializationException(String.Format(JsonWriter.ErrorMaxDepth, this.settings.MaxDepth));
}
try
{
if (!String.IsNullOrEmpty(this.settings.TypeHintName))
{
if (appendDelim)
{
this.WriteObjectPropertyDelim();
}
else
{
appendDelim = true;
}
this.WriteObjectProperty(this.settings.TypeHintName, type.FullName+", "+type.Assembly.GetName().Name);
}
bool anonymousType = type.IsGenericType && type.Name.StartsWith(JsonWriter.AnonymousTypePrefix);
// serialize public properties
PropertyInfo[] properties = type.GetProperties();
foreach (PropertyInfo property in properties)
{
if (!property.CanRead) {
if (Settings.DebugMode)
Console.WriteLine ("Cannot serialize "+property.Name+" : cannot read");
continue;
}
if (!property.CanWrite && !anonymousType) {
if (Settings.DebugMode)
Console.WriteLine ("Cannot serialize "+property.Name+" : cannot write");
continue;
}
if (this.IsIgnored(type, property, value)) {
if (Settings.DebugMode)
Console.WriteLine ("Cannot serialize "+property.Name+" : is ignored by settings");
continue;
}
if (property.GetIndexParameters ().Length != 0) {
if (Settings.DebugMode)
Console.WriteLine ("Cannot serialize "+property.Name+" : is indexed");
continue;
}
object propertyValue = property.GetValue(value, null);
if (this.IsDefaultValue(property, propertyValue)) {
if (Settings.DebugMode)
Console.WriteLine ("Cannot serialize "+property.Name+" : is default value");
continue;
}
if (appendDelim)
this.WriteObjectPropertyDelim();
else
appendDelim = true;
// use Attributes here to control naming
string propertyName = JsonNameAttribute.GetJsonName(property);
if (String.IsNullOrEmpty(propertyName))
propertyName = property.Name;
this.WriteObjectProperty(propertyName, propertyValue);
}
// serialize public fields
FieldInfo[] fields = type.GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
foreach (FieldInfo field in fields)
{
if (field.IsStatic || (!field.IsPublic && field.GetCustomAttributes(typeof(JsonMemberAttribute),true).Length == 0)) {
if (Settings.DebugMode)
Console.WriteLine ("Cannot serialize "+field.Name+" : not public or is static (and does not have a JsonMember attribute)");
continue;
}
if (this.IsIgnored(type, field, value)) {
if (Settings.DebugMode)
Console.WriteLine ("Cannot serialize "+field.Name+" : ignored by settings");
continue;
}
object fieldValue = field.GetValue(value);
if (this.IsDefaultValue(field, fieldValue)) {
if (Settings.DebugMode)
Console.WriteLine ("Cannot serialize "+field.Name+" : is default value");
continue;
}
if (appendDelim)
{
this.WriteObjectPropertyDelim();
this.WriteLine();
} else
{
appendDelim = true;
}
// use Attributes here to control naming
string fieldName = JsonNameAttribute.GetJsonName(field);
if (String.IsNullOrEmpty(fieldName))
fieldName = field.Name;
this.WriteObjectProperty(fieldName, fieldValue);
}
}
finally
{
this.depth--;
}
if (appendDelim)
this.WriteLine();
this.Writer.Write(JsonReader.OperatorObjectEnd);
}
protected virtual void WriteArrayItemDelim()
{
this.Writer.Write(JsonReader.OperatorValueDelim);
}
protected virtual void WriteObjectPropertyDelim()
{
this.Writer.Write(JsonReader.OperatorValueDelim);
}
protected virtual void WriteLine()
{
if (!this.settings.PrettyPrint)
{
return;
}
this.Writer.WriteLine();
for (int i=0; i<this.depth; i++)
{
this.Writer.Write(this.settings.Tab);
}
}
#endregion Writer Methods
#region Private Methods
/// <summary>
/// Determines if the property or field should not be serialized.
/// </summary>
/// <param name="objType"></param>
/// <param name="member"></param>
/// <param name="value"></param>
/// <returns></returns>
/// <remarks>
/// Checks these in order, if any returns true then this is true:
/// - is flagged with the JsonIgnoreAttribute property
/// - has a JsonSpecifiedProperty which returns false
/// </remarks>
private bool IsIgnored(Type objType, MemberInfo member, object obj)
{
if (JsonIgnoreAttribute.IsJsonIgnore(member))
{
return true;
}
string specifiedProperty = JsonSpecifiedPropertyAttribute.GetJsonSpecifiedProperty(member);
if (!String.IsNullOrEmpty(specifiedProperty))
{
PropertyInfo specProp = objType.GetProperty(specifiedProperty);
if (specProp != null)
{
object isSpecified = specProp.GetValue(obj, null);
if (isSpecified is Boolean && !Convert.ToBoolean(isSpecified))
{
return true;
}
}
}
//If the class is specified as opt-in serialization only, members must have the JsonMember attribute
if (objType.GetCustomAttributes (typeof(JsonOptInAttribute),true).Length != 0) {
if (member.GetCustomAttributes(typeof(JsonMemberAttribute),true).Length == 0) {
return true;
}
}
if (this.settings.UseXmlSerializationAttributes)
{
if (JsonIgnoreAttribute.IsXmlIgnore(member))
{
return true;
}
PropertyInfo specProp = objType.GetProperty(member.Name+"Specified");
if (specProp != null)
{
object isSpecified = specProp.GetValue(obj, null);
if (isSpecified is Boolean && !Convert.ToBoolean(isSpecified))
{
return true;
}
}
}
return false;
}
/// <summary>
/// Determines if the member value matches the DefaultValue attribute
/// </summary>
/// <returns>if has a value equivalent to the DefaultValueAttribute</returns>
private bool IsDefaultValue(MemberInfo member, object value)
{
DefaultValueAttribute attribute = Attribute.GetCustomAttribute(member, typeof(DefaultValueAttribute)) as DefaultValueAttribute;
if (attribute == null)
{
return false;
}
if (attribute.Value == null)
{
return (value == null);
}
return (attribute.Value.Equals(value));
}
#endregion Private Methods
#region Utility Methods
/// <summary>
/// Splits a bitwise-OR'd set of enums into a list.
/// </summary>
/// <param name="enumType">the enum type</param>
/// <param name="value">the combined value</param>
/// <returns>list of flag enums</returns>
/// <remarks>
/// from PseudoCode.EnumHelper
/// </remarks>
private static Enum[] GetFlagList(Type enumType, object value)
{
ulong longVal = Convert.ToUInt64(value);
Array enumValues = Enum.GetValues(enumType);
List<Enum> enums = new List<Enum>(enumValues.Length);
// check for empty
if (longVal == 0L)
{
// Return the value of empty, or zero if none exists
enums.Add((Enum)Convert.ChangeType(value, enumType));
return enums.ToArray();
}
for (int i = enumValues.Length-1; i >= 0; i--)
{
ulong enumValue = Convert.ToUInt64(enumValues.GetValue(i));
if ((i == 0) && (enumValue == 0L))
{
continue;
}
// matches a value in enumeration
if ((longVal & enumValue) == enumValue)
{
// remove from val
longVal -= enumValue;
// add enum to list
enums.Add(enumValues.GetValue(i) as Enum);
}
}
if (longVal != 0x0L)
{
enums.Add(Enum.ToObject(enumType, longVal) as Enum);
}
return enums.ToArray();
}
/// <summary>
/// Determines if a numberic value cannot be represented as IEEE-754.
/// </summary>
/// <param name="value"></param>
/// <returns></returns>
protected virtual bool InvalidIeee754(decimal value)
{
// http://stackoverflow.com/questions/1601646
try
{
return (decimal)((double)value) != value;
}
catch
{
return true;
}
}
#endregion Utility Methods
#region IDisposable Members
void IDisposable.Dispose()
{
if (this.Writer != null)
{
this.Writer.Dispose();
}
}
#endregion IDisposable Members
}
}
| |
// 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 gagvc = Google.Ads.GoogleAds.V9.Common;
using gagve = Google.Ads.GoogleAds.V9.Enums;
using gagvr = Google.Ads.GoogleAds.V9.Resources;
using gaxgrpc = Google.Api.Gax.Grpc;
using grpccore = Grpc.Core;
using moq = Moq;
using st = System.Threading;
using stt = System.Threading.Tasks;
using NUnit.Framework;
using Google.Ads.GoogleAds.V9.Services;
namespace Google.Ads.GoogleAds.Tests.V9.Services
{
/// <summary>Generated unit tests.</summary>
public sealed class GeneratedUserInterestServiceClientTest
{
[Category("Autogenerated")][Test]
public void GetUserInterestRequestObject()
{
moq::Mock<UserInterestService.UserInterestServiceClient> mockGrpcClient = new moq::Mock<UserInterestService.UserInterestServiceClient>(moq::MockBehavior.Strict);
GetUserInterestRequest request = new GetUserInterestRequest
{
ResourceNameAsUserInterestName = gagvr::UserInterestName.FromCustomerUserInterest("[CUSTOMER_ID]", "[USER_INTEREST_ID]"),
};
gagvr::UserInterest expectedResponse = new gagvr::UserInterest
{
ResourceNameAsUserInterestName = gagvr::UserInterestName.FromCustomerUserInterest("[CUSTOMER_ID]", "[USER_INTEREST_ID]"),
TaxonomyType = gagve::UserInterestTaxonomyTypeEnum.Types.UserInterestTaxonomyType.Unknown,
Availabilities =
{
new gagvc::CriterionCategoryAvailability(),
},
UserInterestId = 3507346946980618534L,
UserInterestName = gagvr::UserInterestName.FromCustomerUserInterest("[CUSTOMER_ID]", "[USER_INTEREST_ID]"),
UserInterestParentAsUserInterestName = gagvr::UserInterestName.FromCustomerUserInterest("[CUSTOMER_ID]", "[USER_INTEREST_ID]"),
LaunchedToAll = true,
};
mockGrpcClient.Setup(x => x.GetUserInterest(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
UserInterestServiceClient client = new UserInterestServiceClientImpl(mockGrpcClient.Object, null);
gagvr::UserInterest response = client.GetUserInterest(request);
Assert.AreEqual(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[Category("Autogenerated")][Test]
public async stt::Task GetUserInterestRequestObjectAsync()
{
moq::Mock<UserInterestService.UserInterestServiceClient> mockGrpcClient = new moq::Mock<UserInterestService.UserInterestServiceClient>(moq::MockBehavior.Strict);
GetUserInterestRequest request = new GetUserInterestRequest
{
ResourceNameAsUserInterestName = gagvr::UserInterestName.FromCustomerUserInterest("[CUSTOMER_ID]", "[USER_INTEREST_ID]"),
};
gagvr::UserInterest expectedResponse = new gagvr::UserInterest
{
ResourceNameAsUserInterestName = gagvr::UserInterestName.FromCustomerUserInterest("[CUSTOMER_ID]", "[USER_INTEREST_ID]"),
TaxonomyType = gagve::UserInterestTaxonomyTypeEnum.Types.UserInterestTaxonomyType.Unknown,
Availabilities =
{
new gagvc::CriterionCategoryAvailability(),
},
UserInterestId = 3507346946980618534L,
UserInterestName = gagvr::UserInterestName.FromCustomerUserInterest("[CUSTOMER_ID]", "[USER_INTEREST_ID]"),
UserInterestParentAsUserInterestName = gagvr::UserInterestName.FromCustomerUserInterest("[CUSTOMER_ID]", "[USER_INTEREST_ID]"),
LaunchedToAll = true,
};
mockGrpcClient.Setup(x => x.GetUserInterestAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<gagvr::UserInterest>(stt::Task.FromResult(expectedResponse), null, null, null, null));
UserInterestServiceClient client = new UserInterestServiceClientImpl(mockGrpcClient.Object, null);
gagvr::UserInterest responseCallSettings = await client.GetUserInterestAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
Assert.AreEqual(expectedResponse, responseCallSettings);
gagvr::UserInterest responseCancellationToken = await client.GetUserInterestAsync(request, st::CancellationToken.None);
Assert.AreEqual(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[Category("Autogenerated")][Test]
public void GetUserInterest()
{
moq::Mock<UserInterestService.UserInterestServiceClient> mockGrpcClient = new moq::Mock<UserInterestService.UserInterestServiceClient>(moq::MockBehavior.Strict);
GetUserInterestRequest request = new GetUserInterestRequest
{
ResourceNameAsUserInterestName = gagvr::UserInterestName.FromCustomerUserInterest("[CUSTOMER_ID]", "[USER_INTEREST_ID]"),
};
gagvr::UserInterest expectedResponse = new gagvr::UserInterest
{
ResourceNameAsUserInterestName = gagvr::UserInterestName.FromCustomerUserInterest("[CUSTOMER_ID]", "[USER_INTEREST_ID]"),
TaxonomyType = gagve::UserInterestTaxonomyTypeEnum.Types.UserInterestTaxonomyType.Unknown,
Availabilities =
{
new gagvc::CriterionCategoryAvailability(),
},
UserInterestId = 3507346946980618534L,
UserInterestName = gagvr::UserInterestName.FromCustomerUserInterest("[CUSTOMER_ID]", "[USER_INTEREST_ID]"),
UserInterestParentAsUserInterestName = gagvr::UserInterestName.FromCustomerUserInterest("[CUSTOMER_ID]", "[USER_INTEREST_ID]"),
LaunchedToAll = true,
};
mockGrpcClient.Setup(x => x.GetUserInterest(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
UserInterestServiceClient client = new UserInterestServiceClientImpl(mockGrpcClient.Object, null);
gagvr::UserInterest response = client.GetUserInterest(request.ResourceName);
Assert.AreEqual(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[Category("Autogenerated")][Test]
public async stt::Task GetUserInterestAsync()
{
moq::Mock<UserInterestService.UserInterestServiceClient> mockGrpcClient = new moq::Mock<UserInterestService.UserInterestServiceClient>(moq::MockBehavior.Strict);
GetUserInterestRequest request = new GetUserInterestRequest
{
ResourceNameAsUserInterestName = gagvr::UserInterestName.FromCustomerUserInterest("[CUSTOMER_ID]", "[USER_INTEREST_ID]"),
};
gagvr::UserInterest expectedResponse = new gagvr::UserInterest
{
ResourceNameAsUserInterestName = gagvr::UserInterestName.FromCustomerUserInterest("[CUSTOMER_ID]", "[USER_INTEREST_ID]"),
TaxonomyType = gagve::UserInterestTaxonomyTypeEnum.Types.UserInterestTaxonomyType.Unknown,
Availabilities =
{
new gagvc::CriterionCategoryAvailability(),
},
UserInterestId = 3507346946980618534L,
UserInterestName = gagvr::UserInterestName.FromCustomerUserInterest("[CUSTOMER_ID]", "[USER_INTEREST_ID]"),
UserInterestParentAsUserInterestName = gagvr::UserInterestName.FromCustomerUserInterest("[CUSTOMER_ID]", "[USER_INTEREST_ID]"),
LaunchedToAll = true,
};
mockGrpcClient.Setup(x => x.GetUserInterestAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<gagvr::UserInterest>(stt::Task.FromResult(expectedResponse), null, null, null, null));
UserInterestServiceClient client = new UserInterestServiceClientImpl(mockGrpcClient.Object, null);
gagvr::UserInterest responseCallSettings = await client.GetUserInterestAsync(request.ResourceName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
Assert.AreEqual(expectedResponse, responseCallSettings);
gagvr::UserInterest responseCancellationToken = await client.GetUserInterestAsync(request.ResourceName, st::CancellationToken.None);
Assert.AreEqual(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[Category("Autogenerated")][Test]
public void GetUserInterestResourceNames()
{
moq::Mock<UserInterestService.UserInterestServiceClient> mockGrpcClient = new moq::Mock<UserInterestService.UserInterestServiceClient>(moq::MockBehavior.Strict);
GetUserInterestRequest request = new GetUserInterestRequest
{
ResourceNameAsUserInterestName = gagvr::UserInterestName.FromCustomerUserInterest("[CUSTOMER_ID]", "[USER_INTEREST_ID]"),
};
gagvr::UserInterest expectedResponse = new gagvr::UserInterest
{
ResourceNameAsUserInterestName = gagvr::UserInterestName.FromCustomerUserInterest("[CUSTOMER_ID]", "[USER_INTEREST_ID]"),
TaxonomyType = gagve::UserInterestTaxonomyTypeEnum.Types.UserInterestTaxonomyType.Unknown,
Availabilities =
{
new gagvc::CriterionCategoryAvailability(),
},
UserInterestId = 3507346946980618534L,
UserInterestName = gagvr::UserInterestName.FromCustomerUserInterest("[CUSTOMER_ID]", "[USER_INTEREST_ID]"),
UserInterestParentAsUserInterestName = gagvr::UserInterestName.FromCustomerUserInterest("[CUSTOMER_ID]", "[USER_INTEREST_ID]"),
LaunchedToAll = true,
};
mockGrpcClient.Setup(x => x.GetUserInterest(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
UserInterestServiceClient client = new UserInterestServiceClientImpl(mockGrpcClient.Object, null);
gagvr::UserInterest response = client.GetUserInterest(request.ResourceNameAsUserInterestName);
Assert.AreEqual(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[Category("Autogenerated")][Test]
public async stt::Task GetUserInterestResourceNamesAsync()
{
moq::Mock<UserInterestService.UserInterestServiceClient> mockGrpcClient = new moq::Mock<UserInterestService.UserInterestServiceClient>(moq::MockBehavior.Strict);
GetUserInterestRequest request = new GetUserInterestRequest
{
ResourceNameAsUserInterestName = gagvr::UserInterestName.FromCustomerUserInterest("[CUSTOMER_ID]", "[USER_INTEREST_ID]"),
};
gagvr::UserInterest expectedResponse = new gagvr::UserInterest
{
ResourceNameAsUserInterestName = gagvr::UserInterestName.FromCustomerUserInterest("[CUSTOMER_ID]", "[USER_INTEREST_ID]"),
TaxonomyType = gagve::UserInterestTaxonomyTypeEnum.Types.UserInterestTaxonomyType.Unknown,
Availabilities =
{
new gagvc::CriterionCategoryAvailability(),
},
UserInterestId = 3507346946980618534L,
UserInterestName = gagvr::UserInterestName.FromCustomerUserInterest("[CUSTOMER_ID]", "[USER_INTEREST_ID]"),
UserInterestParentAsUserInterestName = gagvr::UserInterestName.FromCustomerUserInterest("[CUSTOMER_ID]", "[USER_INTEREST_ID]"),
LaunchedToAll = true,
};
mockGrpcClient.Setup(x => x.GetUserInterestAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<gagvr::UserInterest>(stt::Task.FromResult(expectedResponse), null, null, null, null));
UserInterestServiceClient client = new UserInterestServiceClientImpl(mockGrpcClient.Object, null);
gagvr::UserInterest responseCallSettings = await client.GetUserInterestAsync(request.ResourceNameAsUserInterestName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
Assert.AreEqual(expectedResponse, responseCallSettings);
gagvr::UserInterest responseCancellationToken = await client.GetUserInterestAsync(request.ResourceNameAsUserInterestName, st::CancellationToken.None);
Assert.AreEqual(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
}
}
| |
using System;
using Csla;
using Csla.Data;
using Csla.Serialization;
using System.ComponentModel.DataAnnotations;
using BusinessObjects.Properties;
using System.Linq;
using BusinessObjects.CoreBusinessClasses;
using DalEf;
using System.Collections.Generic;
namespace BusinessObjects.Documents
{
[Serializable]
public partial class cDocuments_TravelOrder_TravelCosts: CoreBusinessChildClass<cDocuments_TravelOrder_TravelCosts>
{
public static readonly PropertyInfo< System.Int32 > IdProperty = RegisterProperty< System.Int32 >(p => p.Id, string.Empty);
#if !SILVERLIGHT
[System.ComponentModel.DataObjectField(true, true)]
#endif
public System.Int32 Id
{
get { return GetProperty(IdProperty); }
internal set { SetProperty(IdProperty, value); }
}
private static readonly PropertyInfo< System.Int32 > documents_TravelOrderIdProperty = RegisterProperty<System.Int32>(p => p.Documents_TravelOrderId, string.Empty);
[Required(ErrorMessageResourceName = "ErrorMessageRequired", ErrorMessageResourceType = typeof(Resources))]
public System.Int32 Documents_TravelOrderId
{
get { return GetProperty(documents_TravelOrderIdProperty); }
set { SetProperty(documents_TravelOrderIdProperty, value); }
}
private static readonly PropertyInfo<System.Int32> ordinalProperty = RegisterProperty<System.Int32>(p => p.Ordinal, string.Empty);
[Required(ErrorMessageResourceName = "ErrorMessageRequired", ErrorMessageResourceType = typeof(Resources))]
public System.Int32 Ordinal
{
get { return GetProperty(ordinalProperty); }
set { SetProperty(ordinalProperty, value); }
}
private static readonly PropertyInfo< System.Int32? > mDPlaces_Enums_Geo_FromPlaceIdProperty = RegisterProperty<System.Int32?>(p => p.MDPlaces_Enums_Geo_FromPlaceId, string.Empty,(System.Int32?)null);
public System.Int32? MDPlaces_Enums_Geo_FromPlaceId
{
get { return GetProperty(mDPlaces_Enums_Geo_FromPlaceIdProperty); }
set { SetProperty(mDPlaces_Enums_Geo_FromPlaceIdProperty, value); }
}
private static readonly PropertyInfo< System.Int32? > mDPlaces_Enums_Geo_ToPlaceIdProperty = RegisterProperty<System.Int32?>(p => p.MDPlaces_Enums_Geo_ToPlaceId, string.Empty,(System.Int32?)null);
public System.Int32? MDPlaces_Enums_Geo_ToPlaceId
{
get { return GetProperty(mDPlaces_Enums_Geo_ToPlaceIdProperty); }
set { SetProperty(mDPlaces_Enums_Geo_ToPlaceIdProperty, value); }
}
private static readonly PropertyInfo< System.Int32? > mDGeneral_Enums_KindOfTransportationIdProperty = RegisterProperty<System.Int32?>(p => p.MDGeneral_Enums_KindOfTransportationId, string.Empty,(System.Int32?)null);
public System.Int32? MDGeneral_Enums_KindOfTransportationId
{
get { return GetProperty(mDGeneral_Enums_KindOfTransportationIdProperty); }
set { SetProperty(mDGeneral_Enums_KindOfTransportationIdProperty, value); }
}
private static readonly PropertyInfo< System.Int32? > kilometersProperty = RegisterProperty<System.Int32?>(p => p.Kilometers, string.Empty,(System.Int32?)null);
public System.Int32? Kilometers
{
get { return GetProperty(kilometersProperty); }
set { SetProperty(kilometersProperty, value); }
}
/// <summary>
/// Used for optimistic concurrency.
/// </summary>
[NotUndoable]
internal System.Byte[] LastChanged = new System.Byte[8];
internal static cDocuments_TravelOrder_TravelCosts NewDocuments_TravelOrder_TravelCosts()
{
return DataPortal.CreateChild<cDocuments_TravelOrder_TravelCosts>();
}
public static cDocuments_TravelOrder_TravelCosts GetDocuments_TravelOrder_TravelCosts(Documents_TravelOrder_TravelCostsCol data)
{
return DataPortal.FetchChild<cDocuments_TravelOrder_TravelCosts>(data);
}
#region Data Access
[RunLocal]
protected override void Child_Create()
{
BusinessRules.CheckRules();
}
private void Child_Fetch(Documents_TravelOrder_TravelCostsCol data)
{
LoadProperty<int>(IdProperty, data.Id);
LoadProperty<byte[]>(EntityKeyDataProperty, Serialize(data.EntityKey));
LoadProperty<int>(documents_TravelOrderIdProperty, data.Documents_TravelOrderId);
LoadProperty<int>(ordinalProperty, data.Ordinal);
LoadProperty<int?>(mDPlaces_Enums_Geo_FromPlaceIdProperty, data.MDPlaces_Enums_Geo_FromPlaceId);
LoadProperty<int?>(mDPlaces_Enums_Geo_ToPlaceIdProperty, data.MDPlaces_Enums_Geo_ToPlaceId);
LoadProperty<int?>(mDGeneral_Enums_KindOfTransportationIdProperty, data.MDGeneral_Enums_KindOfTransportationId);
LoadProperty<int?>(kilometersProperty, data.Kilometers);
LastChanged = data.LastChanged;
ItemLoaded();
BusinessRules.CheckRules();
}
partial void ItemLoaded();
private void Child_Insert(Documents_TravelOrder parent)
{
using (var ctx = ObjectContextManager<DocumentsEntities>.GetManager("DocumentsEntities"))
{
var data = new Documents_TravelOrder_TravelCostsCol();
data.Documents_TravelOrder = parent;
data.Ordinal = ReadProperty<int>(ordinalProperty);
data.MDPlaces_Enums_Geo_FromPlaceId = ReadProperty<int?>(mDPlaces_Enums_Geo_FromPlaceIdProperty);
data.MDPlaces_Enums_Geo_ToPlaceId = ReadProperty<int?>(mDPlaces_Enums_Geo_ToPlaceIdProperty);
data.MDGeneral_Enums_KindOfTransportationId = ReadProperty<int?>(mDGeneral_Enums_KindOfTransportationIdProperty);
data.Kilometers = ReadProperty<int?>(kilometersProperty);
ctx.ObjectContext.AddToDocuments_TravelOrder_TravelCostsCol(data);
data.PropertyChanged += (o, e) =>
{
if (e.PropertyName == "Id")
{
LoadProperty<int>(IdProperty, data.Id);
LoadProperty<int>(documents_TravelOrderIdProperty, data.Documents_TravelOrderId);
LoadProperty<byte[]>(EntityKeyDataProperty, Serialize(data.EntityKey));
LastChanged = data.LastChanged;
}
};
}
}
private void Child_Update()
{
using (var ctx = ObjectContextManager<DocumentsEntities>.GetManager("DocumentsEntities"))
{
var data = new Documents_TravelOrder_TravelCostsCol();
data.Id = ReadProperty<int>(IdProperty);
data.EntityKey = Deserialize(ReadProperty(EntityKeyDataProperty)) as System.Data.EntityKey;
ctx.ObjectContext.Attach(data);
data.Ordinal = ReadProperty<int>(ordinalProperty);
data.MDPlaces_Enums_Geo_FromPlaceId = ReadProperty<int?>(mDPlaces_Enums_Geo_FromPlaceIdProperty);
data.MDPlaces_Enums_Geo_ToPlaceId = ReadProperty<int?>(mDPlaces_Enums_Geo_ToPlaceIdProperty);
data.MDGeneral_Enums_KindOfTransportationId = ReadProperty<int?>(mDGeneral_Enums_KindOfTransportationIdProperty);
data.Kilometers = ReadProperty<int?>(kilometersProperty);
data.PropertyChanged += (o, e) =>
{
if (e.PropertyName == "LastChanged")
LastChanged = data.LastChanged;
};
}
}
private void Child_DeleteSelf()
{
using (var ctx = ObjectContextManager<DocumentsEntities>.GetManager("DocumentsEntities"))
{
var data = new Documents_TravelOrder_TravelCostsCol();
data.Id = ReadProperty<int>(IdProperty);
data.EntityKey = Deserialize(ReadProperty(EntityKeyDataProperty)) as System.Data.EntityKey;
//data.SubjectId = parent.Id;
ctx.ObjectContext.Attach(data);
ctx.ObjectContext.DeleteObject(data);
}
}
#endregion
}
[Serializable]
public partial class cDocuments_TravelOrder_TravelCostsCol : BusinessListBase<cDocuments_TravelOrder_TravelCostsCol, cDocuments_TravelOrder_TravelCosts>
{
internal static cDocuments_TravelOrder_TravelCostsCol NewDocuments_TravelOrder_TravelCostsCol()
{
return DataPortal.CreateChild<cDocuments_TravelOrder_TravelCostsCol>();
}
public static cDocuments_TravelOrder_TravelCostsCol GetDocuments_TravelOrder_TravelCostsCol(IEnumerable<Documents_TravelOrder_TravelCostsCol> dataSet)
{
var childList = new cDocuments_TravelOrder_TravelCostsCol();
childList.Fetch(dataSet);
return childList;
}
#region Data Access
private void Fetch(IEnumerable<Documents_TravelOrder_TravelCostsCol> dataSet)
{
RaiseListChangedEvents = false;
foreach (var data in dataSet)
this.Add(cDocuments_TravelOrder_TravelCosts.GetDocuments_TravelOrder_TravelCosts(data));
RaiseListChangedEvents = true;
}
#endregion //Data Access
}
}
| |
//---------------------------------------------------------------------
// <copyright file="SegmentInfo.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
// <summary>
// Structure containing information about a segment (Uri is made
// up of bunch of segments, each segment is seperated by '/' character)
// </summary>
//
// @owner [....]
//---------------------------------------------------------------------
namespace System.Data.Services
{
#region Namespaces.
using System;
using System.Collections;
using System.Data.Services.Providers;
using System.Diagnostics;
using System.Linq;
#endregion Namespaces.
/// <summary>Contains the information regarding a segment that makes up the uri</summary>
[DebuggerDisplay("SegmentInfo={Identifier} -> {TargetKind} '{TargetResourceType.InstanceType}'")]
internal class SegmentInfo
{
#region Private fields.
/// <summary>Returns the identifier for this segment i.e. string part without the keys.</summary>
private string identifier;
/// <summary>Returns the values that constitute the key as specified in the request.</summary>
private KeyInstance key;
/// <summary>Returns the query that's being composed for this segment</summary>
private IEnumerable requestEnumerable;
/// <summary>Whether the segment targets a single result or not.</summary>
private bool singleResult;
/// <summary>resource set if applicable.</summary>
private ResourceSetWrapper targetContainer;
/// <summary>The type of resource targeted by this segment.</summary>
private ResourceType targetResourceType;
/// <summary>The kind of resource targeted by this segment.</summary>
private RequestTargetKind targetKind;
/// <summary>Returns the source for this segment</summary>
private RequestTargetSource targetSource;
/// <summary>Service operation being invoked.</summary>
private ServiceOperationWrapper operation;
/// <summary>Operation parameters.</summary>
private object[] operationParameters;
/// <summary>Returns the property that is being projected in this segment, if there's any.</summary>
private ResourceProperty projectedProperty;
#endregion Private fields.
/// <summary>Empty constructor.</summary>
internal SegmentInfo()
{
}
/// <summary>Copy constructor.</summary>
/// <param name="other">Another <see cref="SegmentInfo"/> to get a shallow copy of.</param>
internal SegmentInfo(SegmentInfo other)
{
Debug.Assert(other != null, "other != null");
this.Identifier = other.Identifier;
this.Key = other.Key;
this.Operation = other.Operation;
this.OperationParameters = other.OperationParameters;
this.ProjectedProperty = other.ProjectedProperty;
this.RequestEnumerable = other.RequestEnumerable;
this.SingleResult = other.SingleResult;
this.TargetContainer = other.TargetContainer;
this.TargetKind = other.TargetKind;
this.TargetSource = other.TargetSource;
this.targetResourceType = other.targetResourceType;
}
/// <summary>Returns the identifier for this segment i.e. string part without the keys.</summary>
internal string Identifier
{
get { return this.identifier; }
set { this.identifier = value; }
}
/// <summary>Returns the values that constitute the key as specified in the request.</summary>
internal KeyInstance Key
{
get { return this.key; }
set { this.key = value; }
}
/// <summary>Returns the query that's being composed for this segment</summary>
internal IEnumerable RequestEnumerable
{
get { return this.requestEnumerable; }
set { this.requestEnumerable = value; }
}
/// <summary>Whether the segment targets a single result or not.</summary>
internal bool SingleResult
{
get { return this.singleResult; }
set { this.singleResult = value; }
}
/// <summary>resource set if applicable.</summary>
internal ResourceSetWrapper TargetContainer
{
get { return this.targetContainer; }
set { this.targetContainer = value; }
}
/// <summary>The type of element targeted by this segment.</summary>
internal ResourceType TargetResourceType
{
get { return this.targetResourceType; }
set { this.targetResourceType = value; }
}
/// <summary>The kind of resource targeted by this segment.</summary>
internal RequestTargetKind TargetKind
{
get { return this.targetKind; }
set { this.targetKind = value; }
}
/// <summary>Returns the source for this segment</summary>
internal RequestTargetSource TargetSource
{
get { return this.targetSource; }
set { this.targetSource = value; }
}
/// <summary>Service operation being invoked.</summary>
internal ServiceOperationWrapper Operation
{
get { return this.operation; }
set { this.operation = value; }
}
/// <summary>Operation parameters.</summary>
internal object[] OperationParameters
{
get { return this.operationParameters; }
set { this.operationParameters = value; }
}
/// <summary>Returns the property that is being projected in this segment, if there's any.</summary>
internal ResourceProperty ProjectedProperty
{
get { return this.projectedProperty; }
set { this.projectedProperty = value; }
}
/// <summary>Returns true if this segment has a key filter with values; false otherwise.</summary>
internal bool HasKeyValues
{
get { return this.Key != null && !this.Key.IsEmpty; }
}
/// <summary>
/// Determines whether the target kind is a direct reference to an element
/// i.e. either you have a $value or you are accessing a resource via key property
/// (/Customers(1) or /Customers(1)/BestFriend/Orders('Foo'). Either case the value
/// cannot be null.
/// </summary>
/// <param name="kind">Kind of request to evaluate.</param>
/// <returns>
/// A characteristic of a direct reference is that if its value
/// is null, a 404 error should be returned.
/// </returns>
internal bool IsDirectReference
{
get
{
return
this.TargetKind == RequestTargetKind.PrimitiveValue ||
this.TargetKind == RequestTargetKind.OpenPropertyValue ||
this.HasKeyValues;
}
}
/// <summary>Returns the query for this segment, possibly null.</summary>
internal IQueryable RequestQueryable
{
get
{
return this.RequestEnumerable as IQueryable;
}
set
{
this.RequestEnumerable = value;
}
}
#if DEBUG
/// <summary>In DEBUG builds, ensures that invariants for the class hold.</summary>
internal void AssertValid()
{
WebUtil.DebugEnumIsDefined(this.TargetKind);
WebUtil.DebugEnumIsDefined(this.TargetSource);
Debug.Assert(this.TargetKind != RequestTargetKind.Nothing, "targetKind != RequestTargetKind.Nothing");
Debug.Assert(
this.TargetContainer == null || this.TargetSource != RequestTargetSource.None,
"'None' targets should not have a resource set.");
Debug.Assert(
this.TargetKind != RequestTargetKind.Resource ||
this.TargetContainer != null ||
this.TargetKind == RequestTargetKind.OpenProperty ||
this.TargetSource == RequestTargetSource.ServiceOperation,
"All resource targets (except for some service operations and open properties) should have a container.");
Debug.Assert(
this.TargetContainer == null || this.TargetContainer.ResourceType.IsAssignableFrom(this.TargetResourceType),
"If targetContainer is assigned, it should be equal to (or assignable to) the segment's element type.");
Debug.Assert(
!String.IsNullOrEmpty(this.Identifier) || RequestTargetSource.None == this.TargetSource || RequestTargetKind.VoidServiceOperation == this.TargetKind,
"identifier must not be empty or null except for none or void service operation");
}
#endif
}
}
| |
/*
* Copyright (c) Citrix Systems, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1) Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2) Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials
* provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Globalization;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
namespace XenAPI
{
/// <summary>
/// A VLAN mux/demux
/// First published in XenServer 4.1.
/// </summary>
public partial class VLAN : XenObject<VLAN>
{
public VLAN()
{
}
public VLAN(string uuid,
XenRef<PIF> tagged_PIF,
XenRef<PIF> untagged_PIF,
long tag,
Dictionary<string, string> other_config)
{
this.uuid = uuid;
this.tagged_PIF = tagged_PIF;
this.untagged_PIF = untagged_PIF;
this.tag = tag;
this.other_config = other_config;
}
/// <summary>
/// Creates a new VLAN from a Proxy_VLAN.
/// </summary>
/// <param name="proxy"></param>
public VLAN(Proxy_VLAN proxy)
{
this.UpdateFromProxy(proxy);
}
/// <summary>
/// Updates each field of this instance with the value of
/// the corresponding field of a given VLAN.
/// </summary>
public override void UpdateFrom(VLAN update)
{
uuid = update.uuid;
tagged_PIF = update.tagged_PIF;
untagged_PIF = update.untagged_PIF;
tag = update.tag;
other_config = update.other_config;
}
internal void UpdateFromProxy(Proxy_VLAN proxy)
{
uuid = proxy.uuid == null ? null : (string)proxy.uuid;
tagged_PIF = proxy.tagged_PIF == null ? null : XenRef<PIF>.Create(proxy.tagged_PIF);
untagged_PIF = proxy.untagged_PIF == null ? null : XenRef<PIF>.Create(proxy.untagged_PIF);
tag = proxy.tag == null ? 0 : long.Parse((string)proxy.tag);
other_config = proxy.other_config == null ? null : Maps.convert_from_proxy_string_string(proxy.other_config);
}
public Proxy_VLAN ToProxy()
{
Proxy_VLAN result_ = new Proxy_VLAN();
result_.uuid = uuid ?? "";
result_.tagged_PIF = tagged_PIF ?? "";
result_.untagged_PIF = untagged_PIF ?? "";
result_.tag = tag.ToString();
result_.other_config = Maps.convert_to_proxy_string_string(other_config);
return result_;
}
/// <summary>
/// Creates a new VLAN from a Hashtable.
/// Note that the fields not contained in the Hashtable
/// will be created with their default values.
/// </summary>
/// <param name="table"></param>
public VLAN(Hashtable table) : this()
{
UpdateFrom(table);
}
/// <summary>
/// Given a Hashtable with field-value pairs, it updates the fields of this VLAN
/// with the values listed in the Hashtable. Note that only the fields contained
/// in the Hashtable will be updated and the rest will remain the same.
/// </summary>
/// <param name="table"></param>
public void UpdateFrom(Hashtable table)
{
if (table.ContainsKey("uuid"))
uuid = Marshalling.ParseString(table, "uuid");
if (table.ContainsKey("tagged_PIF"))
tagged_PIF = Marshalling.ParseRef<PIF>(table, "tagged_PIF");
if (table.ContainsKey("untagged_PIF"))
untagged_PIF = Marshalling.ParseRef<PIF>(table, "untagged_PIF");
if (table.ContainsKey("tag"))
tag = Marshalling.ParseLong(table, "tag");
if (table.ContainsKey("other_config"))
other_config = Maps.convert_from_proxy_string_string(Marshalling.ParseHashTable(table, "other_config"));
}
public bool DeepEquals(VLAN other)
{
if (ReferenceEquals(null, other))
return false;
if (ReferenceEquals(this, other))
return true;
return Helper.AreEqual2(this._uuid, other._uuid) &&
Helper.AreEqual2(this._tagged_PIF, other._tagged_PIF) &&
Helper.AreEqual2(this._untagged_PIF, other._untagged_PIF) &&
Helper.AreEqual2(this._tag, other._tag) &&
Helper.AreEqual2(this._other_config, other._other_config);
}
internal static List<VLAN> ProxyArrayToObjectList(Proxy_VLAN[] input)
{
var result = new List<VLAN>();
foreach (var item in input)
result.Add(new VLAN(item));
return result;
}
public override string SaveChanges(Session session, string opaqueRef, VLAN server)
{
if (opaqueRef == null)
{
System.Diagnostics.Debug.Assert(false, "Cannot create instances of this type on the server");
return "";
}
else
{
if (!Helper.AreEqual2(_other_config, server._other_config))
{
VLAN.set_other_config(session, opaqueRef, _other_config);
}
return null;
}
}
/// <summary>
/// Get a record containing the current state of the given VLAN.
/// First published in XenServer 4.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vlan">The opaque_ref of the given vlan</param>
public static VLAN get_record(Session session, string _vlan)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.vlan_get_record(session.opaque_ref, _vlan);
else
return new VLAN((Proxy_VLAN)session.proxy.vlan_get_record(session.opaque_ref, _vlan ?? "").parse());
}
/// <summary>
/// Get a reference to the VLAN instance with the specified UUID.
/// First published in XenServer 4.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_uuid">UUID of object to return</param>
public static XenRef<VLAN> get_by_uuid(Session session, string _uuid)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.vlan_get_by_uuid(session.opaque_ref, _uuid);
else
return XenRef<VLAN>.Create(session.proxy.vlan_get_by_uuid(session.opaque_ref, _uuid ?? "").parse());
}
/// <summary>
/// Get the uuid field of the given VLAN.
/// First published in XenServer 4.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vlan">The opaque_ref of the given vlan</param>
public static string get_uuid(Session session, string _vlan)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.vlan_get_uuid(session.opaque_ref, _vlan);
else
return (string)session.proxy.vlan_get_uuid(session.opaque_ref, _vlan ?? "").parse();
}
/// <summary>
/// Get the tagged_PIF field of the given VLAN.
/// First published in XenServer 4.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vlan">The opaque_ref of the given vlan</param>
public static XenRef<PIF> get_tagged_PIF(Session session, string _vlan)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.vlan_get_tagged_pif(session.opaque_ref, _vlan);
else
return XenRef<PIF>.Create(session.proxy.vlan_get_tagged_pif(session.opaque_ref, _vlan ?? "").parse());
}
/// <summary>
/// Get the untagged_PIF field of the given VLAN.
/// First published in XenServer 4.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vlan">The opaque_ref of the given vlan</param>
public static XenRef<PIF> get_untagged_PIF(Session session, string _vlan)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.vlan_get_untagged_pif(session.opaque_ref, _vlan);
else
return XenRef<PIF>.Create(session.proxy.vlan_get_untagged_pif(session.opaque_ref, _vlan ?? "").parse());
}
/// <summary>
/// Get the tag field of the given VLAN.
/// First published in XenServer 4.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vlan">The opaque_ref of the given vlan</param>
public static long get_tag(Session session, string _vlan)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.vlan_get_tag(session.opaque_ref, _vlan);
else
return long.Parse((string)session.proxy.vlan_get_tag(session.opaque_ref, _vlan ?? "").parse());
}
/// <summary>
/// Get the other_config field of the given VLAN.
/// First published in XenServer 4.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vlan">The opaque_ref of the given vlan</param>
public static Dictionary<string, string> get_other_config(Session session, string _vlan)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.vlan_get_other_config(session.opaque_ref, _vlan);
else
return Maps.convert_from_proxy_string_string(session.proxy.vlan_get_other_config(session.opaque_ref, _vlan ?? "").parse());
}
/// <summary>
/// Set the other_config field of the given VLAN.
/// First published in XenServer 4.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vlan">The opaque_ref of the given vlan</param>
/// <param name="_other_config">New value to set</param>
public static void set_other_config(Session session, string _vlan, Dictionary<string, string> _other_config)
{
if (session.JsonRpcClient != null)
session.JsonRpcClient.vlan_set_other_config(session.opaque_ref, _vlan, _other_config);
else
session.proxy.vlan_set_other_config(session.opaque_ref, _vlan ?? "", Maps.convert_to_proxy_string_string(_other_config)).parse();
}
/// <summary>
/// Add the given key-value pair to the other_config field of the given VLAN.
/// First published in XenServer 4.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vlan">The opaque_ref of the given vlan</param>
/// <param name="_key">Key to add</param>
/// <param name="_value">Value to add</param>
public static void add_to_other_config(Session session, string _vlan, string _key, string _value)
{
if (session.JsonRpcClient != null)
session.JsonRpcClient.vlan_add_to_other_config(session.opaque_ref, _vlan, _key, _value);
else
session.proxy.vlan_add_to_other_config(session.opaque_ref, _vlan ?? "", _key ?? "", _value ?? "").parse();
}
/// <summary>
/// Remove the given key and its corresponding value from the other_config field of the given VLAN. If the key is not in that Map, then do nothing.
/// First published in XenServer 4.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vlan">The opaque_ref of the given vlan</param>
/// <param name="_key">Key to remove</param>
public static void remove_from_other_config(Session session, string _vlan, string _key)
{
if (session.JsonRpcClient != null)
session.JsonRpcClient.vlan_remove_from_other_config(session.opaque_ref, _vlan, _key);
else
session.proxy.vlan_remove_from_other_config(session.opaque_ref, _vlan ?? "", _key ?? "").parse();
}
/// <summary>
/// Create a VLAN mux/demuxer
/// First published in XenServer 4.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_tagged_pif">PIF which receives the tagged traffic</param>
/// <param name="_tag">VLAN tag to use</param>
/// <param name="_network">Network to receive the untagged traffic</param>
public static XenRef<VLAN> create(Session session, string _tagged_pif, long _tag, string _network)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.vlan_create(session.opaque_ref, _tagged_pif, _tag, _network);
else
return XenRef<VLAN>.Create(session.proxy.vlan_create(session.opaque_ref, _tagged_pif ?? "", _tag.ToString(), _network ?? "").parse());
}
/// <summary>
/// Create a VLAN mux/demuxer
/// First published in XenServer 4.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_tagged_pif">PIF which receives the tagged traffic</param>
/// <param name="_tag">VLAN tag to use</param>
/// <param name="_network">Network to receive the untagged traffic</param>
public static XenRef<Task> async_create(Session session, string _tagged_pif, long _tag, string _network)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.async_vlan_create(session.opaque_ref, _tagged_pif, _tag, _network);
else
return XenRef<Task>.Create(session.proxy.async_vlan_create(session.opaque_ref, _tagged_pif ?? "", _tag.ToString(), _network ?? "").parse());
}
/// <summary>
/// Destroy a VLAN mux/demuxer
/// First published in XenServer 4.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vlan">The opaque_ref of the given vlan</param>
public static void destroy(Session session, string _vlan)
{
if (session.JsonRpcClient != null)
session.JsonRpcClient.vlan_destroy(session.opaque_ref, _vlan);
else
session.proxy.vlan_destroy(session.opaque_ref, _vlan ?? "").parse();
}
/// <summary>
/// Destroy a VLAN mux/demuxer
/// First published in XenServer 4.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vlan">The opaque_ref of the given vlan</param>
public static XenRef<Task> async_destroy(Session session, string _vlan)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.async_vlan_destroy(session.opaque_ref, _vlan);
else
return XenRef<Task>.Create(session.proxy.async_vlan_destroy(session.opaque_ref, _vlan ?? "").parse());
}
/// <summary>
/// Return a list of all the VLANs known to the system.
/// First published in XenServer 4.1.
/// </summary>
/// <param name="session">The session</param>
public static List<XenRef<VLAN>> get_all(Session session)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.vlan_get_all(session.opaque_ref);
else
return XenRef<VLAN>.Create(session.proxy.vlan_get_all(session.opaque_ref).parse());
}
/// <summary>
/// Get all the VLAN Records at once, in a single XML RPC call
/// First published in XenServer 4.1.
/// </summary>
/// <param name="session">The session</param>
public static Dictionary<XenRef<VLAN>, VLAN> get_all_records(Session session)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.vlan_get_all_records(session.opaque_ref);
else
return XenRef<VLAN>.Create<Proxy_VLAN>(session.proxy.vlan_get_all_records(session.opaque_ref).parse());
}
/// <summary>
/// Unique identifier/object reference
/// </summary>
public virtual string uuid
{
get { return _uuid; }
set
{
if (!Helper.AreEqual(value, _uuid))
{
_uuid = value;
Changed = true;
NotifyPropertyChanged("uuid");
}
}
}
private string _uuid = "";
/// <summary>
/// interface on which traffic is tagged
/// </summary>
[JsonConverter(typeof(XenRefConverter<PIF>))]
public virtual XenRef<PIF> tagged_PIF
{
get { return _tagged_PIF; }
set
{
if (!Helper.AreEqual(value, _tagged_PIF))
{
_tagged_PIF = value;
Changed = true;
NotifyPropertyChanged("tagged_PIF");
}
}
}
private XenRef<PIF> _tagged_PIF = new XenRef<PIF>(Helper.NullOpaqueRef);
/// <summary>
/// interface on which traffic is untagged
/// </summary>
[JsonConverter(typeof(XenRefConverter<PIF>))]
public virtual XenRef<PIF> untagged_PIF
{
get { return _untagged_PIF; }
set
{
if (!Helper.AreEqual(value, _untagged_PIF))
{
_untagged_PIF = value;
Changed = true;
NotifyPropertyChanged("untagged_PIF");
}
}
}
private XenRef<PIF> _untagged_PIF = new XenRef<PIF>(Helper.NullOpaqueRef);
/// <summary>
/// VLAN tag in use
/// </summary>
public virtual long tag
{
get { return _tag; }
set
{
if (!Helper.AreEqual(value, _tag))
{
_tag = value;
Changed = true;
NotifyPropertyChanged("tag");
}
}
}
private long _tag = -1;
/// <summary>
/// additional configuration
/// </summary>
[JsonConverter(typeof(StringStringMapConverter))]
public virtual Dictionary<string, string> other_config
{
get { return _other_config; }
set
{
if (!Helper.AreEqual(value, _other_config))
{
_other_config = value;
Changed = true;
NotifyPropertyChanged("other_config");
}
}
}
private Dictionary<string, string> _other_config = new Dictionary<string, string>() {};
}
}
| |
using System;
namespace eQuantic.Core.Date
{
// ------------------------------------------------------------------------
public struct Time : IComparable, IComparable<Time>, IEquatable<Time>
{
// ----------------------------------------------------------------------
public Time( DateTime dateTime )
{
duration = dateTime.TimeOfDay;
} // Time
// ----------------------------------------------------------------------
public Time( TimeSpan duration ) :
this( Math.Abs( duration.Hours ), Math.Abs( duration.Minutes ),
Math.Abs( duration.Seconds ), Math.Abs( duration.Milliseconds ) )
{
} // Time
// ----------------------------------------------------------------------
public Time( int hour = 0, int minute = 0, int second = 0, int millisecond = 0 )
{
if ( hour < 0 || hour > TimeSpec.HoursPerDay )
{
throw new ArgumentOutOfRangeException( "hour" );
}
if ( hour == TimeSpec.HoursPerDay )
{
if ( minute > 0 )
{
throw new ArgumentOutOfRangeException( "minute" );
}
if ( second > 0 )
{
throw new ArgumentOutOfRangeException( "second" );
}
if ( millisecond > 0 )
{
throw new ArgumentOutOfRangeException( "millisecond" );
}
}
if ( minute < 0 || minute >= TimeSpec.MinutesPerHour )
{
throw new ArgumentOutOfRangeException( "minute" );
}
if ( second < 0 || second >= TimeSpec.SecondsPerMinute )
{
throw new ArgumentOutOfRangeException( "second" );
}
if ( millisecond < 0 || millisecond >= TimeSpec.MillisecondsPerSecond )
{
throw new ArgumentOutOfRangeException( "millisecond" );
}
duration = new TimeSpan( 0, hour, minute, second, millisecond );
} // Time
// ----------------------------------------------------------------------
public int Hour
{
get { return duration.Hours; }
} // Hour
// ----------------------------------------------------------------------
public int Minute
{
get { return duration.Minutes; }
} // Minute
// ----------------------------------------------------------------------
public int Second
{
get { return duration.Seconds; }
} // Second
// ----------------------------------------------------------------------
public int Millisecond
{
get { return duration.Milliseconds; }
} // Millisecond
// ----------------------------------------------------------------------
public TimeSpan Duration
{
get { return duration; }
} // Duration
// ----------------------------------------------------------------------
public bool IsZero
{
get { return duration.Equals( TimeSpan.Zero ); }
} // IsZero
// ----------------------------------------------------------------------
public bool IsFullDay
{
get { return (int)duration.TotalHours == TimeSpec.HoursPerDay; }
} // IsFullDay
// ----------------------------------------------------------------------
public bool IsFullDayOrZero
{
get { return IsFullDay || IsZero; }
} // IsFullDayOrZero
// ----------------------------------------------------------------------
public long Ticks
{
get { return duration.Ticks; }
} // Ticks
// ----------------------------------------------------------------------
public double TotalHours
{
get { return duration.TotalHours; }
} // TotalHours
// ----------------------------------------------------------------------
public double TotalMinutes
{
get { return duration.TotalMinutes; }
} // TotalMinutes
// ----------------------------------------------------------------------
public double TotalSeconds
{
get { return duration.TotalSeconds; }
} // TotalSeconds
// ----------------------------------------------------------------------
public double TotalMilliseconds
{
get { return duration.TotalMilliseconds; }
} // TotalMilliseconds
// ----------------------------------------------------------------------
public int CompareTo( Time other )
{
return duration.CompareTo( other.duration );
} // CompareTo
// ----------------------------------------------------------------------
public int CompareTo( object obj )
{
return duration.CompareTo( ((Time)obj).duration );
} // CompareTo
// ----------------------------------------------------------------------
public bool Equals( Time other )
{
return duration.Equals( other.duration );
} // Equals
// ----------------------------------------------------------------------
public override string ToString()
{
return ( (int)TotalHours ).ToString( "00" ) + ":" + Minute.ToString( "00" ) +
":" + Second.ToString( "00" ) + "." + Millisecond.ToString( "000" );
} // ToString
// ----------------------------------------------------------------------
public override bool Equals( object obj )
{
if ( obj == null || GetType() != obj.GetType() )
{
return false;
}
return Equals( (Time)obj );
} // Equals
// ----------------------------------------------------------------------
public override int GetHashCode()
{
return HashTool.ComputeHashCode( GetType().GetHashCode(), duration );
} // GetHashCode
// ----------------------------------------------------------------------
public static TimeSpan operator -( Time time1, Time time2 )
{
return ( time1 - time2.duration ).duration;
} // operator -
// ----------------------------------------------------------------------
public static Time operator -( Time time, TimeSpan duration )
{
if ( Equals( duration, TimeSpan.Zero ) )
{
return time;
}
DateTime day = duration > TimeSpan.Zero ? DateTime.MaxValue.Date : DateTime.MinValue.Date;
return new Time( time.ToDateTime( day ).Subtract( duration ) );
} // operator -
// ----------------------------------------------------------------------
public static TimeSpan operator +( Time time1, Time time2 )
{
return ( time1 + time2.duration ).duration;
} // operator +
// ----------------------------------------------------------------------
public static Time operator +( Time time, TimeSpan duration )
{
if ( Equals( duration, TimeSpan.Zero ) )
{
return time;
}
DateTime day = duration > TimeSpan.Zero ? DateTime.MinValue : DateTime.MaxValue;
return new Time( time.ToDateTime( day ).Add( duration ) );
} // operator +
// ----------------------------------------------------------------------
public static bool operator <( Time time1, Time time2 )
{
return time1.duration < time2.duration;
} // operator <
// ----------------------------------------------------------------------
public static bool operator <=( Time time1, Time time2 )
{
return time1.duration <= time2.duration;
} // operator <=
// ----------------------------------------------------------------------
public static bool operator ==( Time left, Time right )
{
return Equals( left, right );
} // operator ==
// ----------------------------------------------------------------------
public static bool operator !=( Time left, Time right )
{
return !Equals( left, right );
} // operator !=
// ----------------------------------------------------------------------
public static bool operator >( Time time1, Time time2 )
{
return time1.duration > time2.duration;
} // operator >
// ----------------------------------------------------------------------
public static bool operator >=( Time time1, Time time2 )
{
return time1.duration >= time2.duration;
} // operator >=
// ----------------------------------------------------------------------
public DateTime ToDateTime( Date date )
{
return ToDateTime( date.DateTime );
} // ToDateTime
// ----------------------------------------------------------------------
public DateTime ToDateTime( DateTime dateTime )
{
return ToDateTime( dateTime, this );
} // ToDateTime
// ----------------------------------------------------------------------
public static DateTime ToDateTime( Date date, Time time )
{
return ToDateTime( date.DateTime, time );
} // ToDateTime
// ----------------------------------------------------------------------
public static DateTime ToDateTime( DateTime dateTime, Time time )
{
return dateTime.Date.Add( time.Duration );
} // ToDateTime
// ----------------------------------------------------------------------
// members
private readonly TimeSpan duration;
} // struct Time
} // namespace Itenso.TimePeriod
// -- EOF -------------------------------------------------------------------
| |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using Trionic5Tools;
namespace Trionic5Controls
{
public partial class frmInjectorWizard : DevExpress.XtraEditors.XtraForm
{
public frmInjectorWizard()
{
InitializeComponent();
}
private float _crankfactor = 9;
private float _oricrankfactor = 9;
public float Crankfactor
{
get { return _crankfactor; }
set
{
_crankfactor = value;
_oricrankfactor = _crankfactor;
spinEdit2.Value = (decimal)_crankfactor;
labelControl18.Text = _crankfactor.ToString("F2");
}
}
public byte[] GetCrankFactor()
{
byte[] retval = new byte[2];
float val = _crankfactor / 0.004F;
int ival = Convert.ToInt32(val);
byte b1 = (byte)(ival / 256);
byte b2 = (byte)(ival - (int)b1 * 256);
retval[0] = b1;
retval[1] = b2;
return retval;
}
public byte[] GetBatteryCorrectionMap()
{
byte[] retval = new byte[22];
int bcount = 0;
for (int i = 0; i < 11; i++)
{
float val = GetBatteryCorrection(i) / 0.004F;
int ival = Convert.ToInt32(val);
byte b1 = (byte)(ival / 256);
byte b2 = (byte)(ival - (int)b1 * 256);
retval[bcount++] = b1;
retval[bcount++] = b2;
}
return retval;
}
public float GetBatteryCorrection(int index)
{
float retval = 0;
switch (index)
{
case 0:
retval = (float)Convert.ToDouble(textEdit22.Text);
break;
case 1:
retval = (float)Convert.ToDouble(textEdit21.Text);
break;
case 2:
retval = (float)Convert.ToDouble(textEdit20.Text);
break;
case 3:
retval = (float)Convert.ToDouble(textEdit19.Text);
break;
case 4:
retval = (float)Convert.ToDouble(textEdit18.Text);
break;
case 5:
retval = (float)Convert.ToDouble(textEdit17.Text);
break;
case 6:
retval = (float)Convert.ToDouble(textEdit16.Text);
break;
case 7:
retval = (float)Convert.ToDouble(textEdit15.Text);
break;
case 8:
retval = (float)Convert.ToDouble(textEdit14.Text);
break;
case 9:
retval = (float)Convert.ToDouble(textEdit13.Text);
break;
case 10:
retval = (float)Convert.ToDouble(textEdit12.Text);
break;
}
return retval;
}
//private byte[] batt_korr_volt;
private int[] batt_korr_map;
private string ConvertBattKorrValue(int value)
{
float fval = (float)value;
fval *= 0.004F;
return fval.ToString("F3");
}
public int[] Batt_korr_map
{
get { return batt_korr_map; }
set
{
batt_korr_map = value;
// SET VALUES correctly
if (batt_korr_map.Length == 11)
{
// <GS-14042010> add correction factors
textEdit1.Text = ConvertBattKorrValue(batt_korr_map[10]);
textEdit2.Text = ConvertBattKorrValue(batt_korr_map[9]);
textEdit3.Text = ConvertBattKorrValue(batt_korr_map[8]);
textEdit4.Text = ConvertBattKorrValue(batt_korr_map[7]);
textEdit5.Text = ConvertBattKorrValue(batt_korr_map[6]);
textEdit6.Text = ConvertBattKorrValue(batt_korr_map[5]);
textEdit7.Text = ConvertBattKorrValue(batt_korr_map[4]);
textEdit8.Text = ConvertBattKorrValue(batt_korr_map[3]);
textEdit9.Text = ConvertBattKorrValue(batt_korr_map[2]);
textEdit10.Text = ConvertBattKorrValue(batt_korr_map[1]);
textEdit11.Text = ConvertBattKorrValue(batt_korr_map[0]);
}
}
}
private int _injectorConstant = 21;
private int _oriinjectorConstant = 21;
public int InjectorConstant
{
get { return _injectorConstant; }
set
{
_injectorConstant = value;
_oriinjectorConstant = _injectorConstant;
labelControl3.Text = _injectorConstant.ToString();
spinEdit1.EditValue = _injectorConstant;
}
}
private bool _progChanges = false;
private InjectorType _injectorType = InjectorType.Stock;
private InjectorType _oriinjectorType = InjectorType.Stock;
public InjectorType InjectorType
{
get { return _injectorType; }
set
{
_injectorType = value;
_oriinjectorType = _injectorType;
_progChanges = true;
comboBoxEdit1.SelectedIndex = (int)_injectorType;
SetInjectorBatteryCorrectionMap(_injectorType);
SetCrankFactor(_injectorType);
_progChanges = false;
}
}
private void SetInjectorBatteryCorrectionMap(InjectorType injectorType)
{
float tempvalue = 0;
switch (injectorType)
{
case InjectorType.Stock:
case InjectorType.Siemens875Dekas:
case InjectorType.Siemens1000cc:
tempvalue = 3.73F;
textEdit12.Text = tempvalue.ToString("F3"); // 5 volt
textEdit13.Text = tempvalue.ToString("F3"); // 6 volt
textEdit14.Text = tempvalue.ToString("F3"); // 7 volt
tempvalue = 2.32F;
textEdit15.Text = tempvalue.ToString("F3"); // 8 volt
tempvalue = 1.85F;
textEdit16.Text = tempvalue.ToString("F3"); // 9 volt
tempvalue = 1.50F;
textEdit17.Text = tempvalue.ToString("F3"); // 10 volt
tempvalue = 1.28F;
textEdit18.Text = tempvalue.ToString("F3"); // 11 volt
tempvalue = 0.94F;
textEdit19.Text = tempvalue.ToString("F3"); // 12 volt
tempvalue = 0.78F;
textEdit20.Text = tempvalue.ToString("F3"); // 13 volt
tempvalue = 0.77F;
textEdit21.Text = tempvalue.ToString("F3"); // 14 volt
tempvalue = 0.59F;
textEdit22.Text = tempvalue.ToString("F3"); // 15 volt
break;
case InjectorType.GreenGiants:
tempvalue = 5.45F;
textEdit12.Text = tempvalue.ToString("F3"); // 5 volt
tempvalue = 4.142F;
textEdit13.Text = tempvalue.ToString("F3"); // 6 volt
tempvalue = 3.216F;
textEdit14.Text = tempvalue.ToString("F3"); // 7 volt
tempvalue = 2.545F;
textEdit15.Text = tempvalue.ToString("F3"); // 8 volt
tempvalue = 2.102F;
textEdit16.Text = tempvalue.ToString("F3"); // 9 volt
tempvalue = 1.768F;
textEdit17.Text = tempvalue.ToString("F3"); // 10 volt
tempvalue = 1.521F;
textEdit18.Text = tempvalue.ToString("F3"); // 11 volt
tempvalue = 1.308F;
textEdit19.Text = tempvalue.ToString("F3"); // 12 volt
tempvalue = 1.15F;
textEdit20.Text = tempvalue.ToString("F3"); // 13 volt
tempvalue = 1.003F;
textEdit21.Text = tempvalue.ToString("F3"); // 14 volt
tempvalue = 0.894F;
textEdit22.Text = tempvalue.ToString("F3"); // 15 volt
break;
case InjectorType.Siemens630Dekas:
tempvalue = 3.6F;
textEdit12.Text = tempvalue.ToString("F3"); // 5 volt
tempvalue = 2.74F;
textEdit13.Text = tempvalue.ToString("F3"); // 6 volt
tempvalue = 2.023F;
textEdit14.Text = tempvalue.ToString("F3"); // 7 volt
tempvalue = 1.524F;
textEdit15.Text = tempvalue.ToString("F3"); // 8 volt
tempvalue = 1.208F;
textEdit16.Text = tempvalue.ToString("F3"); // 9 volt
tempvalue = 0.974F;
textEdit17.Text = tempvalue.ToString("F3"); // 10 volt
tempvalue = 0.802F;
textEdit18.Text = tempvalue.ToString("F3"); // 11 volt
tempvalue = 0.673F;
textEdit19.Text = tempvalue.ToString("F3"); // 12 volt
tempvalue = 0.548F;
textEdit20.Text = tempvalue.ToString("F3"); // 13 volt
tempvalue = 0.433F;
textEdit21.Text = tempvalue.ToString("F3"); // 14 volt
tempvalue = 0.33F;
textEdit22.Text = tempvalue.ToString("F3"); // 15 volt
break;
}
// set battery correction voltage maps
/*
* Siemens deka 875 Siemens Deka 630 stock
* Batt_korr_table
15v = 0.62 15v=0.17ms 0.59
14v = 0.73 14v=0.28ms 0.77
13v = 0.85 13v=0.38ms 0.78
12v = 1.00 12v=0.50ms 0.94
11v = 1.20 11v=0.64ms 1.28
10v = 1.46 10v=0.83ms 1.50
*/
}
private void comboBoxEdit1_SelectedIndexChanged(object sender, EventArgs e)
{
// user change injector type
if (!_progChanges)
{
// calculate the new proposed injector constant
_injectorType = (InjectorType)comboBoxEdit1.SelectedIndex;
if (_oriinjectorType == _injectorType)
{
_injectorConstant = _oriinjectorConstant;
}
else
{
Trionic5Tuner _tun = new Trionic5Tuner();
int diffInInjConstant = _tun.DetermineDifferenceInInjectorConstant(_oriinjectorType, _injectorType);
//<GS-04082010> the diff percentage seemed to cause trouble!
/*
float percentageToCompensate = _tun.DetermineDifferenceInInjectorConstantPercentage(_oriinjectorType, _injectorType);
// substract difference
_injectorConstant = (int)Math.Round(((float)_oriinjectorConstant * percentageToCompensate));
_injectorConstant++;*/
_injectorConstant = _oriinjectorConstant - diffInInjConstant;
}
//<GS-17052010> _injectorConstant = _oriinjectorConstant - diffInInjConstant;
//labelControl3.Text = _injectorConstant.ToString();
spinEdit1.EditValue = _injectorConstant;
// set the correction factor for the selected injectortype
SetInjectorBatteryCorrectionMap(_injectorType);
SetCrankFactor(_injectorType);
}
}
private void SetCrankFactor(InjectorType _type)
{
switch (_type)
{
case InjectorType.Stock:
case InjectorType.GreenGiants:
spinEdit2.EditValue = (decimal)9;
break;
case InjectorType.Siemens630Dekas:
spinEdit2.EditValue = (decimal)6;
break;
case InjectorType.Siemens875Dekas:
spinEdit2.EditValue = (decimal)4;
break;
case InjectorType.Siemens1000cc:
spinEdit2.EditValue = (decimal)3.5;
break;
}
}
private void wizardControl1_FinishClick(object sender, CancelEventArgs e)
{
DialogResult = DialogResult.OK;
this.Close();
}
private void wizardControl1_CancelClick(object sender, CancelEventArgs e)
{
DialogResult = DialogResult.Cancel;
this.Close();
}
private void spinEdit2_ValueChanged(object sender, EventArgs e)
{
_crankfactor = (float)Convert.ToDouble(spinEdit2.EditValue);
}
private void spinEdit1_ValueChanged(object sender, EventArgs e)
{
_injectorConstant = Convert.ToInt32(spinEdit1.EditValue);
}
private void frmInjectorWizard_Load(object sender, EventArgs e)
{
}
}
}
| |
//! \file ImagePT1.cs
//! \date Wed Apr 15 15:17:24 2015
//! \brief FFA System image format implementation.
//
// Copyright (C) 2015 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.Collections.Generic;
using System.ComponentModel.Composition;
using System.IO;
using System.Text;
using System.Windows;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using GameRes.Utility;
namespace GameRes.Formats.Ffa
{
internal class Pt1MetaData : ImageMetaData
{
public int Type;
public int PackedSize;
public int UnpackedSize;
}
[Export(typeof(ImageFormat))]
public class Pt1Format : ImageFormat
{
public override string Tag { get { return "PT1"; } }
public override string Description { get { return "FFA System RGB image format"; } }
public override uint Signature { get { return 2u; } }
public Pt1Format ()
{
Signatures = new uint[] { 3, 2, 1, 0 };
}
public override void Write (Stream file, ImageData image)
{
throw new NotImplementedException ("Pt1Format.Write not implemented");
}
public override ImageMetaData ReadMetaData (IBinaryStream file)
{
int type = file.ReadInt32();
if (type < 0 || type > 3)
return null;
if (-1 != file.ReadInt32())
return null;
int x = file.ReadInt32();
int y = file.ReadInt32();
uint width = file.ReadUInt32();
uint height = file.ReadUInt32();
int comp_size = file.ReadInt32();
int uncomp_size = file.ReadInt32();
if (uncomp_size != width*height*3u)
return null;
return new Pt1MetaData {
Width = width,
Height = height,
OffsetX = x,
OffsetY = y,
BPP = 3 == type ? 32 : 24,
Type = type,
PackedSize = comp_size,
UnpackedSize = uncomp_size
};
}
public override ImageData Read (IBinaryStream stream, ImageMetaData info)
{
var reader = new Reader (stream, (Pt1MetaData)info);
reader.Unpack();
return ImageData.Create (info, reader.Format, null, reader.Data);
}
internal class Reader
{
byte[] m_input;
byte[] m_output;
byte[] m_alpha_packed;
int m_type;
int m_width;
int m_height;
int m_stride;
public PixelFormat Format { get; private set; }
public byte[] Data { get { return m_output; } }
public Reader (IBinaryStream input, Pt1MetaData info)
{
m_type = info.Type;
m_input = new byte[info.PackedSize+8];
input.Position = 0x20;
if (info.PackedSize != input.Read (m_input, 0, info.PackedSize))
throw new InvalidFormatException ("Unexpected end of file");
m_width = (int)info.Width;
m_height = (int)info.Height;
m_output = new byte[info.UnpackedSize];
m_stride = m_width*3;
if (3 == m_type)
{
Format = PixelFormats.Bgra32;
int packed_size = input.ReadInt32();
m_alpha_packed = input.ReadBytes (packed_size);
if (m_alpha_packed.Length != packed_size)
throw new EndOfStreamException();
}
else
{
Format = PixelFormats.Bgr24;
}
}
public byte[] Unpack ()
{
switch (m_type)
{
case 3: UnpackV3(); break;
case 2: UnpackV2(); break;
case 1: UnpackV1(); break;
case 0: UnpackV0 (m_input, m_output); break;
}
return m_output;
}
void UnpackV3 ()
{
UnpackV2();
int total = m_width * m_height;
var alpha = new byte[total];
UnpackV0 (m_alpha_packed, alpha);
var pixels = new byte[total * 4];
int src = 0;
int dst = 0;
for (int i = 0; i < total; ++i)
{
pixels[dst++] = m_output[src++];
pixels[dst++] = m_output[src++];
pixels[dst++] = m_output[src++];
pixels[dst++] = alpha[i];
}
m_output = pixels;
}
uint edx;
byte ch;
int src;
void ReadNext ()
{
byte cl = (byte)(32 - ch);
edx &= 0xFFFFFFFFu >> cl;
edx += LittleEndian.ToUInt32 (m_input, src) << ch;
src += cl >> 3;
ch += (byte)(cl & 0xf8);
}
void UnpackV2 ()
{
src = 0;
int dst = 0;
Buffer.BlockCopy (m_input, src, m_output, dst, 3);
src += 3;
dst += 3;
edx = LittleEndian.ToUInt32 (m_input, src);
src += 3;
ch = 0x18;
uint _CF;
uint ebx;
sbyte ah;
byte al;
// [ebp+var_8] = i
for (int i = 1; i < m_width; ++i)
{
ReadNext();
_CF = edx & 1;
edx >>= 1;
if (0 != _CF)
{
--ch;
Buffer.BlockCopy (m_output, dst-3, m_output, dst, 3);
dst += 3;
}
else
{
ch -= 2;
_CF = edx & 1;
edx >>= 1;
if (0 != _CF)
{
ah = sub_4225EA();
al = (byte)(ah + m_output[dst-3]);
m_output[dst++] = al;
ReadNext();
ah = sub_4225EA();
al = (byte)(ah + m_output[dst-3]);
m_output[dst++] = al;
ReadNext();
ah = sub_4225EA();
al = (byte)(ah + m_output[dst-3]);
m_output[dst++] = al;
}
else
{
ReadNext();
LittleEndian.Pack ((ushort)edx, m_output, dst);
edx >>= 16;
m_output[dst+2] = (byte)edx;
dst += 3;
edx >>= 8;
ch -= 24;
}
}
}
for (int i = 1; i < m_height; ++i)
{
ReadNext();
_CF = edx & 1;
edx >>= 1;
if (0 != _CF)
{
--ch;
Buffer.BlockCopy (m_output, dst-m_stride, m_output, dst, 3);
dst += 3;
}
else // loc_42207F
{
ch -= 2;
_CF = edx & 1;
edx >>= 1;
if (0 != _CF)
{
ah = sub_4225EA();
al = (byte)(ah + m_output[dst-m_stride]);
m_output[dst++] = al;
ReadNext();
ah = sub_4225EA();
al = (byte)(ah + m_output[dst-m_stride]);
m_output[dst++] = al;
ReadNext();
ah = sub_4225EA();
al = (byte)(ah + m_output[dst-m_stride]);
m_output[dst++] = al;
}
else // loc_4220FC
{
ReadNext();
LittleEndian.Pack ((ushort)edx, m_output, dst);
edx >>= 16;
m_output[dst+2] = (byte)edx;
dst += 3;
edx >>= 8;
ch -= 24;
}
}
for (int j = 1; j < m_width; ++j)
{
ReadNext();
_CF = edx & 1;
edx >>= 1;
if (0 != _CF)
{
--ch;
ebx = (uint)(dst - m_stride);
ah = sub_4225EA();
al = (byte)(m_output[dst-3] - m_output[ebx-3] + m_output[ebx] + ah);
m_output[dst++] = al;
ReadNext();
ah = sub_4225EA();
al = (byte)(m_output[dst-3] - m_output[ebx-2] + m_output[ebx+1] + ah);
m_output[dst++] = al;
ReadNext();
ah = sub_4225EA();
al = (byte)(m_output[dst-3] - m_output[ebx-1] + m_output[ebx+2] + ah);
m_output[dst++] = al;
}
else
{
_CF = edx & 1;
edx >>= 1;
if (0 != _CF)
{
ch -= 2;
ebx = (uint)(dst - m_stride);
al = (byte)(m_output[dst-3] - m_output[ebx-3] + m_output[ebx]);
m_output[dst++] = al;
al = (byte)(m_output[dst-3] - m_output[ebx-2] + m_output[ebx+1]);
m_output[dst++] = al;
al = (byte)(m_output[dst-3] - m_output[ebx-1] + m_output[ebx+2]);
m_output[dst++] = al;
}
else
{
ebx = edx & 3;
if (3 == ebx)
{
edx >>= 2;
ch -= 4;
Buffer.BlockCopy (m_output, dst-3, m_output, dst, 3);
dst += 3;
}
else if (2 == ebx)
{
edx >>= 2;
ch -= 4;
ReadNext();
LittleEndian.Pack ((ushort)edx, m_output, dst);
edx >>= 16;
m_output[dst+2] = (byte)edx;
dst += 3;
edx >>= 8;
ch -= 24;
}
else if (1 == ebx)
{
edx >>= 2;
ch -= 4;
ah = sub_4225EA();
al = (byte)(ah + m_output[dst-3]);
m_output[dst++] = al;
ReadNext();
ah = sub_4225EA();
al = (byte)(ah + m_output[dst-3]);
m_output[dst++] = al;
ReadNext();
ah = sub_4225EA();
al = (byte)(ah + m_output[dst-3]);
m_output[dst++] = al;
}
else
{
ebx = edx & 0xf;
edx >>= 4;
ch -= 6;
if (0 == ebx)
{
Buffer.BlockCopy (m_output, dst - m_stride - 3, m_output, dst, 3);
dst += 3;
}
else if (8 == ebx)
{
Buffer.BlockCopy (m_output, dst - m_stride, m_output, dst, 3);
dst += 3;
}
else
{
int off = dst - m_stride;
if (4 == ebx) off -= 3;
ah = sub_4225EA();
m_output[dst++] = (byte)(ah + m_output[off++]);
ReadNext();
ah = sub_4225EA();
m_output[dst++] = (byte)(ah + m_output[off++]);
ReadNext();
ah = sub_4225EA();
m_output[dst++] = (byte)(ah + m_output[off++]);
}
}
}
}
}
}
}
sbyte sub_4225EA ()
{
uint _CF = edx & 1;
edx >>= 1;
if (0 != _CF)
{
--ch;
return 0;
}
uint bits = edx & 3;
if (2 == bits)
{
edx >>= 2;
ch -= 3;
return -1;
}
if (1 == bits)
{
edx >>= 2;
ch -= 3;
return 1;
}
switch (edx & 7)
{
case 7:
edx >>= 3;
ch -= 4;
return -2;
case 3:
edx >>= 3;
ch -= 4;
return 2;
case 4:
edx >>= 3;
ch -= 4;
return -3;
default:
switch (edx & 0x3f)
{
case 0x38:
edx >>= 6;
ch -= 7;
return 3;
case 0x18:
edx >>= 6;
ch -= 7;
return -4;
case 0x28:
edx >>= 6;
ch -= 7;
return 4;
case 0x08:
edx >>= 6;
ch -= 7;
return -5;
case 0x30:
edx >>= 6;
ch -= 7;
return 5;
case 0x10:
edx >>= 6;
ch -= 7;
return -6;
case 0x20:
edx >>= 6;
ch -= 7;
return 6;
default:
switch (edx & 0xff)
{
case 0xc0:
edx >>= 8;
ch -= 9;
return -7;
case 0x40:
edx >>= 8;
ch -= 9;
return 7;
case 0x80:
edx >>= 8;
ch -= 9;
return -8;
default:
switch (edx & 0x3ff)
{
case 0x300:
edx >>= 10;
ch -= 11;
return 8;
case 0x100:
edx >>= 10;
ch -= 11;
return -9;
case 0x200:
edx >>= 10;
ch -= 11;
return 9;
default:
switch (edx & 0xfff)
{
case 0xc00:
edx >>= 12;
ch -= 13;
return -10;
case 0x400:
edx >>= 12;
ch -= 13;
return 10;
case 0x800:
edx >>= 12;
ch -= 13;
return -11;
default:
switch (edx & 0x3fff)
{
case 0x3000:
edx >>= 14;
ch -= 15;
return 0x0b;
case 0x1000:
edx >>= 14;
ch -= 15;
return -12;
case 0x2000:
edx >>= 14;
ch -= 15;
return 0x0c;
default:
edx >>= 14;
ch -= 15;
return -13;
}
}
}
}
}
}
}
void UnpackV1 ()
{
int src = 0; // dword_462E74
int dst = 0; // dword_462E78
byte[] frame = new byte[0x1000]; // word_461A28
PopulateLzssFrame (frame);
int ebp = 0xfee;
while (src < m_input.Length)
{
byte ah = m_input[src++];
for (int mask = 1; mask != 0x100; mask <<= 1)
{
if (0 != (ah & mask))
{
byte al = m_input[src++];
frame[ebp++] = al;
ebp &= 0xfff;
m_output[dst++] = al;
m_output[dst++] = al;
m_output[dst++] = al;
}
else
{
int offset = m_input[src++];
int count = m_input[src++];
offset |= (count & 0xf0) << 4;
count = (count & 0x0f) + 3;
for (; count != 0; --count)
{
byte al = frame[offset++];
frame[ebp++] = al;
offset &= 0xfff;
ebp &= 0xfff;
m_output[dst++] = al;
m_output[dst++] = al;
m_output[dst++] = al;
}
}
if (dst >= m_output.Length)
return;
}
}
}
void UnpackV0 (byte[] input, byte[] output)
{
int src = 0;
int dst = 0;
byte[] frame = new byte[0x1000]; // word_461A28
PopulateLzssFrame (frame);
int ebp = 0xfee;
while (src < input.Length)
{
byte ah = input[src++];
for (int mask = 1; mask != 0x100; mask <<= 1)
{
if (0 != (ah & mask))
{
byte al = input[src++];
frame[ebp++] = al;
ebp &= 0xfff;
output[dst++] = al;
}
else
{
int offset = input[src++];
int count = input[src++];
offset |= (count & 0xf0) << 4;
count = (count & 0x0f) + 3;
for (int i = 0; i < count; ++i)
{
byte al = frame[offset++];
frame[ebp++] = al;
offset &= 0xfff;
ebp &= 0xfff;
output[dst++] = al;
}
}
if (dst >= output.Length)
return;
}
}
}
void PopulateLzssFrame (byte[] frame)
{
int fill = 0;
int ecx;
for (int al = 0; al < 0x100; ++al)
for (ecx = 0x0d; ecx > 0; --ecx)
frame[fill++] = (byte)al;
for (int al = 0; al < 0x100; ++al)
frame[fill++] = (byte)al;
for (int al = 0xff; al >= 0; --al)
frame[fill++] = (byte)al;
for (ecx = 0x80; ecx > 0; --ecx)
frame[fill++] = 0;
for (ecx = 0x6e; ecx > 0; --ecx)
frame[fill++] = 0x20;
for (ecx = 0x12; ecx > 0; --ecx)
frame[fill++] = 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.Runtime;
using System.Xml;
namespace System.ServiceModel.Channels
{
internal abstract class AddressingHeader : DictionaryHeader, IMessageHeaderWithSharedNamespace
{
private AddressingVersion _version;
protected AddressingHeader(AddressingVersion version)
{
_version = version;
}
internal AddressingVersion Version
{
get { return _version; }
}
XmlDictionaryString IMessageHeaderWithSharedNamespace.SharedPrefix
{
get { return XD.AddressingDictionary.Prefix; }
}
XmlDictionaryString IMessageHeaderWithSharedNamespace.SharedNamespace
{
get { return _version.DictionaryNamespace; }
}
public override XmlDictionaryString DictionaryNamespace
{
get { return _version.DictionaryNamespace; }
}
}
internal class ActionHeader : AddressingHeader
{
private string _action;
private const bool mustUnderstandValue = true;
private ActionHeader(string action, AddressingVersion version)
: base(version)
{
_action = action;
}
public string Action
{
get { return _action; }
}
public override bool MustUnderstand
{
get { return mustUnderstandValue; }
}
public override XmlDictionaryString DictionaryName
{
get { return XD.AddressingDictionary.Action; }
}
public static ActionHeader Create(string action, AddressingVersion addressingVersion)
{
if (action == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("action"));
if (addressingVersion == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("addressingVersion");
return new ActionHeader(action, addressingVersion);
}
public static ActionHeader Create(XmlDictionaryString dictionaryAction, AddressingVersion addressingVersion)
{
if (dictionaryAction == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("action"));
if (addressingVersion == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("addressingVersion");
return new DictionaryActionHeader(dictionaryAction, addressingVersion);
}
protected override void OnWriteHeaderContents(XmlDictionaryWriter writer, MessageVersion messageVersion)
{
writer.WriteString(_action);
}
public static string ReadHeaderValue(XmlDictionaryReader reader, AddressingVersion addressingVersion)
{
Fx.Assert(reader.IsStartElement(XD.AddressingDictionary.Action, addressingVersion.DictionaryNamespace), "");
string act = reader.ReadElementContentAsString();
if (act.Length > 0 && (act[0] <= 32 || act[act.Length - 1] <= 32))
act = XmlUtil.Trim(act);
return act;
}
public static ActionHeader ReadHeader(XmlDictionaryReader reader, AddressingVersion version,
string actor, bool mustUnderstand, bool relay)
{
string action = ReadHeaderValue(reader, version);
if (actor.Length == 0 && mustUnderstand == mustUnderstandValue && !relay)
{
return new ActionHeader(action, version);
}
else
{
return new FullActionHeader(action, actor, mustUnderstand, relay, version);
}
}
internal class DictionaryActionHeader : ActionHeader
{
private XmlDictionaryString _dictionaryAction;
public DictionaryActionHeader(XmlDictionaryString dictionaryAction, AddressingVersion version)
: base(dictionaryAction.Value, version)
{
_dictionaryAction = dictionaryAction;
}
protected override void OnWriteHeaderContents(XmlDictionaryWriter writer, MessageVersion messageVersion)
{
writer.WriteString(_dictionaryAction);
}
}
internal class FullActionHeader : ActionHeader
{
private string _actor;
private bool _mustUnderstand;
private bool _relay;
public FullActionHeader(string action, string actor, bool mustUnderstand, bool relay, AddressingVersion version)
: base(action, version)
{
_actor = actor;
_mustUnderstand = mustUnderstand;
_relay = relay;
}
public override string Actor
{
get { return _actor; }
}
public override bool MustUnderstand
{
get { return _mustUnderstand; }
}
public override bool Relay
{
get { return _relay; }
}
}
}
internal class FromHeader : AddressingHeader
{
private EndpointAddress _from;
private const bool mustUnderstandValue = false;
private FromHeader(EndpointAddress from, AddressingVersion version)
: base(version)
{
_from = from;
}
public EndpointAddress From
{
get { return _from; }
}
public override XmlDictionaryString DictionaryName
{
get { return XD.AddressingDictionary.From; }
}
public override bool MustUnderstand
{
get { return mustUnderstandValue; }
}
public static FromHeader Create(EndpointAddress from, AddressingVersion addressingVersion)
{
if (from == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("from"));
if (addressingVersion == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("addressingVersion");
return new FromHeader(from, addressingVersion);
}
protected override void OnWriteHeaderContents(XmlDictionaryWriter writer, MessageVersion messageVersion)
{
_from.WriteContentsTo(this.Version, writer);
}
public static FromHeader ReadHeader(XmlDictionaryReader reader, AddressingVersion version,
string actor, bool mustUnderstand, bool relay)
{
EndpointAddress from = ReadHeaderValue(reader, version);
if (actor.Length == 0 && mustUnderstand == mustUnderstandValue && !relay)
{
return new FromHeader(from, version);
}
else
{
return new FullFromHeader(from, actor, mustUnderstand, relay, version);
}
}
public static EndpointAddress ReadHeaderValue(XmlDictionaryReader reader, AddressingVersion addressingVersion)
{
Fx.Assert(reader.IsStartElement(XD.AddressingDictionary.From, addressingVersion.DictionaryNamespace), "");
return EndpointAddress.ReadFrom(addressingVersion, reader);
}
internal class FullFromHeader : FromHeader
{
private string _actor;
private bool _mustUnderstand;
private bool _relay;
public FullFromHeader(EndpointAddress from, string actor, bool mustUnderstand, bool relay, AddressingVersion version)
: base(from, version)
{
_actor = actor;
_mustUnderstand = mustUnderstand;
_relay = relay;
}
public override string Actor
{
get { return _actor; }
}
public override bool MustUnderstand
{
get { return _mustUnderstand; }
}
public override bool Relay
{
get { return _relay; }
}
}
}
internal class FaultToHeader : AddressingHeader
{
private EndpointAddress _faultTo;
private const bool mustUnderstandValue = false;
private FaultToHeader(EndpointAddress faultTo, AddressingVersion version)
: base(version)
{
_faultTo = faultTo;
}
public EndpointAddress FaultTo
{
get { return _faultTo; }
}
public override XmlDictionaryString DictionaryName
{
get { return XD.AddressingDictionary.FaultTo; }
}
public override bool MustUnderstand
{
get { return mustUnderstandValue; }
}
protected override void OnWriteHeaderContents(XmlDictionaryWriter writer, MessageVersion messageVersion)
{
_faultTo.WriteContentsTo(this.Version, writer);
}
public static FaultToHeader Create(EndpointAddress faultTo, AddressingVersion addressingVersion)
{
if (faultTo == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("faultTo"));
if (addressingVersion == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("addressingVersion");
return new FaultToHeader(faultTo, addressingVersion);
}
public static FaultToHeader ReadHeader(XmlDictionaryReader reader, AddressingVersion version,
string actor, bool mustUnderstand, bool relay)
{
EndpointAddress faultTo = ReadHeaderValue(reader, version);
if (actor.Length == 0 && mustUnderstand == mustUnderstandValue && !relay)
{
return new FaultToHeader(faultTo, version);
}
else
{
return new FullFaultToHeader(faultTo, actor, mustUnderstand, relay, version);
}
}
public static EndpointAddress ReadHeaderValue(XmlDictionaryReader reader, AddressingVersion version)
{
Fx.Assert(reader.IsStartElement(XD.AddressingDictionary.FaultTo, version.DictionaryNamespace), "");
return EndpointAddress.ReadFrom(version, reader);
}
internal class FullFaultToHeader : FaultToHeader
{
private string _actor;
private bool _mustUnderstand;
private bool _relay;
public FullFaultToHeader(EndpointAddress faultTo, string actor, bool mustUnderstand, bool relay, AddressingVersion version)
: base(faultTo, version)
{
_actor = actor;
_mustUnderstand = mustUnderstand;
_relay = relay;
}
public override string Actor
{
get { return _actor; }
}
public override bool MustUnderstand
{
get { return _mustUnderstand; }
}
public override bool Relay
{
get { return _relay; }
}
}
}
internal class ToHeader : AddressingHeader
{
private Uri _to;
private const bool mustUnderstandValue = true;
private static ToHeader s_anonymousToHeader10;
protected ToHeader(Uri to, AddressingVersion version)
: base(version)
{
_to = to;
}
private static ToHeader AnonymousTo10
{
get
{
if (s_anonymousToHeader10 == null)
s_anonymousToHeader10 = new AnonymousToHeader(AddressingVersion.WSAddressing10);
return s_anonymousToHeader10;
}
}
public override XmlDictionaryString DictionaryName
{
get { return XD.AddressingDictionary.To; }
}
public override bool MustUnderstand
{
get { return mustUnderstandValue; }
}
public Uri To
{
get { return _to; }
}
public static ToHeader Create(Uri toUri, XmlDictionaryString dictionaryTo, AddressingVersion addressingVersion)
{
if (addressingVersion == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("addressingVersion");
if (((object)toUri == (object)addressingVersion.AnonymousUri))
{
if (addressingVersion == AddressingVersion.WSAddressing10)
return AnonymousTo10;
else
// Verify that only WSA10 is supported
throw ExceptionHelper.PlatformNotSupported();
}
else
{
return new DictionaryToHeader(toUri, dictionaryTo, addressingVersion);
}
}
public static ToHeader Create(Uri to, AddressingVersion addressingVersion)
{
if ((object)to == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("to"));
}
else if ((object)to == (object)addressingVersion.AnonymousUri)
{
if (addressingVersion == AddressingVersion.WSAddressing10)
return AnonymousTo10;
else
// Verify that only WSA10 is supported
throw ExceptionHelper.PlatformNotSupported();
}
else
{
return new ToHeader(to, addressingVersion);
}
}
protected override void OnWriteHeaderContents(XmlDictionaryWriter writer, MessageVersion messageVersion)
{
writer.WriteString(_to.AbsoluteUri);
}
public static Uri ReadHeaderValue(XmlDictionaryReader reader, AddressingVersion version)
{
return ReadHeaderValue(reader, version, null);
}
public static Uri ReadHeaderValue(XmlDictionaryReader reader, AddressingVersion version, UriCache uriCache)
{
Fx.Assert(reader.IsStartElement(XD.AddressingDictionary.To, version.DictionaryNamespace), "");
string toString = reader.ReadElementContentAsString();
if ((object)toString == (object)version.Anonymous)
{
return version.AnonymousUri;
}
if (uriCache == null)
{
return new Uri(toString);
}
return uriCache.CreateUri(toString);
}
public static ToHeader ReadHeader(XmlDictionaryReader reader, AddressingVersion version, UriCache uriCache,
string actor, bool mustUnderstand, bool relay)
{
Uri to = ReadHeaderValue(reader, version, uriCache);
if (actor.Length == 0 && mustUnderstand == mustUnderstandValue && !relay)
{
if ((object)to == (object)version.Anonymous)
{
if (version == AddressingVersion.WSAddressing10)
return AnonymousTo10;
else
throw ExceptionHelper.PlatformNotSupported();
}
else
{
return new ToHeader(to, version);
}
}
else
{
return new FullToHeader(to, actor, mustUnderstand, relay, version);
}
}
private class AnonymousToHeader : ToHeader
{
public AnonymousToHeader(AddressingVersion version)
: base(version.AnonymousUri, version)
{
}
protected override void OnWriteHeaderContents(XmlDictionaryWriter writer, MessageVersion messageVersion)
{
writer.WriteString(this.Version.DictionaryAnonymous);
}
}
internal class DictionaryToHeader : ToHeader
{
private XmlDictionaryString _dictionaryTo;
public DictionaryToHeader(Uri to, XmlDictionaryString dictionaryTo, AddressingVersion version)
: base(to, version)
{
_dictionaryTo = dictionaryTo;
}
protected override void OnWriteHeaderContents(XmlDictionaryWriter writer, MessageVersion messageVersion)
{
writer.WriteString(_dictionaryTo);
}
}
internal class FullToHeader : ToHeader
{
private string _actor;
private bool _mustUnderstand;
private bool _relay;
public FullToHeader(Uri to, string actor, bool mustUnderstand, bool relay, AddressingVersion version)
: base(to, version)
{
_actor = actor;
_mustUnderstand = mustUnderstand;
_relay = relay;
}
public override string Actor
{
get { return _actor; }
}
public override bool MustUnderstand
{
get { return _mustUnderstand; }
}
public override bool Relay
{
get { return _relay; }
}
}
}
internal class ReplyToHeader : AddressingHeader
{
private EndpointAddress _replyTo;
private const bool mustUnderstandValue = false;
private static ReplyToHeader s_anonymousReplyToHeader10;
private ReplyToHeader(EndpointAddress replyTo, AddressingVersion version)
: base(version)
{
_replyTo = replyTo;
}
public EndpointAddress ReplyTo
{
get { return _replyTo; }
}
public override XmlDictionaryString DictionaryName
{
get { return XD.AddressingDictionary.ReplyTo; }
}
public override bool MustUnderstand
{
get { return mustUnderstandValue; }
}
public static ReplyToHeader AnonymousReplyTo10
{
get
{
if (s_anonymousReplyToHeader10 == null)
s_anonymousReplyToHeader10 = new ReplyToHeader(EndpointAddress.AnonymousAddress, AddressingVersion.WSAddressing10);
return s_anonymousReplyToHeader10;
}
}
public static ReplyToHeader Create(EndpointAddress replyTo, AddressingVersion addressingVersion)
{
if (replyTo == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("replyTo"));
if (addressingVersion == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("addressingVersion"));
return new ReplyToHeader(replyTo, addressingVersion);
}
protected override void OnWriteHeaderContents(XmlDictionaryWriter writer, MessageVersion messageVersion)
{
_replyTo.WriteContentsTo(this.Version, writer);
}
public static ReplyToHeader ReadHeader(XmlDictionaryReader reader, AddressingVersion version,
string actor, bool mustUnderstand, bool relay)
{
EndpointAddress replyTo = ReadHeaderValue(reader, version);
if (actor.Length == 0 && mustUnderstand == mustUnderstandValue && !relay)
{
if ((object)replyTo == (object)EndpointAddress.AnonymousAddress)
{
if (version == AddressingVersion.WSAddressing10)
return AnonymousReplyTo10;
else
// Verify that only WSA10 is supported
throw ExceptionHelper.PlatformNotSupported();
}
return new ReplyToHeader(replyTo, version);
}
else
{
return new FullReplyToHeader(replyTo, actor, mustUnderstand, relay, version);
}
}
public static EndpointAddress ReadHeaderValue(XmlDictionaryReader reader, AddressingVersion version)
{
Fx.Assert(reader.IsStartElement(XD.AddressingDictionary.ReplyTo, version.DictionaryNamespace), "");
return EndpointAddress.ReadFrom(version, reader);
}
internal class FullReplyToHeader : ReplyToHeader
{
private string _actor;
private bool _mustUnderstand;
private bool _relay;
public FullReplyToHeader(EndpointAddress replyTo, string actor, bool mustUnderstand, bool relay, AddressingVersion version)
: base(replyTo, version)
{
_actor = actor;
_mustUnderstand = mustUnderstand;
_relay = relay;
}
public override string Actor
{
get { return _actor; }
}
public override bool MustUnderstand
{
get { return _mustUnderstand; }
}
public override bool Relay
{
get { return _relay; }
}
}
}
internal class MessageIDHeader : AddressingHeader
{
private UniqueId _messageId;
private const bool mustUnderstandValue = false;
private MessageIDHeader(UniqueId messageId, AddressingVersion version)
: base(version)
{
_messageId = messageId;
}
public override XmlDictionaryString DictionaryName
{
get { return XD.AddressingDictionary.MessageId; }
}
public UniqueId MessageId
{
get { return _messageId; }
}
public override bool MustUnderstand
{
get { return mustUnderstandValue; }
}
public static MessageIDHeader Create(UniqueId messageId, AddressingVersion addressingVersion)
{
if (object.ReferenceEquals(messageId, null))
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("messageId"));
if (addressingVersion == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("addressingVersion"));
return new MessageIDHeader(messageId, addressingVersion);
}
protected override void OnWriteHeaderContents(XmlDictionaryWriter writer, MessageVersion messageVersion)
{
writer.WriteValue(_messageId);
}
public static UniqueId ReadHeaderValue(XmlDictionaryReader reader, AddressingVersion version)
{
Fx.Assert(reader.IsStartElement(XD.AddressingDictionary.MessageId, version.DictionaryNamespace), "");
return reader.ReadElementContentAsUniqueId();
}
public static MessageIDHeader ReadHeader(XmlDictionaryReader reader, AddressingVersion version,
string actor, bool mustUnderstand, bool relay)
{
UniqueId messageId = ReadHeaderValue(reader, version);
if (actor.Length == 0 && mustUnderstand == mustUnderstandValue && !relay)
{
return new MessageIDHeader(messageId, version);
}
else
{
return new FullMessageIDHeader(messageId, actor, mustUnderstand, relay, version);
}
}
internal class FullMessageIDHeader : MessageIDHeader
{
private string _actor;
private bool _mustUnderstand;
private bool _relay;
public FullMessageIDHeader(UniqueId messageId, string actor, bool mustUnderstand, bool relay, AddressingVersion version)
: base(messageId, version)
{
_actor = actor;
_mustUnderstand = mustUnderstand;
_relay = relay;
}
public override string Actor
{
get { return _actor; }
}
public override bool MustUnderstand
{
get { return _mustUnderstand; }
}
public override bool Relay
{
get { return _relay; }
}
}
}
internal class RelatesToHeader : AddressingHeader
{
private UniqueId _messageId;
private const bool mustUnderstandValue = false;
internal static readonly Uri ReplyRelationshipType = new Uri(Addressing10Strings.ReplyRelationship);
private RelatesToHeader(UniqueId messageId, AddressingVersion version)
: base(version)
{
_messageId = messageId;
}
public override XmlDictionaryString DictionaryName
{
get { return XD.AddressingDictionary.RelatesTo; }
}
public UniqueId UniqueId
{
get { return _messageId; }
}
public override bool MustUnderstand
{
get { return mustUnderstandValue; }
}
public virtual Uri RelationshipType
{
get { return ReplyRelationshipType; }
}
public static RelatesToHeader Create(UniqueId messageId, AddressingVersion addressingVersion)
{
if (object.ReferenceEquals(messageId, null))
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("messageId"));
if (addressingVersion == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("addressingVersion"));
return new RelatesToHeader(messageId, addressingVersion);
}
public static RelatesToHeader Create(UniqueId messageId, AddressingVersion addressingVersion, Uri relationshipType)
{
if (object.ReferenceEquals(messageId, null))
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("messageId"));
if (addressingVersion == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("addressingVersion"));
if (relationshipType == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("relationshipType"));
if (relationshipType == ReplyRelationshipType)
{
return new RelatesToHeader(messageId, addressingVersion);
}
else
{
return new FullRelatesToHeader(messageId, "", false, false, addressingVersion);
}
}
protected override void OnWriteHeaderContents(XmlDictionaryWriter writer, MessageVersion messageVersion)
{
writer.WriteValue(_messageId);
}
public static void ReadHeaderValue(XmlDictionaryReader reader, AddressingVersion version, out Uri relationshipType, out UniqueId messageId)
{
AddressingDictionary addressingDictionary = XD.AddressingDictionary;
// The RelationshipType attribute has no namespace.
relationshipType = ReplyRelationshipType;
/*
string relation = reader.GetAttribute(addressingDictionary.RelationshipType, addressingDictionary.Empty);
if (relation == null)
{
relationshipType = ReplyRelationshipType;
}
else
{
relationshipType = new Uri(relation);
}
*/
Fx.Assert(reader.IsStartElement(addressingDictionary.RelatesTo, version.DictionaryNamespace), "");
messageId = reader.ReadElementContentAsUniqueId();
}
public static RelatesToHeader ReadHeader(XmlDictionaryReader reader, AddressingVersion version,
string actor, bool mustUnderstand, bool relay)
{
UniqueId messageId;
Uri relationship;
ReadHeaderValue(reader, version, out relationship, out messageId);
if (actor.Length == 0 && mustUnderstand == mustUnderstandValue && !relay && (object)relationship == (object)ReplyRelationshipType)
{
return new RelatesToHeader(messageId, version);
}
else
{
return new FullRelatesToHeader(messageId, actor, mustUnderstand, relay, version);
}
}
internal class FullRelatesToHeader : RelatesToHeader
{
private string _actor;
private bool _mustUnderstand;
private bool _relay;
//Uri relationship;
public FullRelatesToHeader(UniqueId messageId, string actor, bool mustUnderstand, bool relay, AddressingVersion version)
: base(messageId, version)
{
//this.relationship = relationship;
_actor = actor;
_mustUnderstand = mustUnderstand;
_relay = relay;
}
public override string Actor
{
get { return _actor; }
}
public override bool MustUnderstand
{
get { return _mustUnderstand; }
}
/*
public override Uri RelationshipType
{
get { return relationship; }
}
*/
public override bool Relay
{
get { return _relay; }
}
protected override void OnWriteHeaderContents(XmlDictionaryWriter writer, MessageVersion messageVersion)
{
/*
if ((object)relationship != (object)ReplyRelationshipType)
{
// The RelationshipType attribute has no namespace.
writer.WriteStartAttribute(AddressingStrings.RelationshipType, AddressingStrings.Empty);
writer.WriteString(relationship.AbsoluteUri);
writer.WriteEndAttribute();
}
*/
writer.WriteValue(_messageId);
}
}
}
}
| |
//
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Warning: This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if the
// code is regenerated.
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Azure.Management.StreamAnalytics.Models;
namespace Microsoft.Azure.Management.StreamAnalytics.Models
{
/// <summary>
/// The properties of the stream analytics job.
/// </summary>
public partial class JobProperties
{
private System.DateTime? _createdDate;
/// <summary>
/// Optional. Gets the created date of the stream analytics job.
/// </summary>
public System.DateTime? CreatedDate
{
get { return this._createdDate; }
set { this._createdDate = value; }
}
private string _dataLocale;
/// <summary>
/// Optional. Gets or sets the data locale of the stream analytics job.
/// Value should be the name of a supported .NET Culture from the set
/// https://msdn.microsoft.com/en-us/library/system.globalization.culturetypes(v=vs.110).aspx.
/// Defaults to "en-US" if none specified.
/// </summary>
public string DataLocale
{
get { return this._dataLocale; }
set { this._dataLocale = value; }
}
private string _etag;
/// <summary>
/// Optional. Gets the etag of the stream analytics job.
/// </summary>
public string Etag
{
get { return this._etag; }
set { this._etag = value; }
}
private int? _eventsLateArrivalMaxDelayInSeconds;
/// <summary>
/// Optional. Gets or sets the maximum tolerable delay in seconds where
/// events arriving late could be included. Supported range is -1 to
/// 1814399 (20.23:59:59 days) and -1 is used to specify wait
/// indefinitely. If the property is absent, it is interpreted to have
/// a value of -1.
/// </summary>
public int? EventsLateArrivalMaxDelayInSeconds
{
get { return this._eventsLateArrivalMaxDelayInSeconds; }
set { this._eventsLateArrivalMaxDelayInSeconds = value; }
}
private int? _eventsOutOfOrderMaxDelayInSeconds;
/// <summary>
/// Optional. Gets or sets the maximum tolerable delay in seconds where
/// out-of-order events can be adjusted to be back in order.
/// </summary>
public int? EventsOutOfOrderMaxDelayInSeconds
{
get { return this._eventsOutOfOrderMaxDelayInSeconds; }
set { this._eventsOutOfOrderMaxDelayInSeconds = value; }
}
private string _eventsOutOfOrderPolicy;
/// <summary>
/// Optional. Gets or sets the out of order policy of the stream
/// analytics job. Indicates the policy to apply to events that arrive
/// out of order in the input event stream.
/// </summary>
public string EventsOutOfOrderPolicy
{
get { return this._eventsOutOfOrderPolicy; }
set { this._eventsOutOfOrderPolicy = value; }
}
private IList<Input> _inputs;
/// <summary>
/// Optional. Gets or sets a list of one or more inputs.
/// </summary>
public IList<Input> Inputs
{
get { return this._inputs; }
set { this._inputs = value; }
}
private string _jobId;
/// <summary>
/// Optional. Gets the id of the stream analytics job.
/// </summary>
public string JobId
{
get { return this._jobId; }
set { this._jobId = value; }
}
private string _jobState;
/// <summary>
/// Optional. Gets the running state of the stream analytics job.
/// </summary>
public string JobState
{
get { return this._jobState; }
set { this._jobState = value; }
}
private System.DateTime? _lastOutputEventTime;
/// <summary>
/// Optional. Gets the last output event time of the stream analytics
/// job.
/// </summary>
public System.DateTime? LastOutputEventTime
{
get { return this._lastOutputEventTime; }
set { this._lastOutputEventTime = value; }
}
private IList<Output> _outputs;
/// <summary>
/// Optional. Gets or sets a list of outputs.
/// </summary>
public IList<Output> Outputs
{
get { return this._outputs; }
set { this._outputs = value; }
}
private string _outputStartMode;
/// <summary>
/// Optional. Gets or sets the output start mode of the stream
/// analytics job.
/// </summary>
public string OutputStartMode
{
get { return this._outputStartMode; }
set { this._outputStartMode = value; }
}
private System.DateTime? _outputStartTime;
/// <summary>
/// Optional. Gets or sets the output start time of the stream
/// analytics job.
/// </summary>
public System.DateTime? OutputStartTime
{
get { return this._outputStartTime; }
set { this._outputStartTime = value; }
}
private string _provisioningState;
/// <summary>
/// Optional. Gets the provisioning state of the stream analytics job.
/// </summary>
public string ProvisioningState
{
get { return this._provisioningState; }
set { this._provisioningState = value; }
}
private Sku _sku;
/// <summary>
/// Optional. Gets or sets the Sku of the stream analytics job.
/// </summary>
public Sku Sku
{
get { return this._sku; }
set { this._sku = value; }
}
private Transformation _transformation;
/// <summary>
/// Optional. Gets or sets the transformation definition, including the
/// query and the streaming unit count.
/// </summary>
public Transformation Transformation
{
get { return this._transformation; }
set { this._transformation = value; }
}
/// <summary>
/// Initializes a new instance of the JobProperties class.
/// </summary>
public JobProperties()
{
}
}
}
| |
/*
*
* (c) Copyright Ascensio System Limited 2010-2021
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using ASC.Core;
using ASC.Files.Core;
using ASC.Web.Core.Files;
using File = ASC.Files.Core.File;
namespace ASC.Files.Thirdparty.SharePoint
{
internal class SharePointFileDao : SharePointDaoBase, IFileDao
{
public SharePointFileDao(SharePointProviderInfo sharePointInfo, SharePointDaoSelector sharePointDaoSelector)
: base(sharePointInfo, sharePointDaoSelector)
{
}
public void Dispose()
{
ProviderInfo.Dispose();
}
public void InvalidateCache(object fileId)
{
ProviderInfo.InvalidateStorage();
}
public File GetFile(object fileId)
{
return GetFile(fileId, 1);
}
public File GetFile(object fileId, int fileVersion)
{
return ProviderInfo.ToFile(ProviderInfo.GetFileById(fileId));
}
public File GetFile(object parentId, string title)
{
return ProviderInfo.ToFile(ProviderInfo.GetFolderFiles(parentId).FirstOrDefault(item => item.Name.Equals(title, StringComparison.InvariantCultureIgnoreCase)));
}
public File GetFileStable(object fileId, int fileVersion)
{
return ProviderInfo.ToFile(ProviderInfo.GetFileById(fileId));
}
public List<File> GetFileHistory(object fileId)
{
return new List<File> { GetFile(fileId) };
}
public List<File> GetFiles(IEnumerable<object> fileIds)
{
return fileIds.Select(fileId => ProviderInfo.ToFile(ProviderInfo.GetFileById(fileId))).ToList();
}
public List<File> GetFilesFiltered(IEnumerable<object> fileIds, FilterType filterType, bool subjectGroup, Guid subjectID, string searchText, bool searchInContent)
{
if (fileIds == null || !fileIds.Any() || filterType == FilterType.FoldersOnly) return new List<File>();
var files = GetFiles(fileIds).AsEnumerable();
//Filter
if (subjectID != Guid.Empty)
{
files = files.Where(x => subjectGroup
? CoreContext.UserManager.IsUserInGroup(x.CreateBy, subjectID)
: x.CreateBy == subjectID);
}
switch (filterType)
{
case FilterType.FoldersOnly:
return new List<File>();
case FilterType.DocumentsOnly:
files = files.Where(x => FileUtility.GetFileTypeByFileName(x.Title) == FileType.Document);
break;
case FilterType.PresentationsOnly:
files = files.Where(x => FileUtility.GetFileTypeByFileName(x.Title) == FileType.Presentation);
break;
case FilterType.SpreadsheetsOnly:
files = files.Where(x => FileUtility.GetFileTypeByFileName(x.Title) == FileType.Spreadsheet);
break;
case FilterType.ImagesOnly:
files = files.Where(x => FileUtility.GetFileTypeByFileName(x.Title) == FileType.Image);
break;
case FilterType.ArchiveOnly:
files = files.Where(x => FileUtility.GetFileTypeByFileName(x.Title) == FileType.Archive);
break;
case FilterType.MediaOnly:
files = files.Where(x =>
{
FileType fileType;
return (fileType = FileUtility.GetFileTypeByFileName(x.Title)) == FileType.Audio || fileType == FileType.Video;
});
break;
case FilterType.ByExtension:
if (!string.IsNullOrEmpty(searchText))
{
searchText = searchText.Trim().ToLower();
files = files.Where(x => FileUtility.GetFileExtension(x.Title).Equals(searchText));
}
break;
}
if (!string.IsNullOrEmpty(searchText))
files = files.Where(x => x.Title.IndexOf(searchText, StringComparison.OrdinalIgnoreCase) != -1);
return files.ToList();
}
public List<object> GetFiles(object parentId)
{
return ProviderInfo.GetFolderFiles(parentId).Select(r => ProviderInfo.ToFile(r).ID).ToList();
}
public List<File> GetFiles(object parentId, OrderBy orderBy, FilterType filterType, bool subjectGroup, Guid subjectID, string searchText, bool searchInContent, bool withSubfolders = false)
{
if (filterType == FilterType.FoldersOnly) return new List<File>();
//Get only files
var files = ProviderInfo.GetFolderFiles(parentId).Select(r => ProviderInfo.ToFile(r));
//Filter
if (subjectID != Guid.Empty)
{
files = files.Where(x => subjectGroup
? CoreContext.UserManager.IsUserInGroup(x.CreateBy, subjectID)
: x.CreateBy == subjectID);
}
switch (filterType)
{
case FilterType.FoldersOnly:
return new List<File>();
case FilterType.DocumentsOnly:
files = files.Where(x => FileUtility.GetFileTypeByFileName(x.Title) == FileType.Document).ToList();
break;
case FilterType.PresentationsOnly:
files = files.Where(x => FileUtility.GetFileTypeByFileName(x.Title) == FileType.Presentation).ToList();
break;
case FilterType.SpreadsheetsOnly:
files = files.Where(x => FileUtility.GetFileTypeByFileName(x.Title) == FileType.Spreadsheet).ToList();
break;
case FilterType.ImagesOnly:
files = files.Where(x => FileUtility.GetFileTypeByFileName(x.Title) == FileType.Image).ToList();
break;
case FilterType.ArchiveOnly:
files = files.Where(x => FileUtility.GetFileTypeByFileName(x.Title) == FileType.Archive).ToList();
break;
case FilterType.MediaOnly:
files = files.Where(x =>
{
FileType fileType;
return (fileType = FileUtility.GetFileTypeByFileName(x.Title)) == FileType.Audio || fileType == FileType.Video;
});
break;
case FilterType.ByExtension:
if (!string.IsNullOrEmpty(searchText))
{
searchText = searchText.Trim().ToLower();
files = files.Where(x => FileUtility.GetFileExtension(x.Title).Equals(searchText));
}
break;
}
if (!string.IsNullOrEmpty(searchText))
files = files.Where(x => x.Title.IndexOf(searchText, StringComparison.OrdinalIgnoreCase) != -1).ToList();
if (orderBy == null) orderBy = new OrderBy(SortedByType.DateAndTime, false);
switch (orderBy.SortedBy)
{
case SortedByType.Author:
files = orderBy.IsAsc ? files.OrderBy(x => x.CreateBy) : files.OrderByDescending(x => x.CreateBy);
break;
case SortedByType.AZ:
files = orderBy.IsAsc ? files.OrderBy(x => x.Title) : files.OrderByDescending(x => x.Title);
break;
case SortedByType.DateAndTime:
files = orderBy.IsAsc ? files.OrderBy(x => x.ModifiedOn) : files.OrderByDescending(x => x.ModifiedOn);
break;
case SortedByType.DateAndTimeCreation:
files = orderBy.IsAsc ? files.OrderBy(x => x.CreateOn) : files.OrderByDescending(x => x.CreateOn);
break;
default:
files = orderBy.IsAsc ? files.OrderBy(x => x.Title) : files.OrderByDescending(x => x.Title);
break;
}
return files.ToList();
}
public Stream GetFileStream(File file)
{
return GetFileStream(file, 0);
}
public Stream GetFileStream(File file, long offset)
{
var fileToDownload = ProviderInfo.GetFileById(file.ID);
if (fileToDownload == null)
throw new ArgumentNullException("file", Web.Files.Resources.FilesCommonResource.ErrorMassage_FileNotFound);
var fileStream = ProviderInfo.GetFileStream(fileToDownload.ServerRelativeUrl, (int)offset);
return fileStream;
}
public Uri GetPreSignedUri(File file, TimeSpan expires)
{
throw new NotSupportedException();
}
public bool IsSupportedPreSignedUri(File file)
{
return false;
}
public File SaveFile(File file, Stream fileStream)
{
if (fileStream == null) throw new ArgumentNullException("fileStream");
if (file.ID != null)
{
var sharePointFile = ProviderInfo.CreateFile((string)file.ID, fileStream);
var resultFile = ProviderInfo.ToFile(sharePointFile);
if (!sharePointFile.Name.Equals(file.Title))
{
var folder = ProviderInfo.GetFolderById(file.FolderID);
file.Title = GetAvailableTitle(file.Title, folder, IsExist);
var id = ProviderInfo.RenameFile(SharePointDaoSelector.ConvertId(resultFile.ID).ToString(), file.Title);
return GetFile(SharePointDaoSelector.ConvertId(id));
}
return resultFile;
}
if (file.FolderID != null)
{
var folder = ProviderInfo.GetFolderById(file.FolderID);
file.Title = GetAvailableTitle(file.Title, folder, IsExist);
return ProviderInfo.ToFile(ProviderInfo.CreateFile(folder.ServerRelativeUrl + "/" + file.Title, fileStream));
}
return null;
}
public File ReplaceFileVersion(File file, Stream fileStream)
{
return SaveFile(file, fileStream);
}
public void DeleteFile(object fileId)
{
ProviderInfo.DeleteFile((string)fileId);
}
public bool IsExist(string title, object folderId)
{
return ProviderInfo.GetFolderFiles(folderId)
.Any(item => item.Name.Equals(title, StringComparison.InvariantCultureIgnoreCase));
}
public bool IsExist(string title, Microsoft.SharePoint.Client.Folder folder)
{
return ProviderInfo.GetFolderFiles(folder.ServerRelativeUrl)
.Any(item => item.Name.Equals(title, StringComparison.InvariantCultureIgnoreCase));
}
public object MoveFile(object fileId, object toFolderId)
{
var newFileId = ProviderInfo.MoveFile(fileId, toFolderId);
UpdatePathInDB(ProviderInfo.MakeId((string)fileId), (string)newFileId);
return newFileId;
}
public File CopyFile(object fileId, object toFolderId)
{
return ProviderInfo.ToFile(ProviderInfo.CopyFile(fileId, toFolderId));
}
public object FileRename(File file, string newTitle)
{
var newFileId = ProviderInfo.RenameFile((string)file.ID, newTitle);
UpdatePathInDB(ProviderInfo.MakeId((string)file.ID), (string)newFileId);
return newFileId;
}
public string UpdateComment(object fileId, int fileVersion, string comment)
{
return string.Empty;
}
public void CompleteVersion(object fileId, int fileVersion)
{
}
public void ContinueVersion(object fileId, int fileVersion)
{
}
public bool UseTrashForRemove(File file)
{
return false;
}
public ChunkedUploadSession CreateUploadSession(File file, long contentLength)
{
return new ChunkedUploadSession(FixId(file), contentLength) { UseChunks = false };
}
public File UploadChunk(ChunkedUploadSession uploadSession, Stream chunkStream, long chunkLength)
{
if (!uploadSession.UseChunks)
{
if (uploadSession.BytesTotal == 0)
uploadSession.BytesTotal = chunkLength;
uploadSession.File = SaveFile(uploadSession.File, chunkStream);
uploadSession.BytesUploaded = chunkLength;
return uploadSession.File;
}
throw new NotImplementedException();
}
public void AbortUploadSession(ChunkedUploadSession uploadSession)
{
//throw new NotImplementedException();
}
private File FixId(File file)
{
if (file.ID != null)
file.ID = ProviderInfo.MakeId((string)file.ID);
if (file.FolderID != null)
file.FolderID = ProviderInfo.MakeId((string)file.FolderID);
return file;
}
#region Only in TMFileDao
public void ReassignFiles(IEnumerable<object> fileIds, Guid newOwnerId)
{
}
public List<File> GetFiles(IEnumerable<object> parentIds, FilterType filterType, bool subjectGroup, Guid subjectID, string searchText, bool searchInContent)
{
return new List<File>();
}
public IEnumerable<File> Search(string text, bool bunch)
{
return null;
}
public bool IsExistOnStorage(File file)
{
return true;
}
public void SaveEditHistory(File file, string changes, Stream differenceStream)
{
//Do nothing
}
public List<EditHistory> GetEditHistory(object fileId, int fileVersion)
{
return null;
}
public Stream GetDifferenceStream(File file)
{
return null;
}
public bool ContainChanges(object fileId, int fileVersion)
{
return false;
}
public void SaveThumbnail(File file, Stream thumbnail)
{
//Do nothing
}
public Stream GetThumbnail(File file)
{
return null;
}
public Task<Stream> GetFileStreamAsync(File file)
{
return Task.FromResult(GetFileStream(file));
}
public Task<bool> IsExistOnStorageAsync(File file)
{
return Task.FromResult(IsExistOnStorage(file));
}
#endregion
}
}
| |
using NUnit.Framework;
using System;
using System.Collections.Generic;
using System.ComponentModel;
namespace DevExpress.Mvvm.Tests {
[TestFixture]
public class WeakEventTests {
class EventOwner {
WeakEvent<EventHandler, EventArgs> myEvent = new WeakEvent<EventHandler, EventArgs>();
public event EventHandler MyEvent { add { myEvent.Add(value); } remove { myEvent.Remove(value); } }
public void RaiseMyEvent(EventArgs e) {
myEvent.Raise(this, e);
}
public void RaiseMyEvent(object sender, EventArgs e) {
myEvent.Raise(sender, e);
}
static WeakEvent<EventHandler, EventArgs> myStaticEvent = new WeakEvent<EventHandler, EventArgs>();
public static event EventHandler MyStaticEvent { add { myStaticEvent.Add(value); } remove { myStaticEvent.Remove(value); } }
public void RaiseMyStaticEvent(EventArgs e) {
myStaticEvent.Raise(this, e);
}
public void RaiseMyStaticEvent(object sender, EventArgs e) {
myStaticEvent.Raise(sender, e);
}
WeakEvent<Action<object, string>, string> myEvent2 = new WeakEvent<Action<object, string>, string>();
public event Action<object, string> MyEvent2 { add { myEvent2.Add(value); } remove { myEvent2.Remove(value); } }
public void RaiseMyEvent2(string args) {
myEvent2.Raise(this, args);
}
}
class Subscriber {
public object Sender { get; private set; }
public EventArgs E { get; private set; }
public int Count { get; private set; }
public void Clear() {
Sender = null;
E = null;
Count = 0;
}
public void Subscribe(EventOwner eventOwner) {
eventOwner.MyEvent += OnMyEvent;
}
public void SubscribeTwice(EventOwner eventOwner) {
EventHandler h = null;
h += OnMyEvent;
h += OnMyEvent;
eventOwner.MyEvent += h;
}
public void Unsubscribe(EventOwner eventOwner) {
eventOwner.MyEvent -= OnMyEvent;
}
void OnMyEvent(object sender, EventArgs e) {
Sender = sender;
E = e;
Count++;
}
public void SubscribeStaticEvent(EventOwner eventOwner) {
EventOwner.MyStaticEvent += OnMyEvent;
}
public void SubscribeStaticEventTwice(EventOwner eventOwner) {
EventHandler h = null;
h += OnMyEvent;
h += OnMyEvent;
EventOwner.MyStaticEvent += h;
}
public void UnsubscribeStaticEvent(EventOwner eventOwner) {
EventOwner.MyStaticEvent -= OnMyEvent;
}
void OnMyStaticEvent(object sender, EventArgs e) {
Sender = sender;
E = e;
Count++;
}
}
class Subscriber2 {
public bool _PublicOnEvent { get; private set; }
bool _PrivateOnEvent { get; set; }
internal bool _InternalOnEvent { get; set; }
static bool _StaticOnEvent { get; set; }
public void PublicOnEvent(object sender, EventArgs e) { _PublicOnEvent = true; }
void PrivateOnEvent(object sender, EventArgs e) { _PrivateOnEvent = true; }
internal void InternalOnEvent(object sender, EventArgs e) { _InternalOnEvent = true; }
static void StaticOnEvent(object sender, EventArgs e) { _StaticOnEvent = true; }
public void SubscribePublic(EventOwner e, bool stat) {
if(stat) EventOwner.MyStaticEvent += PublicOnEvent;
else e.MyEvent += PublicOnEvent;
}
public void SubscribePrivate(EventOwner e, bool stat) {
if(stat) EventOwner.MyStaticEvent += PrivateOnEvent;
else e.MyEvent += PrivateOnEvent;
}
public void SubscribeInternal(EventOwner e, bool stat) {
if(stat) EventOwner.MyStaticEvent += InternalOnEvent;
else e.MyEvent += InternalOnEvent;
}
public void SibscribeStatic(EventOwner e, bool stat) {
if(stat) EventOwner.MyStaticEvent += StaticOnEvent;
else e.MyEvent += StaticOnEvent;
}
public void SibscribeAnonymousPublic(EventOwner e, bool stat) {
if(stat)
EventOwner.MyStaticEvent += (s, args) => _PublicOnEvent = args != null;
else e.MyEvent += (s, args) => _PublicOnEvent = args != null;
}
public void SibscribeAnonymousPrivate(EventOwner e, bool stat) {
if(stat)
EventOwner.MyStaticEvent += (s, args) => _PrivateOnEvent = args != null;
else e.MyEvent += (s, args) => _PrivateOnEvent = args != null;
}
public void SibscribeAnonymousInternal(EventOwner e, bool stat) {
if(stat)
EventOwner.MyStaticEvent += (s, args) => _InternalOnEvent = args != null;
else e.MyEvent += (s, args) => _InternalOnEvent = args != null;
}
public void SibscribeAnonymousStatic(EventOwner e, bool stat) {
if(stat)
EventOwner.MyStaticEvent += (s, args) => _StaticOnEvent = args != null;
else e.MyEvent += (s, args) => _StaticOnEvent = args != null;
}
public void Clear() {
_PublicOnEvent = false;
_PrivateOnEvent = false;
_InternalOnEvent = false;
_StaticOnEvent = false;
}
public void CheckPublic() { Assert.AreEqual(true, _PublicOnEvent); }
public void CheckPrivate() { Assert.AreEqual(true, _PrivateOnEvent); }
public void CheckInternal() { Assert.AreEqual(true, _InternalOnEvent); }
public void CheckStatic() { Assert.AreEqual(true, _StaticOnEvent); }
}
[Test]
public void SubscribeUnsubscribe() {
SubscribeUnsubsribeCore(false, (e, args) => e.RaiseMyEvent(args), (e, sender, args) => e.RaiseMyEvent(sender, args),
(s, e) => s.Subscribe(e), (s, e) => s.SubscribeTwice(e), (s, e) => s.Unsubscribe(e));
SubscribeUnsubsribeCore(true, (e, args) => e.RaiseMyEvent(args), (e, sender, args) => e.RaiseMyEvent(sender, args),
(s, e) => s.Subscribe(e), (s, e) => s.SubscribeTwice(e), (s, e) => s.Unsubscribe(e));
SubscribeUnsubsribeCore(false, (e, args) => e.RaiseMyStaticEvent(args), (e, sender, args) => e.RaiseMyStaticEvent(sender, args),
(s, e) => s.SubscribeStaticEvent(e), (s, e) => s.SubscribeStaticEventTwice(e), (s, e) => s.UnsubscribeStaticEvent(e));
SubscribeUnsubsribeCore(true, (e, args) => e.RaiseMyStaticEvent(args), (e, sender, args) => e.RaiseMyStaticEvent(sender, args),
(s, e) => s.SubscribeStaticEvent(e), (s, e) => s.SubscribeStaticEventTwice(e), (s, e) => s.UnsubscribeStaticEvent(e));
}
void SubscribeUnsubsribeCore(bool passSender, Action<EventOwner, EventArgs> raiseMyEvent1, Action<EventOwner, object, EventArgs> raiseMyEvent2,
Action<Subscriber, EventOwner> subscribe, Action<Subscriber, EventOwner> subscribeTwice, Action<Subscriber, EventOwner> unsubscribe) {
var e = new EventOwner();
var sender = passSender ? new object() : e;
var args = new PropertyChangedEventArgs("Test");
Action raise = () => {
if(passSender) raiseMyEvent2(e, sender, args);
else raiseMyEvent1(e, args);
};
WeakReference sRef = SubscribeUnsubsribeCoreAlloc(e, sender, args, raise, raiseMyEvent1, raiseMyEvent2, subscribe, subscribeTwice, unsubscribe);
MemoryLeaksHelper.CollectOptional(sRef);
MemoryLeaksHelper.EnsureCollected(sRef);
raise();
}
WeakReference SubscribeUnsubsribeCoreAlloc(EventOwner e, object sender, PropertyChangedEventArgs args, Action raise,
Action<EventOwner, EventArgs> raiseMyEvent1, Action<EventOwner, object, EventArgs> raiseMyEvent2,
Action<Subscriber, EventOwner> subscribe, Action<Subscriber, EventOwner> subscribeTwice, Action<Subscriber, EventOwner> unsubscribe) {
var s = new Subscriber();
subscribe(s, e);
raise();
Assert.AreEqual(sender, s.Sender);
Assert.AreEqual(args, s.E);
Assert.AreEqual(1, s.Count);
raise();
Assert.AreEqual(sender, s.Sender);
Assert.AreEqual(args, s.E);
Assert.AreEqual(2, s.Count);
s.Clear();
subscribe(s, e);
raise();
Assert.AreEqual(sender, s.Sender);
Assert.AreEqual(args, s.E);
Assert.AreEqual(2, s.Count);
s.Clear();
unsubscribe(s, e);
raise();
Assert.AreEqual(sender, s.Sender);
Assert.AreEqual(args, s.E);
Assert.AreEqual(1, s.Count);
s.Clear();
unsubscribe(s, e);
raise();
Assert.AreEqual(null, s.Sender);
Assert.AreEqual(null, s.E);
Assert.AreEqual(0, s.Count);
s.Clear();
subscribeTwice(s, e);
raise();
Assert.AreEqual(sender, s.Sender);
Assert.AreEqual(args, s.E);
Assert.AreEqual(2, s.Count);
unsubscribe(s, e);
unsubscribe(s, e);
unsubscribe(s, e);
subscribe(s, e);
return new WeakReference(s);
}
[Test]
public void Memory() {
MemoryCore((s, e) => s.SubscribePublic(e, false), (s) => s.CheckPublic(), (e) => e.RaiseMyEvent(EventArgs.Empty));
MemoryCore((s, e) => s.SubscribePrivate(e, false), (s) => s.CheckPrivate(), (e) => e.RaiseMyEvent(EventArgs.Empty));
MemoryCore((s, e) => s.SubscribeInternal(e, false), (s) => s.CheckInternal(), (e) => e.RaiseMyEvent(EventArgs.Empty));
MemoryCore((s, e) => s.SibscribeStatic(e, false), (s) => s.CheckStatic(), (e) => e.RaiseMyEvent(EventArgs.Empty));
MemoryCore((s, e) => s.SibscribeAnonymousPublic(e, false), (s) => s.CheckPublic(), (e) => e.RaiseMyEvent(EventArgs.Empty));
MemoryCore((s, e) => s.SibscribeAnonymousPrivate(e, false), (s) => s.CheckPrivate(), (e) => e.RaiseMyEvent(EventArgs.Empty));
MemoryCore((s, e) => s.SibscribeAnonymousInternal(e, false), (s) => s.CheckInternal(), (e) => e.RaiseMyEvent(EventArgs.Empty));
MemoryCore((s, e) => s.SibscribeAnonymousStatic(e, false), (s) => s.CheckStatic(), (e) => e.RaiseMyEvent(EventArgs.Empty));
MemoryCore((s, e) => s.SubscribePublic(e, true), (s) => s.CheckPublic(), (e) => e.RaiseMyStaticEvent(EventArgs.Empty));
MemoryCore((s, e) => s.SubscribePrivate(e, true), (s) => s.CheckPrivate(), (e) => e.RaiseMyStaticEvent(EventArgs.Empty));
MemoryCore((s, e) => s.SubscribeInternal(e, true), (s) => s.CheckInternal(), (e) => e.RaiseMyStaticEvent(EventArgs.Empty));
MemoryCore((s, e) => s.SibscribeStatic(e, true), (s) => s.CheckStatic(), (e) => e.RaiseMyStaticEvent(EventArgs.Empty));
MemoryCore((s, e) => s.SibscribeAnonymousPublic(e, true), (s) => s.CheckPublic(), (e) => e.RaiseMyStaticEvent(EventArgs.Empty));
MemoryCore((s, e) => s.SibscribeAnonymousPrivate(e, true), (s) => s.CheckPrivate(), (e) => e.RaiseMyStaticEvent(EventArgs.Empty));
MemoryCore((s, e) => s.SibscribeAnonymousInternal(e, true), (s) => s.CheckInternal(), (e) => e.RaiseMyStaticEvent(EventArgs.Empty));
MemoryCore((s, e) => s.SibscribeAnonymousStatic(e, true), (s) => s.CheckStatic(), (e) => e.RaiseMyStaticEvent(EventArgs.Empty));
}
void MemoryCore(Action<Subscriber2, EventOwner> subscribe, Action<Subscriber2> check, Action<EventOwner> raise) {
WeakReference sRef = MemoryCoreAlloc(subscribe, check, raise);
Collect();
Assert.AreEqual(false, sRef.IsAlive);
}
WeakReference MemoryCoreAlloc(Action<Subscriber2, EventOwner> subscribe, Action<Subscriber2> check, Action<EventOwner> raise) {
EventOwner e = new EventOwner();
Subscriber2 s = new Subscriber2();
subscribe(s, e);
Collect();
raise(e);
check(s);
s.Clear();
return new WeakReference(s);
}
[Test]
public void Order() {
var e = new EventOwner();
List<string> args = new List<string>();
e.MyEvent2 += (s, x) => args.Add("first");
e.MyEvent2 += (s, x) => args.Add("second");
e.RaiseMyEvent2("test");
Assert.AreEqual("first", args[0]);
Assert.AreEqual("second", args[1]);
}
void Collect() {
GC.GetTotalMemory(true);
GC.WaitForPendingFinalizers();
GC.GetTotalMemory(true);
}
[Test]
public void T846808() {
var eventOwner = new EventOwner();
int c1 = 0;
int c2 = 0;
EventHandler h1 = null;
EventHandler h2 = null;
h1 = (s, e) => { c1++; eventOwner.MyEvent -= h1; };
h2 = (s, e) => { c2++; };
eventOwner.MyEvent += h1;
eventOwner.MyEvent += h2;
eventOwner.RaiseMyEvent(EventArgs.Empty);
Assert.AreEqual(1, c1);
Assert.AreEqual(1, c2);
eventOwner.RaiseMyEvent(EventArgs.Empty);
Assert.AreEqual(1, c1);
Assert.AreEqual(2, c2);
}
}
}
| |
// Copyright 1998-2016 Epic Games, Inc. All Rights Reserved.
using UnrealBuildTool;
using System.IO;
using System.Text.RegularExpressions;
using System.Collections.Generic;
using Tools.DotNETCommon;
public class UnrealEnginePython : ModuleRules
{
// leave this string as empty for triggering auto-discovery of python installations...
private string pythonHome = "";
// otherwise specify the path of your python installation
//private string pythonHome = "C:/Program Files/Python36";
// this is an example for Homebrew on Mac
//private string pythonHome = "/usr/local/Cellar/python3/3.6.0/Frameworks/Python.framework/Versions/3.6/";
// on Linux an include;libs syntax is expected:
//private string pythonHome = "/usr/local/include/python3.6;/usr/local/lib/libpython3.6.so"
private string[] windowsKnownPaths =
{
"../../../../../ThirdParty/Python3",
"C:/Program Files/Python37",
"C:/Program Files/Python36",
"C:/Program Files/Python35",
"C:/Python27",
"C:/IntelPython35"
};
private string[] macKnownPaths =
{
"/Library/Frameworks/Python.framework/Versions/3.7",
"/Library/Frameworks/Python.framework/Versions/3.6",
"/Library/Frameworks/Python.framework/Versions/3.5",
"/Library/Frameworks/Python.framework/Versions/2.7",
"/System/Library/Frameworks/Python.framework/Versions/3.7",
"/System/Library/Frameworks/Python.framework/Versions/3.6",
"/System/Library/Frameworks/Python.framework/Versions/3.5",
"/System/Library/Frameworks/Python.framework/Versions/2.7"
};
private string[] linuxKnownIncludesPaths =
{
"/usr/local/include/python3.7",
"/usr/local/include/python3.7m",
"/usr/local/include/python3.6",
"/usr/local/include/python3.6m",
"/usr/local/include/python3.5",
"/usr/local/include/python3.5m",
"/usr/local/include/python2.7",
"/usr/include/python3.7",
"/usr/include/python3.7m",
"/usr/include/python3.6",
"/usr/include/python3.6m",
"/usr/include/python3.5",
"/usr/include/python3.5m",
"/usr/include/python2.7",
};
private string[] linuxKnownLibsPaths =
{
"/usr/local/lib/libpython3.7.so",
"/usr/local/lib/libpython3.7m.so",
"/usr/local/lib/x86_64-linux-gnu/libpython3.7.so",
"/usr/local/lib/x86_64-linux-gnu/libpython3.7m.so",
"/usr/local/lib/libpython3.6.so",
"/usr/local/lib/libpython3.6m.so",
"/usr/local/lib/x86_64-linux-gnu/libpython3.6.so",
"/usr/local/lib/x86_64-linux-gnu/libpython3.6m.so",
"/usr/local/lib/libpython3.5.so",
"/usr/local/lib/libpython3.5m.so",
"/usr/local/lib/x86_64-linux-gnu/libpython3.5.so",
"/usr/local/lib/x86_64-linux-gnu/libpython3.5m.so",
"/usr/local/lib/libpython2.7.so",
"/usr/local/lib/x86_64-linux-gnu/libpython2.7.so",
"/usr/lib/libpython3.7.so",
"/usr/lib/libpython3.7m.so",
"/usr/lib/x86_64-linux-gnu/libpython3.7.so",
"/usr/lib/x86_64-linux-gnu/libpython3.7m.so",
"/usr/lib/libpython3.6.so",
"/usr/lib/libpython3.6m.so",
"/usr/lib/x86_64-linux-gnu/libpython3.6.so",
"/usr/lib/x86_64-linux-gnu/libpython3.6m.so",
"/usr/lib/libpython3.5.so",
"/usr/lib/libpython3.5m.so",
"/usr/lib/x86_64-linux-gnu/libpython3.5.so",
"/usr/lib/x86_64-linux-gnu/libpython3.5m.so",
"/usr/lib/libpython2.7.so",
"/usr/lib/x86_64-linux-gnu/libpython2.7.so",
};
#if WITH_FORWARDED_MODULE_RULES_CTOR
public UnrealEnginePython(ReadOnlyTargetRules Target) : base(Target)
#else
public UnrealEnginePython(TargetInfo Target)
#endif
{
// @third party code - BEGIN Bebylon - #ThirdParty-Python: WITH_KNL_PYEXT - Workaround for our deployment process
PublicDefinitions.Add("WITH_KNL_PYEXT=1");
// @third party code - END Bebylon
PCHUsage = ModuleRules.PCHUsageMode.UseExplicitOrSharedPCHs;
// @third party code - BEGIN Bebylon - #ThirdParty-Python: Add UnrealEnginePython Plugin PrivatePCH file
PrivatePCHHeaderFile = Path.Combine(ModuleDirectory, "Private/UnrealEnginePythonPrivatePCH.h");
// @third party code - END Bebylon
string enableUnityBuild = System.Environment.GetEnvironmentVariable("UEP_ENABLE_UNITY_BUILD");
bFasterWithoutUnity = string.IsNullOrEmpty(enableUnityBuild);
PublicIncludePaths.AddRange(
new string[] {
Path.Combine(ModuleDirectory, "Public"),
// ... add public include paths required here ...
}
);
PrivateIncludePaths.AddRange(
new string[] {
Path.Combine(ModuleDirectory, "Private"),
// ... add other private include paths required here ...
Path.Combine(EngineDirectory, "Source/Runtime/Slate/Private"),
Path.Combine(EngineDirectory, "Source/Editor/Sequencer/Private"),
}
);
PublicDependencyModuleNames.AddRange(
new string[]
{
"Core",
"Sockets",
"Networking"
// ... add other public dependencies that you statically link with here ...
}
);
PrivateDependencyModuleNames.AddRange(
new string[]
{
"CoreUObject",
"Engine",
"InputCore",
"Slate",
"SlateCore",
"MovieScene",
"LevelSequence",
"HTTP",
"UMG",
"AppFramework",
"RHI",
"Voice",
"RenderCore",
"MovieSceneCapture",
"Landscape",
"Foliage",
"AIModule"
// ... add private dependencies that you statically link with here ...
}
);
#if WITH_FORWARDED_MODULE_RULES_CTOR
BuildVersion Version;
if (BuildVersion.TryRead(BuildVersion.GetDefaultFileName(), out Version))
{
if (Version.MinorVersion >= 18)
{
PrivateDependencyModuleNames.Add("ApplicationCore");
}
}
#endif
DynamicallyLoadedModuleNames.AddRange(
new string[]
{
// ... add any modules that your module loads dynamically here ...
}
);
#if WITH_FORWARDED_MODULE_RULES_CTOR
if (Target.bBuildEditor)
#else
if (UEBuildConfiguration.bBuildEditor)
#endif
{
PrivateDependencyModuleNames.AddRange(new string[]{
"UnrealEd",
"LevelEditor",
"BlueprintGraph",
"Projects",
"Sequencer",
"SequencerWidgets",
"AssetTools",
"LevelSequenceEditor",
"MovieSceneTools",
"MovieSceneTracks",
"CinematicCamera",
"EditorStyle",
"GraphEditor",
"UMGEditor",
"AIGraph",
"RawMesh",
"DesktopWidgets",
"EditorWidgets",
"FBX",
"Persona",
"PropertyEditor",
"LandscapeEditor",
"MaterialEditor"
});
}
if ((Target.Platform == UnrealTargetPlatform.Win64) || (Target.Platform == UnrealTargetPlatform.Win32))
{
if (pythonHome == "")
{
pythonHome = DiscoverPythonPath(windowsKnownPaths, "Win64");
if (pythonHome == "")
{
throw new System.Exception("Unable to find Python installation");
}
}
Log.TraceInformation("Using Python at: {0}", pythonHome);
PublicSystemIncludePaths.Add(pythonHome);
string libPath = GetWindowsPythonLibFile(pythonHome);
PublicLibraryPaths.Add(Path.GetDirectoryName(libPath));
//PublicAdditionalLibraries.Add(libPath);
//string py3DllPath = Path.Combine(pythonHome, "python3.dll");
//string py36DllPath = Path.Combine(pythonHome, "python36.dll");
//Log.TraceInformation(py3DllPath);
//Log.TraceInformation(py36DllPath);
//PublicDelayLoadDLLs.Add(py3DllPath);
//PublicDelayLoadDLLs.Add(py36DllPath);
//RuntimeDependencies.Add(py3DllPath);
//RuntimeDependencies.Add(py36DllPath);
//AdditionalLinkArguments += " /NODEFAULTLIB:\"python36_d\"";
//AdditionalLinkArguments += " /NODEFAULTLIB:\"python3\"";
//AdditionalLinkArguments += " /NODEFAULTLIB:\"python36\"";
}
else if (Target.Platform == UnrealTargetPlatform.Mac)
{
if (pythonHome == "")
{
pythonHome = DiscoverPythonPath(macKnownPaths, "Mac");
if (pythonHome == "")
{
throw new System.Exception("Unable to find Python installation");
}
}
Log.TraceInformation("Using Python at: {0}", pythonHome);
PublicIncludePaths.Add(pythonHome);
string libPath = GetMacPythonLibFile(pythonHome);
PublicLibraryPaths.Add(Path.GetDirectoryName(libPath));
PublicDelayLoadDLLs.Add(libPath);
}
else if (Target.Platform == UnrealTargetPlatform.Linux)
{
if (pythonHome == "")
{
string includesPath = DiscoverLinuxPythonIncludesPath();
if (includesPath == null)
{
throw new System.Exception("Unable to find Python includes, please add a search path to linuxKnownIncludesPaths");
}
string libsPath = DiscoverLinuxPythonLibsPath();
if (libsPath == null)
{
throw new System.Exception("Unable to find Python libs, please add a search path to linuxKnownLibsPaths");
}
PublicIncludePaths.Add(includesPath);
PublicAdditionalLibraries.Add(libsPath);
}
else
{
string[] items = pythonHome.Split(';');
PublicIncludePaths.Add(items[0]);
PublicAdditionalLibraries.Add(items[1]);
}
}
#if WITH_FORWARDED_MODULE_RULES_CTOR
else if (Target.Platform == UnrealTargetPlatform.Android)
{
PublicIncludePaths.Add(System.IO.Path.Combine(ModuleDirectory, "../../android/python35/include"));
PublicLibraryPaths.Add(System.IO.Path.Combine(ModuleDirectory, "../../android/armeabi-v7a"));
PublicAdditionalLibraries.Add("python3.5m");
string APLName = "UnrealEnginePython_APL.xml";
string RelAPLPath = Utils.MakePathRelativeTo(System.IO.Path.Combine(ModuleDirectory, APLName), Target.RelativeEnginePath);
AdditionalPropertiesForReceipt.Add("AndroidPlugin", RelAPLPath);
}
#endif
}
private bool IsPathRelative(string Path)
{
bool IsRooted = Path.StartsWith("\\", System.StringComparison.Ordinal) || // Root of the current directory on Windows. Also covers "\\" for UNC or "network" paths.
Path.StartsWith("/", System.StringComparison.Ordinal) || // Root of the current directory on Windows, root on UNIX-likes.
// Also covers "\\", considering normalization replaces "\\" with "//".
(Path.Length >= 2 && char.IsLetter(Path[0]) && Path[1] == ':'); // Starts with "<DriveLetter>:"
return !IsRooted;
}
/// <summary>
/// Regex that matches environment variables in $(Variable) format.
/// </summary>
static Regex EnvironmentVariableRegex = new Regex("\\$\\(([\\d\\w]+)\\)");
/// <summary>
/// Replaces the environment variables references in a string with their values.
/// </summary>
public string UEExpandEnvironmentVariables(string Text)
{
Text = Text.Replace("%GAMEDIR%", "$(GAMEDIR)");
Text = Utils.ExpandVariables(Text, new Dictionary<string, string>(){ { "GAMEDIR", Target.ProjectFile.Directory.ToNormalizedPath() + "/" } } );
return Text;
}
private string DiscoverPythonPath(string[] knownPaths, string binaryPath)
{
// insert the PYTHONHOME content as the first known path
List<string> paths = new List<string>(knownPaths);
paths.Insert(0, Path.Combine(ModuleDirectory, "../../Binaries", binaryPath));
string environmentPath = System.Environment.GetEnvironmentVariable("PYTHONHOME");
if (!string.IsNullOrEmpty(environmentPath))
{ paths.Insert(0, environmentPath); }
{
List<string> absoluteHomePaths;
ConfigHierarchy pluginIni = ConfigCache.ReadHierarchy(ConfigHierarchyType.Engine, Target.ProjectFile.Directory, Target.Platform);
pluginIni.GetArray("Python", "Home", out absoluteHomePaths);
foreach (string absoluteHomePath in absoluteHomePaths)
{
string expandedPath = UEExpandEnvironmentVariables(absoluteHomePath);
if (!string.IsNullOrEmpty(expandedPath))
{ paths.Insert(0, expandedPath); }
}
}
{
string relativeHomePath = "";
ConfigHierarchy pluginIni = ConfigCache.ReadHierarchy(ConfigHierarchyType.Engine, Target.ProjectFile.Directory, Target.Platform);
pluginIni.GetString("Python", "RelativeHome", out relativeHomePath);
relativeHomePath = UEExpandEnvironmentVariables(relativeHomePath);
if (!string.IsNullOrEmpty(relativeHomePath))
{ paths.Insert(0, Path.Combine(EngineDirectory, relativeHomePath)); }
}
// look in an alternate custom location
environmentPath = System.Environment.GetEnvironmentVariable("UNREALENGINEPYTHONHOME");
if (!string.IsNullOrEmpty(environmentPath))
paths.Insert(0, environmentPath);
foreach (string path in paths)
{
string actualPath = path;
if (IsPathRelative(actualPath))
{
actualPath = Path.GetFullPath(Path.Combine(ModuleDirectory, actualPath));
}
string headerFile = Path.Combine(actualPath, "include", "Python.h");
if (File.Exists(headerFile))
{
return actualPath;
}
// this is mainly useful for OSX
headerFile = Path.Combine(actualPath, "Headers", "Python.h");
if (File.Exists(headerFile))
{
return actualPath;
}
}
return "";
}
private string DiscoverLinuxPythonIncludesPath()
{
List<string> paths = new List<string>(linuxKnownIncludesPaths);
paths.Insert(0, Path.Combine(ModuleDirectory, "../../Binaries", "Linux", "include"));
foreach (string path in paths)
{
string headerFile = Path.Combine(path, "Python.h");
if (File.Exists(headerFile))
{
return path;
}
}
return null;
}
private string DiscoverLinuxPythonLibsPath()
{
List<string> paths = new List<string>(linuxKnownLibsPaths);
paths.Insert(0, Path.Combine(ModuleDirectory, "../../Binaries", "Linux", "lib"));
paths.Insert(0, Path.Combine(ModuleDirectory, "../../Binaries", "Linux", "lib64"));
foreach (string path in paths)
{
if (File.Exists(path))
{
return path;
}
}
return null;
}
private string GetMacPythonLibFile(string basePath)
{
// first try with python3
for (int i = 9; i >= 0; i--)
{
string fileName = string.Format("libpython3.{0}.dylib", i);
string fullPath = Path.Combine(basePath, "lib", fileName);
if (File.Exists(fullPath))
{
return fullPath;
}
fileName = string.Format("libpython3.{0}m.dylib", i);
fullPath = Path.Combine(basePath, "lib", fileName);
if (File.Exists(fullPath))
{
return fullPath;
}
}
// then python2
for (int i = 9; i >= 0; i--)
{
string fileName = string.Format("libpython2.{0}.dylib", i);
string fullPath = Path.Combine(basePath, "lib", fileName);
if (File.Exists(fullPath))
{
return fullPath;
}
fileName = string.Format("libpython2.{0}m.dylib", i);
fullPath = Path.Combine(basePath, "lib", fileName);
if (File.Exists(fullPath))
{
return fullPath;
}
}
throw new System.Exception("Invalid Python installation, missing .dylib files");
}
private string GetWindowsPythonLibFile(string basePath)
{
// just for usability, report if the pythonHome is not in the system path
string[] allPaths = System.Environment.GetEnvironmentVariable("PATH").Split(';');
// this will transform the slashes in backslashes...
string checkedPath = !string.IsNullOrWhiteSpace(basePath)
? new System.Uri(Path.GetFullPath(System.Environment.ExpandEnvironmentVariables(basePath)).TrimEnd(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar)).LocalPath
: basePath;
bool found = false;
foreach (string item in allPaths)
{
string checkedItem = !string.IsNullOrWhiteSpace(item)
? new System.Uri(Path.GetFullPath(System.Environment.ExpandEnvironmentVariables(item)).TrimEnd(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar)).LocalPath
: item;
if (checkedItem == checkedPath)
{
found = true;
break;
}
}
if (!found)
{
Log.TraceWarning("Your Python installation ({0}) is not in the system PATH environment variable.", checkedPath);
Log.TraceWarning("Ensure your python paths are set in GlobalConfig (DefaultEngine.ini) so the path can be corrected at runtime.");
}
// first try with python3
for (int i = 9; i >= 0; i--)
{
string fileName = string.Format("python3{0}.lib", i);
string fullPath = Path.Combine(basePath, "libs", fileName);
if (File.Exists(fullPath))
{
return fullPath;
}
}
// then python2
for (int i = 9; i >= 0; i--)
{
string fileName = string.Format("python2{0}.lib", i);
string fullPath = Path.Combine(basePath, "libs", fileName);
if (File.Exists(fullPath))
{
return fullPath;
}
}
throw new System.Exception("Invalid Python installation, missing .lib files");
}
}
| |
//
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Warning: This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if the
// code is regenerated.
using System;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Azure;
using Microsoft.AzureStack.Management;
using Microsoft.AzureStack.Management.Models;
namespace Microsoft.AzureStack.Management
{
public static partial class ProviderRegistrationOperationsExtensions
{
/// <summary>
/// Your documentation here. (see
/// http://msdn.microsoft.com/en-us/library/windowsazure/XXXXX.aspx
/// for more information)
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.AzureStack.Management.IProviderRegistrationOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. Your documentation here.
/// </param>
/// <param name='parameters'>
/// Required. Your documentation here.
/// </param>
/// <returns>
/// Your documentation here.
/// </returns>
public static ProviderRegistrationCreateOrUpdateResult CreateOrUpdate(this IProviderRegistrationOperations operations, string resourceGroupName, ProviderRegistrationCreateOrUpdateParameters parameters)
{
return Task.Factory.StartNew((object s) =>
{
return ((IProviderRegistrationOperations)s).CreateOrUpdateAsync(resourceGroupName, parameters);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Your documentation here. (see
/// http://msdn.microsoft.com/en-us/library/windowsazure/XXXXX.aspx
/// for more information)
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.AzureStack.Management.IProviderRegistrationOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. Your documentation here.
/// </param>
/// <param name='parameters'>
/// Required. Your documentation here.
/// </param>
/// <returns>
/// Your documentation here.
/// </returns>
public static Task<ProviderRegistrationCreateOrUpdateResult> CreateOrUpdateAsync(this IProviderRegistrationOperations operations, string resourceGroupName, ProviderRegistrationCreateOrUpdateParameters parameters)
{
return operations.CreateOrUpdateAsync(resourceGroupName, parameters, CancellationToken.None);
}
/// <summary>
/// Your documentation here. (see
/// http://msdn.microsoft.com/en-us/library/windowsazure/XXXXX.aspx
/// for more information)
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.AzureStack.Management.IProviderRegistrationOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. Your documentation here.
/// </param>
/// <param name='providerregistrationId'>
/// Required. Your documentation here.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
public static AzureOperationResponse Delete(this IProviderRegistrationOperations operations, string resourceGroupName, string providerregistrationId)
{
return Task.Factory.StartNew((object s) =>
{
return ((IProviderRegistrationOperations)s).DeleteAsync(resourceGroupName, providerregistrationId);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Your documentation here. (see
/// http://msdn.microsoft.com/en-us/library/windowsazure/XXXXX.aspx
/// for more information)
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.AzureStack.Management.IProviderRegistrationOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. Your documentation here.
/// </param>
/// <param name='providerregistrationId'>
/// Required. Your documentation here.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
public static Task<AzureOperationResponse> DeleteAsync(this IProviderRegistrationOperations operations, string resourceGroupName, string providerregistrationId)
{
return operations.DeleteAsync(resourceGroupName, providerregistrationId, CancellationToken.None);
}
/// <summary>
/// Your documentation here. (see
/// http://msdn.microsoft.com/en-us/library/windowsazure/XXXXX.aspx
/// for more information)
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.AzureStack.Management.IProviderRegistrationOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. Your documentation here.
/// </param>
/// <param name='providerregistrationId'>
/// Required. Your documentation here.
/// </param>
/// <returns>
/// Your documentation here.
/// </returns>
public static ProviderRegistrationGetResult Get(this IProviderRegistrationOperations operations, string resourceGroupName, string providerregistrationId)
{
return Task.Factory.StartNew((object s) =>
{
return ((IProviderRegistrationOperations)s).GetAsync(resourceGroupName, providerregistrationId);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Your documentation here. (see
/// http://msdn.microsoft.com/en-us/library/windowsazure/XXXXX.aspx
/// for more information)
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.AzureStack.Management.IProviderRegistrationOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. Your documentation here.
/// </param>
/// <param name='providerregistrationId'>
/// Required. Your documentation here.
/// </param>
/// <returns>
/// Your documentation here.
/// </returns>
public static Task<ProviderRegistrationGetResult> GetAsync(this IProviderRegistrationOperations operations, string resourceGroupName, string providerregistrationId)
{
return operations.GetAsync(resourceGroupName, providerregistrationId, CancellationToken.None);
}
/// <summary>
/// Your documentation here. (see
/// http://msdn.microsoft.com/en-us/library/windowsazure/XXXXX.aspx
/// for more information)
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.AzureStack.Management.IProviderRegistrationOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. Your documentation here.
/// </param>
/// <returns>
/// Your documentation here.
/// </returns>
public static ProviderRegistrationListResult List(this IProviderRegistrationOperations operations, string resourceGroupName)
{
return Task.Factory.StartNew((object s) =>
{
return ((IProviderRegistrationOperations)s).ListAsync(resourceGroupName);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Your documentation here. (see
/// http://msdn.microsoft.com/en-us/library/windowsazure/XXXXX.aspx
/// for more information)
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.AzureStack.Management.IProviderRegistrationOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. Your documentation here.
/// </param>
/// <returns>
/// Your documentation here.
/// </returns>
public static Task<ProviderRegistrationListResult> ListAsync(this IProviderRegistrationOperations operations, string resourceGroupName)
{
return operations.ListAsync(resourceGroupName, CancellationToken.None);
}
/// <summary>
/// Your documentation here. (see
/// http://msdn.microsoft.com/en-us/library/windowsazure/XXXXX.aspx
/// for more information)
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.AzureStack.Management.IProviderRegistrationOperations.
/// </param>
/// <param name='nextLink'>
/// Required. Your documentation here. (see
/// http://msdn.microsoft.com/en-us/library/windowsazure/XXXXX.aspx
/// for more information)
/// </param>
/// <returns>
/// Your documentation here.
/// </returns>
public static ProviderRegistrationListResult ListNext(this IProviderRegistrationOperations operations, string nextLink)
{
return Task.Factory.StartNew((object s) =>
{
return ((IProviderRegistrationOperations)s).ListNextAsync(nextLink);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Your documentation here. (see
/// http://msdn.microsoft.com/en-us/library/windowsazure/XXXXX.aspx
/// for more information)
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.AzureStack.Management.IProviderRegistrationOperations.
/// </param>
/// <param name='nextLink'>
/// Required. Your documentation here. (see
/// http://msdn.microsoft.com/en-us/library/windowsazure/XXXXX.aspx
/// for more information)
/// </param>
/// <returns>
/// Your documentation here.
/// </returns>
public static Task<ProviderRegistrationListResult> ListNextAsync(this IProviderRegistrationOperations operations, string nextLink)
{
return operations.ListNextAsync(nextLink, CancellationToken.None);
}
/// <summary>
/// Your documentation here. (see
/// http://msdn.microsoft.com/en-us/library/windowsazure/XXXXX.aspx
/// for more information)
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.AzureStack.Management.IProviderRegistrationOperations.
/// </param>
/// <returns>
/// Your documentation here.
/// </returns>
public static ProviderRegistrationListResult ListWithoutResourceGroup(this IProviderRegistrationOperations operations)
{
return Task.Factory.StartNew((object s) =>
{
return ((IProviderRegistrationOperations)s).ListWithoutResourceGroupAsync();
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Your documentation here. (see
/// http://msdn.microsoft.com/en-us/library/windowsazure/XXXXX.aspx
/// for more information)
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.AzureStack.Management.IProviderRegistrationOperations.
/// </param>
/// <returns>
/// Your documentation here.
/// </returns>
public static Task<ProviderRegistrationListResult> ListWithoutResourceGroupAsync(this IProviderRegistrationOperations operations)
{
return operations.ListWithoutResourceGroupAsync(CancellationToken.None);
}
/// <summary>
/// Validate provider registration. (see
/// http://msdn.microsoft.com/en-us/library/windowsazure/XXXXX.aspx
/// for more information)
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.AzureStack.Management.IProviderRegistrationOperations.
/// </param>
/// <param name='parameters'>
/// Required. Provider registration validation parameters.
/// </param>
/// <returns>
/// Your documentation here.
/// </returns>
public static ProviderRegistrationValidateResult Validate(this IProviderRegistrationOperations operations, ProviderRegistrationValidateParameters parameters)
{
return Task.Factory.StartNew((object s) =>
{
return ((IProviderRegistrationOperations)s).ValidateAsync(parameters);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Validate provider registration. (see
/// http://msdn.microsoft.com/en-us/library/windowsazure/XXXXX.aspx
/// for more information)
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.AzureStack.Management.IProviderRegistrationOperations.
/// </param>
/// <param name='parameters'>
/// Required. Provider registration validation parameters.
/// </param>
/// <returns>
/// Your documentation here.
/// </returns>
public static Task<ProviderRegistrationValidateResult> ValidateAsync(this IProviderRegistrationOperations operations, ProviderRegistrationValidateParameters parameters)
{
return operations.ValidateAsync(parameters, CancellationToken.None);
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Microsoft.Build.Framework;
using Microsoft.DotNet.VersionTools.Automation;
using Microsoft.DotNet.VersionTools.BuildManifest.Model;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.Xml.Linq;
using MSBuild = Microsoft.Build.Utilities;
namespace Microsoft.DotNet.Build.Tasks.Feed
{
public partial class PushToBlobFeed : BuildTask
{
private static readonly char[] ManifestDataPairSeparators = { ';' };
private const string DisableManifestPushConfigurationBlob = "disable-manifest-push";
private const string AssetsVirtualDir = "assets/";
[Required]
public string ExpectedFeedUrl { get; set; }
[Required]
public string AccountKey { get; set; }
[Required]
public ITaskItem[] ItemsToPush { get; set; }
public bool Overwrite { get; set; }
/// <summary>
/// Specify max number of minutes that the lock of the feed container will be hold.
/// </summary>
public int FeedLockTimeoutMinutes { get; set; } = int.MaxValue;
/// <summary>
/// Enables idempotency when Overwrite is false.
///
/// false: (default) Attempting to upload an item that already exists fails.
///
/// true: When an item already exists, download the existing blob to check if it's
/// byte-for-byte identical to the one being uploaded. If so, pass. If not, fail.
/// </summary>
public bool PassIfExistingItemIdentical { get; set; }
public bool PublishFlatContainer { get; set; }
public int MaxClients { get; set; } = 8;
public bool SkipCreateContainer { get; set; } = false;
public int UploadTimeoutInMinutes { get; set; } = 5;
public bool SkipCreateManifest { get; set; }
public string ManifestName { get; set; } = "anonymous";
public string ManifestBuildId { get; set; } = "no build id provided";
public string ManifestBranch { get; set; }
public string ManifestCommit { get; set; }
public string ManifestBuildData { get; set; }
/// <summary>
/// If the ExpectedFeedUrl includes an authentication token, this property is ignored.
/// </summary>
public bool MakeContainerPublic { get; set; } = true;
/// <summary>
/// When publishing build outputs to an orchestrated blob feed, do not change this property.
///
/// The virtual dir to place the manifest XML file in, under the assets/ virtual dir. The
/// default value is the well-known location that orchestration searches to find all
/// manifest XML files and combine them into the orchestrated build output manifest.
/// </summary>
public string ManifestAssetOutputDir { get; set; } = "orchestration-metadata/manifests/";
public override bool Execute()
{
return ExecuteAsync().GetAwaiter().GetResult();
}
public async Task<bool> ExecuteAsync()
{
try
{
Log.LogMessage(MessageImportance.High, "Performing feed push...");
if (ItemsToPush == null)
{
Log.LogError($"No items to push. Please check ItemGroup ItemsToPush.");
}
else
{
BlobFeedAction blobFeedAction = new BlobFeedAction(ExpectedFeedUrl, AccountKey, FeedLockTimeoutMinutes, Log);
IEnumerable<BlobArtifactModel> blobArtifacts = Enumerable.Empty<BlobArtifactModel>();
IEnumerable<PackageArtifactModel> packageArtifacts = Enumerable.Empty<PackageArtifactModel>();
if (!SkipCreateContainer)
{
await blobFeedAction.CreateContainerAsync(BuildEngine, PublishFlatContainer, MakeContainerPublic);
}
if (PublishFlatContainer)
{
await PublishToFlatContainerAsync(ItemsToPush, blobFeedAction);
blobArtifacts = ConcatBlobArtifacts(blobArtifacts, ItemsToPush);
}
else
{
ITaskItem[] symbolItems = ItemsToPush
.Where(i => i.ItemSpec.Contains("symbols.nupkg"))
.Select(i =>
{
string fileName = Path.GetFileName(i.ItemSpec);
i.SetMetadata("RelativeBlobPath", $"{AssetsVirtualDir}symbols/{fileName}");
return i;
})
.ToArray();
ITaskItem[] packageItems = ItemsToPush
.Where(i => !symbolItems.Contains(i))
.ToArray();
var packagePaths = packageItems.Select(i => i.ItemSpec);
await blobFeedAction.PushToFeedAsync(packagePaths, CreatePushOptions());
await PublishToFlatContainerAsync(symbolItems, blobFeedAction);
packageArtifacts = ConcatPackageArtifacts(packageArtifacts, packageItems);
blobArtifacts = ConcatBlobArtifacts(blobArtifacts, symbolItems);
}
if (!SkipCreateManifest)
{
await PushBuildManifestAsync(blobFeedAction, blobArtifacts, packageArtifacts);
}
}
}
catch (Exception e)
{
Log.LogErrorFromException(e, true);
}
return !Log.HasLoggedErrors;
}
private async Task PushBuildManifestAsync(
BlobFeedAction blobFeedAction,
IEnumerable<BlobArtifactModel> blobArtifacts,
IEnumerable<PackageArtifactModel> packageArtifacts)
{
bool disabledByBlob = await blobFeedAction.feed.CheckIfBlobExistsAsync(
$"{blobFeedAction.feed.RelativePath}{DisableManifestPushConfigurationBlob}");
if (disabledByBlob)
{
Log.LogMessage(
MessageImportance.Normal,
$"Skipping manifest push: feed has '{DisableManifestPushConfigurationBlob}'.");
return;
}
string blobPath = $"{AssetsVirtualDir}{ManifestAssetOutputDir}{ManifestName}.xml";
string existingStr = await blobFeedAction.feed.DownloadBlobAsStringAsync(
$"{blobFeedAction.feed.RelativePath}{blobPath}");
BuildModel buildModel;
if (existingStr != null)
{
buildModel = BuildModel.Parse(XElement.Parse(existingStr));
}
else
{
buildModel = new BuildModel(
new BuildIdentity
{
Attributes = ParseManifestMetadataString(ManifestBuildData),
Name = ManifestName,
BuildId = ManifestBuildId,
Branch = ManifestBranch,
Commit = ManifestCommit
});
}
buildModel.Artifacts.Blobs.AddRange(blobArtifacts);
buildModel.Artifacts.Packages.AddRange(packageArtifacts);
string tempFile = null;
try
{
tempFile = Path.GetTempFileName();
File.WriteAllText(tempFile, buildModel.ToXml().ToString());
var item = new MSBuild.TaskItem(tempFile, new Dictionary<string, string>
{
["RelativeBlobPath"] = blobPath
});
using (var clientThrottle = new SemaphoreSlim(MaxClients, MaxClients))
{
await blobFeedAction.UploadAssetAsync(
item,
clientThrottle,
UploadTimeoutInMinutes,
new PushOptions
{
AllowOverwrite = true
});
}
}
finally
{
if (tempFile != null)
{
File.Delete(tempFile);
}
}
}
private async Task PublishToFlatContainerAsync(IEnumerable<ITaskItem> taskItems, BlobFeedAction blobFeedAction)
{
if (taskItems.Any())
{
using (var clientThrottle = new SemaphoreSlim(this.MaxClients, this.MaxClients))
{
Log.LogMessage($"Uploading {taskItems.Count()} items...");
await Task.WhenAll(taskItems.Select(
item => blobFeedAction.UploadAssetAsync(
item,
clientThrottle,
UploadTimeoutInMinutes,
CreatePushOptions())));
}
}
}
private static IEnumerable<PackageArtifactModel> ConcatPackageArtifacts(
IEnumerable<PackageArtifactModel> artifacts,
IEnumerable<ITaskItem> items)
{
return artifacts.Concat(items
.Select(CreatePackageArtifactModel));
}
private static IEnumerable<BlobArtifactModel> ConcatBlobArtifacts(
IEnumerable<BlobArtifactModel> artifacts,
IEnumerable<ITaskItem> items)
{
return artifacts.Concat(items
.Select(CreateBlobArtifactModel)
.Where(blob => blob != null));
}
private static PackageArtifactModel CreatePackageArtifactModel(ITaskItem item)
{
NupkgInfo info = new NupkgInfo(item.ItemSpec);
return new PackageArtifactModel
{
Attributes = ParseCustomAttributes(item),
Id = info.Id,
Version = info.Version
};
}
private static BlobArtifactModel CreateBlobArtifactModel(ITaskItem item)
{
string path = item.GetMetadata("RelativeBlobPath");
// Only include assets in the manifest if they're in "assets/".
if (path?.StartsWith(AssetsVirtualDir, StringComparison.Ordinal) == true)
{
return new BlobArtifactModel
{
Attributes = ParseCustomAttributes(item),
Id = path.Substring(AssetsVirtualDir.Length)
};
}
return null;
}
private static Dictionary<string, string> ParseCustomAttributes(ITaskItem item)
{
return ParseManifestMetadataString(item.GetMetadata("ManifestArtifactData"));
}
private static Dictionary<string, string> ParseManifestMetadataString(string data)
{
if (string.IsNullOrEmpty(data))
{
return new Dictionary<string, string>();
}
return data.Split(ManifestDataPairSeparators, StringSplitOptions.RemoveEmptyEntries)
.Select(pair =>
{
int keyValueSeparatorIndex = pair.IndexOf('=');
if (keyValueSeparatorIndex > 0)
{
return new
{
Key = pair.Substring(0, keyValueSeparatorIndex).Trim(),
Value = pair.Substring(keyValueSeparatorIndex + 1).Trim()
};
}
return null;
})
.Where(pair => pair != null)
.ToDictionary(pair => pair.Key, pair => pair.Value);
}
private PushOptions CreatePushOptions()
{
return new PushOptions
{
AllowOverwrite = Overwrite,
PassIfExistingItemIdentical = PassIfExistingItemIdentical
};
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Formatting;
using System.Net.Http.Headers;
using System.Web.Http.Description;
using System.Xml.Linq;
using Newtonsoft.Json;
namespace MRTutorial.Identity.Areas.HelpPage
{
/// <summary>
/// This class will generate the samples for the help page.
/// </summary>
public class HelpPageSampleGenerator
{
/// <summary>
/// Initializes a new instance of the <see cref="HelpPageSampleGenerator"/> class.
/// </summary>
public HelpPageSampleGenerator()
{
ActualHttpMessageTypes = new Dictionary<HelpPageSampleKey, Type>();
ActionSamples = new Dictionary<HelpPageSampleKey, object>();
SampleObjects = new Dictionary<Type, object>();
SampleObjectFactories = new List<Func<HelpPageSampleGenerator, Type, object>>
{
DefaultSampleObjectFactory,
};
}
/// <summary>
/// Gets CLR types that are used as the content of <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/>.
/// </summary>
public IDictionary<HelpPageSampleKey, Type> ActualHttpMessageTypes { get; internal set; }
/// <summary>
/// Gets the objects that are used directly as samples for certain actions.
/// </summary>
public IDictionary<HelpPageSampleKey, object> ActionSamples { get; internal set; }
/// <summary>
/// Gets the objects that are serialized as samples by the supported formatters.
/// </summary>
public IDictionary<Type, object> SampleObjects { get; internal set; }
/// <summary>
/// Gets factories for the objects that the supported formatters will serialize as samples. Processed in order,
/// stopping when the factory successfully returns a non-<see langref="null"/> object.
/// </summary>
/// <remarks>
/// Collection includes just <see cref="ObjectGenerator.GenerateObject(Type)"/> initially. Use
/// <code>SampleObjectFactories.Insert(0, func)</code> to provide an override and
/// <code>SampleObjectFactories.Add(func)</code> to provide a fallback.</remarks>
[SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures",
Justification = "This is an appropriate nesting of generic types")]
public IList<Func<HelpPageSampleGenerator, Type, object>> SampleObjectFactories { get; private set; }
/// <summary>
/// Gets the request body samples for a given <see cref="ApiDescription"/>.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The samples keyed by media type.</returns>
public IDictionary<MediaTypeHeaderValue, object> GetSampleRequests(ApiDescription api)
{
return GetSample(api, SampleDirection.Request);
}
/// <summary>
/// Gets the response body samples for a given <see cref="ApiDescription"/>.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The samples keyed by media type.</returns>
public IDictionary<MediaTypeHeaderValue, object> GetSampleResponses(ApiDescription api)
{
return GetSample(api, SampleDirection.Response);
}
/// <summary>
/// Gets the request or response body samples.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param>
/// <returns>The samples keyed by media type.</returns>
public virtual IDictionary<MediaTypeHeaderValue, object> GetSample(ApiDescription api, SampleDirection sampleDirection)
{
if (api == null)
{
throw new ArgumentNullException("api");
}
string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName;
string actionName = api.ActionDescriptor.ActionName;
IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name);
Collection<MediaTypeFormatter> formatters;
Type type = ResolveType(api, controllerName, actionName, parameterNames, sampleDirection, out formatters);
var samples = new Dictionary<MediaTypeHeaderValue, object>();
// Use the samples provided directly for actions
var actionSamples = GetAllActionSamples(controllerName, actionName, parameterNames, sampleDirection);
foreach (var actionSample in actionSamples)
{
samples.Add(actionSample.Key.MediaType, WrapSampleIfString(actionSample.Value));
}
// Do the sample generation based on formatters only if an action doesn't return an HttpResponseMessage.
// Here we cannot rely on formatters because we don't know what's in the HttpResponseMessage, it might not even use formatters.
if (type != null && !typeof(HttpResponseMessage).IsAssignableFrom(type))
{
object sampleObject = GetSampleObject(type);
foreach (var formatter in formatters)
{
foreach (MediaTypeHeaderValue mediaType in formatter.SupportedMediaTypes)
{
if (!samples.ContainsKey(mediaType))
{
object sample = GetActionSample(controllerName, actionName, parameterNames, type, formatter, mediaType, sampleDirection);
// If no sample found, try generate sample using formatter and sample object
if (sample == null && sampleObject != null)
{
sample = WriteSampleObjectUsingFormatter(formatter, sampleObject, type, mediaType);
}
samples.Add(mediaType, WrapSampleIfString(sample));
}
}
}
}
return samples;
}
/// <summary>
/// Search for samples that are provided directly through <see cref="ActionSamples"/>.
/// </summary>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
/// <param name="type">The CLR type.</param>
/// <param name="formatter">The formatter.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param>
/// <returns>The sample that matches the parameters.</returns>
public virtual object GetActionSample(string controllerName, string actionName, IEnumerable<string> parameterNames, Type type, MediaTypeFormatter formatter, MediaTypeHeaderValue mediaType, SampleDirection sampleDirection)
{
object sample;
// First, try to get the sample provided for the specified mediaType, sampleDirection, controllerName, actionName and parameterNames.
// If not found, try to get the sample provided for the specified mediaType, sampleDirection, controllerName and actionName regardless of the parameterNames.
// If still not found, try to get the sample provided for the specified mediaType and type.
// Finally, try to get the sample provided for the specified mediaType.
if (ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, parameterNames), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, new[] { "*" }), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, type), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType), out sample))
{
return sample;
}
return null;
}
/// <summary>
/// Gets the sample object that will be serialized by the formatters.
/// First, it will look at the <see cref="SampleObjects"/>. If no sample object is found, it will try to create
/// one using <see cref="DefaultSampleObjectFactory"/> (which wraps an <see cref="ObjectGenerator"/>) and other
/// factories in <see cref="SampleObjectFactories"/>.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>The sample object.</returns>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes",
Justification = "Even if all items in SampleObjectFactories throw, problem will be visible as missing sample.")]
public virtual object GetSampleObject(Type type)
{
object sampleObject;
if (!SampleObjects.TryGetValue(type, out sampleObject))
{
// No specific object available, try our factories.
foreach (Func<HelpPageSampleGenerator, Type, object> factory in SampleObjectFactories)
{
if (factory == null)
{
continue;
}
try
{
sampleObject = factory(this, type);
if (sampleObject != null)
{
break;
}
}
catch
{
// Ignore any problems encountered in the factory; go on to the next one (if any).
}
}
}
return sampleObject;
}
/// <summary>
/// Resolves the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The type.</returns>
public virtual Type ResolveHttpRequestMessageType(ApiDescription api)
{
string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName;
string actionName = api.ActionDescriptor.ActionName;
IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name);
Collection<MediaTypeFormatter> formatters;
return ResolveType(api, controllerName, actionName, parameterNames, SampleDirection.Request, out formatters);
}
/// <summary>
/// Resolves the type of the action parameter or return value when <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/> is used.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or a response.</param>
/// <param name="formatters">The formatters.</param>
[SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", Justification = "This is only used in advanced scenarios.")]
public virtual Type ResolveType(ApiDescription api, string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection, out Collection<MediaTypeFormatter> formatters)
{
if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection))
{
throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection));
}
if (api == null)
{
throw new ArgumentNullException("api");
}
Type type;
if (ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, parameterNames), out type) ||
ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, new[] { "*" }), out type))
{
// Re-compute the supported formatters based on type
Collection<MediaTypeFormatter> newFormatters = new Collection<MediaTypeFormatter>();
foreach (var formatter in api.ActionDescriptor.Configuration.Formatters)
{
if (IsFormatSupported(sampleDirection, formatter, type))
{
newFormatters.Add(formatter);
}
}
formatters = newFormatters;
}
else
{
switch (sampleDirection)
{
case SampleDirection.Request:
ApiParameterDescription requestBodyParameter = api.ParameterDescriptions.FirstOrDefault(p => p.Source == ApiParameterSource.FromBody);
type = requestBodyParameter == null ? null : requestBodyParameter.ParameterDescriptor.ParameterType;
formatters = api.SupportedRequestBodyFormatters;
break;
case SampleDirection.Response:
default:
type = api.ResponseDescription.ResponseType ?? api.ResponseDescription.DeclaredType;
formatters = api.SupportedResponseFormatters;
break;
}
}
return type;
}
/// <summary>
/// Writes the sample object using formatter.
/// </summary>
/// <param name="formatter">The formatter.</param>
/// <param name="value">The value.</param>
/// <param name="type">The type.</param>
/// <param name="mediaType">Type of the media.</param>
/// <returns></returns>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as InvalidSample.")]
public virtual object WriteSampleObjectUsingFormatter(MediaTypeFormatter formatter, object value, Type type, MediaTypeHeaderValue mediaType)
{
if (formatter == null)
{
throw new ArgumentNullException("formatter");
}
if (mediaType == null)
{
throw new ArgumentNullException("mediaType");
}
object sample = String.Empty;
MemoryStream ms = null;
HttpContent content = null;
try
{
if (formatter.CanWriteType(type))
{
ms = new MemoryStream();
content = new ObjectContent(type, value, formatter, mediaType);
formatter.WriteToStreamAsync(type, value, ms, content, null).Wait();
ms.Position = 0;
StreamReader reader = new StreamReader(ms);
string serializedSampleString = reader.ReadToEnd();
if (mediaType.MediaType.ToUpperInvariant().Contains("XML"))
{
serializedSampleString = TryFormatXml(serializedSampleString);
}
else if (mediaType.MediaType.ToUpperInvariant().Contains("JSON"))
{
serializedSampleString = TryFormatJson(serializedSampleString);
}
sample = new TextSample(serializedSampleString);
}
else
{
sample = new InvalidSample(String.Format(
CultureInfo.CurrentCulture,
"Failed to generate the sample for media type '{0}'. Cannot use formatter '{1}' to write type '{2}'.",
mediaType,
formatter.GetType().Name,
type.Name));
}
}
catch (Exception e)
{
sample = new InvalidSample(String.Format(
CultureInfo.CurrentCulture,
"An exception has occurred while using the formatter '{0}' to generate sample for media type '{1}'. Exception message: {2}",
formatter.GetType().Name,
mediaType.MediaType,
UnwrapException(e).Message));
}
finally
{
if (ms != null)
{
ms.Dispose();
}
if (content != null)
{
content.Dispose();
}
}
return sample;
}
internal static Exception UnwrapException(Exception exception)
{
AggregateException aggregateException = exception as AggregateException;
if (aggregateException != null)
{
return aggregateException.Flatten().InnerException;
}
return exception;
}
// Default factory for sample objects
private static object DefaultSampleObjectFactory(HelpPageSampleGenerator sampleGenerator, Type type)
{
// Try to create a default sample object
ObjectGenerator objectGenerator = new ObjectGenerator();
return objectGenerator.GenerateObject(type);
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")]
private static string TryFormatJson(string str)
{
try
{
object parsedJson = JsonConvert.DeserializeObject(str);
return JsonConvert.SerializeObject(parsedJson, Formatting.Indented);
}
catch
{
// can't parse JSON, return the original string
return str;
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")]
private static string TryFormatXml(string str)
{
try
{
XDocument xml = XDocument.Parse(str);
return xml.ToString();
}
catch
{
// can't parse XML, return the original string
return str;
}
}
private static bool IsFormatSupported(SampleDirection sampleDirection, MediaTypeFormatter formatter, Type type)
{
switch (sampleDirection)
{
case SampleDirection.Request:
return formatter.CanReadType(type);
case SampleDirection.Response:
return formatter.CanWriteType(type);
}
return false;
}
private IEnumerable<KeyValuePair<HelpPageSampleKey, object>> GetAllActionSamples(string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection)
{
HashSet<string> parameterNamesSet = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase);
foreach (var sample in ActionSamples)
{
HelpPageSampleKey sampleKey = sample.Key;
if (String.Equals(controllerName, sampleKey.ControllerName, StringComparison.OrdinalIgnoreCase) &&
String.Equals(actionName, sampleKey.ActionName, StringComparison.OrdinalIgnoreCase) &&
(sampleKey.ParameterNames.SetEquals(new[] { "*" }) || parameterNamesSet.SetEquals(sampleKey.ParameterNames)) &&
sampleDirection == sampleKey.SampleDirection)
{
yield return sample;
}
}
}
private static object WrapSampleIfString(object sample)
{
string stringSample = sample as string;
if (stringSample != null)
{
return new TextSample(stringSample);
}
return sample;
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
internal class test
{
public static int Main()
{
float x;
float y;
bool pass = true;
x = -10.0F;
y = 4.0F;
x = x + y;
if (x != -6)
{
Console.WriteLine("\nInitial parameters: x is -10.0F and y is 4.0F");
Console.WriteLine("x = x + y failed. x: {0}, \texpected: -6\n", x);
pass = false;
}
x = -10.0F;
y = 4.0F;
x = x - y;
if (x != -14)
{
Console.WriteLine("\nInitial parameters: x is -10.0F and y is 4.0F");
Console.WriteLine("x = x - y failed. x: {0}, \texpected: -14\n", x);
pass = false;
}
x = -10.0F;
y = 4.0F;
x = x * y;
if (x != -40)
{
Console.WriteLine("\nInitial parameters: x is -10.0F and y is 4.0F");
Console.WriteLine("x = x * y failed. x: {0}, \texpected: -40\n", x);
pass = false;
}
x = -10.0F;
y = 4.0F;
x = x / y;
if (x != -2.5)
{
Console.WriteLine("\nInitial parameters: x is -10.0F and y is 4.0F");
Console.WriteLine("x = x / y failed. x: {0}, \texpected: -2.5\n", x);
pass = false;
}
x = -10.0F;
y = 4.0F;
x = x % y;
if (x != -2)
{
Console.WriteLine("\nInitial parameters: x is -10.0F and y is 4.0F");
Console.WriteLine("x = x % y failed. x: {0}, \texpected: -2\n", x);
pass = false;
}
x = -10.0F;
y = 4.0F;
x += x + y;
if (x != -16)
{
Console.WriteLine("\nInitial parameters: x is -10.0F and y is 4.0F");
Console.WriteLine("x += x + y failed. x: {0}, \texpected: -16\n", x);
pass = false;
}
x = -10.0F;
y = 4.0F;
x += x - y;
if (x != -24)
{
Console.WriteLine("\nInitial parameters: x is -10.0F and y is 4.0F");
Console.WriteLine("x += x - y failed. x: {0}, \texpected: -24\n", x);
pass = false;
}
x = -10.0F;
y = 4.0F;
x += x * y;
if (x != -50)
{
Console.WriteLine("\nInitial parameters: x is -10.0F and y is 4.0F");
Console.WriteLine("x += x * y failed. x: {0}, \texpected: -50\n", x);
pass = false;
}
x = -10.0F;
y = 4.0F;
x += x / y;
if (x != -12.5)
{
Console.WriteLine("\nInitial parameters: x is -10.0F and y is 4.0F");
Console.WriteLine("x += x / y failed. x: {0}, \texpected: -12.5\n", x);
pass = false;
}
x = -10.0F;
y = 4.0F;
x += x % y;
if (x != -12)
{
Console.WriteLine("\nInitial parameters: x is -10.0F and y is 4.0F");
Console.WriteLine("x += x % y failed. x: {0}, \texpected: -12\n", x);
pass = false;
}
x = -10.0F;
y = 4.0F;
x -= x + y;
if (x != -4)
{
Console.WriteLine("\nInitial parameters: x is -10.0F and y is 4.0F");
Console.WriteLine("x -= x + y failed. x: {0}, \texpected: -4\n", x);
pass = false;
}
x = -10.0F;
y = 4.0F;
x -= x - y;
if (x != 4)
{
Console.WriteLine("\nInitial parameters: x is -10.0F and y is 4.0F");
Console.WriteLine("x -= x - y failed. x: {0}, \texpected: 4\n", x);
pass = false;
}
x = -10.0F;
y = 4.0F;
x -= x * y;
if (x != 30)
{
Console.WriteLine("\nInitial parameters: x is -10.0F and y is 4.0F");
Console.WriteLine("x -= x * y failed. x: {0}, \texpected: 30\n", x);
pass = false;
}
x = -10.0F;
y = 4.0F;
x -= x / y;
if (x != -7.5)
{
Console.WriteLine("\nInitial parameters: x is -10.0F and y is 4.0F");
Console.WriteLine("x -= x / y failed. x: {0}, \texpected: -7.5\n", x);
pass = false;
}
x = -10.0F;
y = 4.0F;
x -= x % y;
if (x != -8)
{
Console.WriteLine("\nInitial parameters: x is -10.0F and y is 4.0F");
Console.WriteLine("x -= x % y failed. x: {0}, \texpected: -8\n", x);
pass = false;
}
x = -10.0F;
y = 4.0F;
x *= x + y;
if (x != 60)
{
Console.WriteLine("\nInitial parameters: x is -10.0F and y is 4.0F");
Console.WriteLine("x *= x + y failed. x: {0}, \texpected: 60\n", x);
pass = false;
}
x = -10.0F;
y = 4.0F;
x *= x - y;
if (x != 140)
{
Console.WriteLine("\nInitial parameters: x is -10.0F and y is 4.0F");
Console.WriteLine("x *= x - y failed. x: {0}, \texpected: 140\n", x);
pass = false;
}
x = -10.0F;
y = 4.0F;
x *= x * y;
if (x != 400)
{
Console.WriteLine("\nInitial parameters: x is -10.0F and y is 4.0F");
Console.WriteLine("x *= x * y failed. x: {0}, \texpected: 400\n", x);
pass = false;
}
x = -10.0F;
y = 4.0F;
x *= x / y;
if (x != 25)
{
Console.WriteLine("\nInitial parameters: x is -10.0F and y is 4.0F");
Console.WriteLine("x *= x / y failed. x: {0}, \texpected: 25\n", x);
pass = false;
}
x = -10.0F;
y = 4.0F;
x *= x % y;
if (x != 20)
{
Console.WriteLine("\nInitial parameters: x is -10.0F and y is 4.0F");
Console.WriteLine("x *= x % y failed. x: {0}, \texpected: 20\n", x);
pass = false;
}
x = -10.0F;
y = 4.0F;
x /= x + y;
if (!x.Equals(1.66666663F))
{
Console.WriteLine("\nInitial parameters: x is -10.0F and y is 4.0F");
Console.WriteLine("x /= x + y failed. x: {0}, \texpected: 1.66666663F\n", x);
pass = false;
}
x = -10.0F;
y = 4.0F;
x /= x - y;
if (!x.Equals(0.714285731F))
{
Console.WriteLine("\nInitial parameters: x is -10.0F and y is 4.0F");
Console.WriteLine("x /= x - y failed. x: {0}, \texpected: 0.714285731F\n", x);
pass = false;
}
x = -10.0F;
y = 4.0F;
x /= x * y;
if (x != 0.25)
{
Console.WriteLine("\nInitial parameters: x is -10.0F and y is 4.0F");
Console.WriteLine("x /= x * y failed. x: {0}, \texpected: 0.25\n", x);
pass = false;
}
x = -10.0F;
y = 4.0F;
x /= x / y;
if (x != 4)
{
Console.WriteLine("\nInitial parameters: x is -10.0F and y is 4.0F");
Console.WriteLine("x /= x / y failed. x: {0}, \texpected: 4\n", x);
pass = false;
}
x = -10.0F;
y = 4.0F;
x /= x % y;
if (x != 5)
{
Console.WriteLine("\nInitial parameters: x is -10.0F and y is 4.0F");
Console.WriteLine("x /= x % y failed. x: {0}, \texpected: 5\n", x);
pass = false;
}
if (pass)
{
Console.WriteLine("PASSED");
return 100;
}
else
return 1;
}
}
| |
//
// System.IO.BinaryWriter
//
// Authors:
// Matt Kimball (matt@kimball.net)
// Marek Safar (marek.safar@gmail.com)
//
//
// Copyright (C) 2004 Novell, Inc (http://www.novell.com)
// Copyright 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 System.Text;
using System.Globalization;
using System.Runtime.InteropServices;
using Java.IO;
using Java.Util;
namespace System.IO {
[Serializable]
[ComVisible (true)]
public class BinaryWriter : IDisposable {
// Null is a BinaryWriter with no backing store.
public static readonly BinaryWriter Null = new BinaryWriter ();
protected Stream OutStream;
private Encoding m_encoding;
private byte [] buffer;
byte [] stringBuffer;
int maxCharsPerRound;
bool disposed;
protected BinaryWriter() : this (Stream.Null, Encoding.UTF8)
{
}
public BinaryWriter(Stream output) : this(output, Encoding.UTF8)
{
}
#if NET_4_5
readonly bool leave_open;
public BinaryWriter(Stream output, Encoding encoding)
: this (output, encoding, false)
{
}
public BinaryWriter(Stream output, Encoding encoding, bool leaveOpen)
#else
const bool leave_open = false;
public BinaryWriter(Stream output, Encoding encoding)
#endif
{
if (output == null)
throw new ArgumentNullException("output");
if (encoding == null)
throw new ArgumentNullException("encoding");
if (!output.CanWrite)
throw new ArgumentException("Stream does not support writing or already closed.");
#if NET_4_5
leave_open = leaveOpen;
#endif
OutStream = output;
m_encoding = encoding;
buffer = new byte [16];
}
public virtual Stream BaseStream {
get {
Flush ();
return OutStream;
}
}
public virtual void Close() {
Dispose (true);
}
#if NET_4_0
public void Dispose ()
#else
void IDisposable.Dispose()
#endif
{
Dispose (true);
}
protected virtual void Dispose (bool disposing)
{
if (disposing && OutStream != null && !leave_open)
OutStream.Close();
buffer = null;
m_encoding = null;
disposed = true;
}
public virtual void Flush() {
OutStream.Flush();
}
public virtual long Seek(int offset, SeekOrigin origin) {
return OutStream.Seek(offset, origin);
}
public virtual void Write(bool value) {
if (disposed)
throw new ObjectDisposedException ("BinaryWriter", "Cannot write to a closed BinaryWriter");
buffer [0] = (byte) (value ? 1 : 0);
OutStream.Write(buffer, 0, 1);
}
public virtual void Write(byte value) {
if (disposed)
throw new ObjectDisposedException ("BinaryWriter", "Cannot write to a closed BinaryWriter");
OutStream.WriteByte(value);
}
public virtual void Write(byte[] buffer) {
if (disposed)
throw new ObjectDisposedException ("BinaryWriter", "Cannot write to a closed BinaryWriter");
if (buffer == null)
throw new ArgumentNullException("buffer");
OutStream.Write(buffer, 0, buffer.Length);
}
public virtual void Write(byte[] buffer, int index, int count) {
if (disposed)
throw new ObjectDisposedException ("BinaryWriter", "Cannot write to a closed BinaryWriter");
if (buffer == null)
throw new ArgumentNullException("buffer");
OutStream.Write(buffer, index, count);
}
public virtual void Write(char ch) {
if (disposed)
throw new ObjectDisposedException ("BinaryWriter", "Cannot write to a closed BinaryWriter");
char[] dec = new char[1];
dec[0] = ch;
byte[] enc = m_encoding.GetBytes(dec, 0, 1);
OutStream.Write(enc, 0, enc.Length);
}
public virtual void Write(char[] chars) {
if (disposed)
throw new ObjectDisposedException ("BinaryWriter", "Cannot write to a closed BinaryWriter");
if (chars == null)
throw new ArgumentNullException("chars");
byte[] enc = m_encoding.GetBytes(chars, 0, chars.Length);
OutStream.Write(enc, 0, enc.Length);
}
public virtual void Write(char[] chars, int index, int count) {
if (disposed)
throw new ObjectDisposedException ("BinaryWriter", "Cannot write to a closed BinaryWriter");
if (chars == null)
throw new ArgumentNullException("chars");
byte[] enc = m_encoding.GetBytes(chars, index, count);
OutStream.Write(enc, 0, enc.Length);
}
public virtual void Write(decimal value) {
if (disposed)
throw new ObjectDisposedException ("BinaryWriter", "Cannot write to a closed BinaryWriter");
var bits = decimal.GetBits(value);
Write(bits[0]);
Write(bits[1]);
Write(bits[2]);
Write(bits[3]);
}
public virtual void Write(double value) {
if (disposed)
throw new ObjectDisposedException ("BinaryWriter", "Cannot write to a closed BinaryWriter");
var byteArrayOutputStream = new ByteArrayOutputStream();
var dataOutputStream = new DataOutputStream(byteArrayOutputStream);
dataOutputStream.WriteDouble(value);
byteArrayOutputStream.Flush();
WriteSwapped(byteArrayOutputStream.ToByteArray(), 8);
byteArrayOutputStream.Close();
dataOutputStream.Close();
}
public virtual void Write(short value) {
if (disposed)
throw new ObjectDisposedException ("BinaryWriter", "Cannot write to a closed BinaryWriter");
buffer [0] = (byte) value;
buffer [1] = (byte) (value >> 8);
OutStream.Write(buffer, 0, 2);
}
public virtual void Write(int value) {
if (disposed)
throw new ObjectDisposedException ("BinaryWriter", "Cannot write to a closed BinaryWriter");
buffer [0] = (byte) value;
buffer [1] = (byte) (value >> 8);
buffer [2] = (byte) (value >> 16);
buffer [3] = (byte) (value >> 24);
OutStream.Write(buffer, 0, 4);
}
public virtual void Write(long value) {
if (disposed)
throw new ObjectDisposedException ("BinaryWriter", "Cannot write to a closed BinaryWriter");
for (int i = 0, sh = 0; i < 8; i++, sh += 8)
buffer [i] = (byte) (value >> sh);
OutStream.Write(buffer, 0, 8);
}
[CLSCompliant(false)]
public virtual void Write(sbyte value) {
if (disposed)
throw new ObjectDisposedException ("BinaryWriter", "Cannot write to a closed BinaryWriter");
buffer [0] = (byte) value;
OutStream.Write(buffer, 0, 1);
}
public virtual void Write(float value) {
if (disposed)
throw new ObjectDisposedException ("BinaryWriter", "Cannot write to a closed BinaryWriter");
var byteArrayOutputStream = new ByteArrayOutputStream();
var dataOutputStream = new DataOutputStream(byteArrayOutputStream);
dataOutputStream.WriteFloat(value);
byteArrayOutputStream.Flush();
WriteSwapped(byteArrayOutputStream.ToByteArray(), 4);
byteArrayOutputStream.Close();
dataOutputStream.Close();
}
private void WriteSwapped(byte[] bytes, int count)
{
var swappedBytes = new byte[count];
for (int i = 0, j = count - 1; i < count; i++, j--)
swappedBytes[i] = bytes[j];
OutStream.Write(swappedBytes, 0, count);
}
public virtual void Write(string value) {
if (disposed)
throw new ObjectDisposedException ("BinaryWriter", "Cannot write to a closed BinaryWriter");
int len = m_encoding.GetByteCount (value);
Write7BitEncodedInt (len);
if (stringBuffer == null) {
stringBuffer = new byte [512];
maxCharsPerRound = 512 / m_encoding.GetMaxByteCount (1);
}
int chpos = 0;
int chrem = value.Length;
while (chrem > 0) {
int cch = (chrem > maxCharsPerRound) ? maxCharsPerRound : chrem;
int blen = m_encoding.GetBytes (value, chpos, cch, stringBuffer, 0);
OutStream.Write (stringBuffer, 0, blen);
chpos += cch;
chrem -= cch;
}
}
[CLSCompliant(false)]
public virtual void Write(ushort value) {
if (disposed)
throw new ObjectDisposedException ("BinaryWriter", "Cannot write to a closed BinaryWriter");
buffer [0] = (byte) value;
buffer [1] = (byte) (value >> 8);
OutStream.Write(buffer, 0, 2);
}
[CLSCompliant(false)]
public virtual void Write(uint value) {
if (disposed)
throw new ObjectDisposedException ("BinaryWriter", "Cannot write to a closed BinaryWriter");
buffer [0] = (byte) value;
buffer [1] = (byte) (value >> 8);
buffer [2] = (byte) (value >> 16);
buffer [3] = (byte) (value >> 24);
OutStream.Write(buffer, 0, 4);
}
[CLSCompliant(false)]
public virtual void Write(ulong value) {
if (disposed)
throw new ObjectDisposedException ("BinaryWriter", "Cannot write to a closed BinaryWriter");
for (int i = 0, sh = 0; i < 8; i++, sh += 8)
buffer [i] = (byte) (value >> sh);
OutStream.Write(buffer, 0, 8);
}
protected void Write7BitEncodedInt(int value) {
do {
int high = (value >> 7) & 0x01ffffff;
byte b = (byte)(value & 0x7f);
if (high != 0) {
b = (byte)(b | 0x80);
}
Write(b);
value = high;
} while(value != 0);
}
}
}
| |
//
// Copyright (c) 2008-2011, Kenneth Bell
//
// 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 DiscUtils;
using DiscUtils.Iso9660;
using Xunit;
namespace LibraryTests.Iso9660
{
public class IsoDirectoryInfoTest
{
[Fact]
public void Exists()
{
CDBuilder builder = new CDBuilder();
builder.AddFile(@"SOMEDIR\CHILDDIR\FILE.TXT", new byte[0]);
CDReader fs = new CDReader(builder.Build(), false);
Assert.True(fs.GetDirectoryInfo(@"\").Exists);
Assert.True(fs.GetDirectoryInfo(@"SOMEDIR").Exists);
Assert.True(fs.GetDirectoryInfo(@"SOMEDIR\CHILDDIR").Exists);
Assert.True(fs.GetDirectoryInfo(@"SOMEDIR\CHILDDIR\").Exists);
Assert.False(fs.GetDirectoryInfo(@"NONDIR").Exists);
Assert.False(fs.GetDirectoryInfo(@"SOMEDIR\NONDIR").Exists);
}
[Fact]
public void FullName()
{
CDBuilder builder = new CDBuilder();
CDReader fs = new CDReader(builder.Build(), false);
Assert.Equal(@"\", fs.Root.FullName);
Assert.Equal(@"SOMEDIR\", fs.GetDirectoryInfo(@"SOMEDIR").FullName);
Assert.Equal(@"SOMEDIR\CHILDDIR\", fs.GetDirectoryInfo(@"SOMEDIR\CHILDDIR").FullName);
}
[Fact]
public void SimpleSearch()
{
CDBuilder builder = new CDBuilder();
builder.AddFile(@"SOMEDIR\CHILDDIR\GCHILDIR\FILE.TXT", new byte[0]);
CDReader fs = new CDReader(builder.Build(), false);
DiscDirectoryInfo di = fs.GetDirectoryInfo(@"SOMEDIR\CHILDDIR");
DiscFileInfo[] fis = di.GetFiles("*.*", SearchOption.AllDirectories);
}
[Fact]
public void Extension()
{
CDBuilder builder = new CDBuilder();
CDReader fs = new CDReader(builder.Build(), false);
Assert.Equal("dir", fs.GetDirectoryInfo("fred.dir").Extension);
Assert.Equal("", fs.GetDirectoryInfo("fred").Extension);
}
[Fact]
public void GetDirectories()
{
CDBuilder builder = new CDBuilder();
builder.AddDirectory(@"SOMEDIR\CHILD\GCHILD");
builder.AddDirectory(@"A.DIR");
CDReader fs = new CDReader(builder.Build(), false);
Assert.Equal(2, fs.Root.GetDirectories().Length);
DiscDirectoryInfo someDir = fs.Root.GetDirectories(@"SoMeDir")[0];
Assert.Equal(1, fs.Root.GetDirectories("SOMEDIR").Length);
Assert.Equal("SOMEDIR", someDir.Name);
Assert.Equal(1, someDir.GetDirectories("*.*").Length);
Assert.Equal("CHILD", someDir.GetDirectories("*.*")[0].Name);
Assert.Equal(2, someDir.GetDirectories("*.*", SearchOption.AllDirectories).Length);
Assert.Equal(4, fs.Root.GetDirectories("*.*", SearchOption.AllDirectories).Length);
Assert.Equal(2, fs.Root.GetDirectories("*.*", SearchOption.TopDirectoryOnly).Length);
Assert.Equal(1, fs.Root.GetDirectories("*.DIR", SearchOption.AllDirectories).Length);
Assert.Equal(@"A.DIR\", fs.Root.GetDirectories("*.DIR", SearchOption.AllDirectories)[0].FullName);
Assert.Equal(1, fs.Root.GetDirectories("GCHILD", SearchOption.AllDirectories).Length);
Assert.Equal(@"SOMEDIR\CHILD\GCHILD\", fs.Root.GetDirectories("GCHILD", SearchOption.AllDirectories)[0].FullName);
}
[Fact]
public void GetFiles()
{
CDBuilder builder = new CDBuilder();
builder.AddDirectory(@"SOMEDIR\CHILD\GCHILD");
builder.AddDirectory(@"AAA.DIR");
builder.AddFile(@"FOO.TXT", new byte[10]);
builder.AddFile(@"SOMEDIR\CHILD.TXT", new byte[10]);
builder.AddFile(@"SOMEDIR\FOO.TXT", new byte[10]);
builder.AddFile(@"SOMEDIR\CHILD\GCHILD\BAR.TXT", new byte[10]);
CDReader fs = new CDReader(builder.Build(), false);
Assert.Equal(1, fs.Root.GetFiles().Length);
Assert.Equal("FOO.TXT", fs.Root.GetFiles()[0].FullName);
Assert.Equal(2, fs.Root.GetDirectories("SOMEDIR")[0].GetFiles("*.TXT").Length);
Assert.Equal(4, fs.Root.GetFiles("*.TXT", SearchOption.AllDirectories).Length);
Assert.Equal(0, fs.Root.GetFiles("*.DIR", SearchOption.AllDirectories).Length);
}
[Fact]
public void GetFileSystemInfos()
{
CDBuilder builder = new CDBuilder();
builder.AddDirectory(@"SOMEDIR\CHILD\GCHILD");
builder.AddDirectory(@"AAA.EXT");
builder.AddFile(@"FOO.TXT", new byte[10]);
builder.AddFile(@"SOMEDIR\CHILD.TXT", new byte[10]);
builder.AddFile(@"SOMEDIR\FOO.TXT", new byte[10]);
builder.AddFile(@"SOMEDIR\CHILD\GCHILD\BAR.TXT", new byte[10]);
CDReader fs = new CDReader(builder.Build(), false);
Assert.Equal(3, fs.Root.GetFileSystemInfos().Length);
Assert.Equal(1, fs.Root.GetFileSystemInfos("*.EXT").Length);
Assert.Equal(2, fs.Root.GetFileSystemInfos("*.?XT").Length);
}
[Fact]
public void Parent()
{
CDBuilder builder = new CDBuilder();
builder.AddDirectory(@"SOMEDIR");
CDReader fs = new CDReader(builder.Build(), false);
Assert.Equal(fs.Root, fs.Root.GetDirectories("SOMEDIR")[0].Parent);
}
[Fact]
public void Parent_Root()
{
CDBuilder builder = new CDBuilder();
CDReader fs = new CDReader(builder.Build(), false);
Assert.Null(fs.Root.Parent);
}
[Fact]
public void RootBehaviour()
{
// Start time rounded down to whole seconds
DateTime start = DateTime.UtcNow;
start = new DateTime(start.Year, start.Month, start.Day, start.Hour, start.Minute, start.Second);
CDBuilder builder = new CDBuilder();
CDReader fs = new CDReader(builder.Build(), false);
DateTime end = DateTime.UtcNow;
Assert.Equal(FileAttributes.Directory | FileAttributes.ReadOnly, fs.Root.Attributes);
Assert.True(fs.Root.CreationTimeUtc >= start);
Assert.True(fs.Root.CreationTimeUtc <= end);
Assert.True(fs.Root.LastAccessTimeUtc >= start);
Assert.True(fs.Root.LastAccessTimeUtc <= end);
Assert.True(fs.Root.LastWriteTimeUtc >= start);
Assert.True(fs.Root.LastWriteTimeUtc <= end);
}
[Fact]
public void Attributes()
{
// Start time rounded down to whole seconds
DateTime start = DateTime.UtcNow;
start = new DateTime(start.Year, start.Month, start.Day, start.Hour, start.Minute, start.Second);
CDBuilder builder = new CDBuilder();
builder.AddDirectory("Foo");
CDReader fs = new CDReader(builder.Build(), false);
DateTime end = DateTime.UtcNow;
DiscDirectoryInfo di = fs.GetDirectoryInfo("Foo");
Assert.Equal(FileAttributes.Directory | FileAttributes.ReadOnly, di.Attributes);
Assert.True(di.CreationTimeUtc >= start);
Assert.True(di.CreationTimeUtc <= end);
Assert.True(di.LastAccessTimeUtc >= start);
Assert.True(di.LastAccessTimeUtc <= end);
Assert.True(di.LastWriteTimeUtc >= start);
Assert.True(di.LastWriteTimeUtc <= end);
}
}
}
| |
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Diagnostics;
using System.Text;
using HtcSharp.HttpModule.Core.Internal.Infrastructure;
using HtcSharp.HttpModule.Http;
using HtcSharp.HttpModule.Shared.UrlDecoder;
namespace HtcSharp.HttpModule.Core.Internal.Http {
// SourceTools-Start
// Remote-File C:\ASP\src\Servers\Kestrel\Core\src\Internal\Http\PathNormalizer.cs
// Start-At-Remote-Line 11
// SourceTools-End
internal static class PathNormalizer {
private const byte ByteSlash = (byte) '/';
private const byte ByteDot = (byte) '.';
public static string DecodePath(Span<byte> path, bool pathEncoded, string rawTarget, int queryLength) {
int pathLength;
if (pathEncoded) {
// URI was encoded, unescape and then parse as UTF-8
pathLength = UrlDecoder.DecodeInPlace(path, isFormEncoding: false);
// Removing dot segments must be done after unescaping. From RFC 3986:
//
// URI producing applications should percent-encode data octets that
// correspond to characters in the reserved set unless these characters
// are specifically allowed by the URI scheme to represent data in that
// component. If a reserved character is found in a URI component and
// no delimiting role is known for that character, then it must be
// interpreted as representing the data octet corresponding to that
// character's encoding in US-ASCII.
//
// https://tools.ietf.org/html/rfc3986#section-2.2
pathLength = RemoveDotSegments(path.Slice(0, pathLength));
return Encoding.UTF8.GetString(path.Slice(0, pathLength));
}
pathLength = RemoveDotSegments(path);
if (path.Length == pathLength && queryLength == 0) {
// If no decoding was required, no dot segments were removed and
// there is no query, the request path is the same as the raw target
return rawTarget;
}
return path.Slice(0, pathLength).GetAsciiStringNonNullCharacters();
}
// In-place implementation of the algorithm from https://tools.ietf.org/html/rfc3986#section-5.2.4
public static unsafe int RemoveDotSegments(Span<byte> input) {
fixed (byte* start = input) {
var end = start + input.Length;
return RemoveDotSegments(start, end);
}
}
public static unsafe int RemoveDotSegments(byte* start, byte* end) {
if (!ContainsDotSegments(start, end)) {
return (int) (end - start);
}
var src = start;
var dst = start;
while (src < end) {
var ch1 = *src;
Debug.Assert(ch1 == '/', "Path segment must always start with a '/'");
byte ch2, ch3, ch4;
switch (end - src) {
case 1:
break;
case 2:
ch2 = *(src + 1);
if (ch2 == ByteDot) {
// B. if the input buffer begins with a prefix of "/./" or "/.",
// where "." is a complete path segment, then replace that
// prefix with "/" in the input buffer; otherwise,
src += 1;
*src = ByteSlash;
continue;
}
break;
case 3:
ch2 = *(src + 1);
ch3 = *(src + 2);
if (ch2 == ByteDot && ch3 == ByteDot) {
// C. if the input buffer begins with a prefix of "/../" or "/..",
// where ".." is a complete path segment, then replace that
// prefix with "/" in the input buffer and remove the last
// segment and its preceding "/" (if any) from the output
// buffer; otherwise,
src += 2;
*src = ByteSlash;
if (dst > start) {
do {
dst--;
} while (dst > start && *dst != ByteSlash);
}
continue;
} else if (ch2 == ByteDot && ch3 == ByteSlash) {
// B. if the input buffer begins with a prefix of "/./" or "/.",
// where "." is a complete path segment, then replace that
// prefix with "/" in the input buffer; otherwise,
src += 2;
continue;
}
break;
default:
ch2 = *(src + 1);
ch3 = *(src + 2);
ch4 = *(src + 3);
if (ch2 == ByteDot && ch3 == ByteDot && ch4 == ByteSlash) {
// C. if the input buffer begins with a prefix of "/../" or "/..",
// where ".." is a complete path segment, then replace that
// prefix with "/" in the input buffer and remove the last
// segment and its preceding "/" (if any) from the output
// buffer; otherwise,
src += 3;
if (dst > start) {
do {
dst--;
} while (dst > start && *dst != ByteSlash);
}
continue;
} else if (ch2 == ByteDot && ch3 == ByteSlash) {
// B. if the input buffer begins with a prefix of "/./" or "/.",
// where "." is a complete path segment, then replace that
// prefix with "/" in the input buffer; otherwise,
src += 2;
continue;
}
break;
}
// E. move the first path segment in the input buffer to the end of
// the output buffer, including the initial "/" character (if
// any) and any subsequent characters up to, but not including,
// the next "/" character or the end of the input buffer.
do {
*dst++ = ch1;
ch1 = *++src;
} while (src < end && ch1 != ByteSlash);
}
if (dst == start) {
*dst++ = ByteSlash;
}
return (int) (dst - start);
}
public static unsafe bool ContainsDotSegments(byte* start, byte* end) {
var src = start;
while (src < end) {
var ch1 = *src;
Debug.Assert(ch1 == '/', "Path segment must always start with a '/'");
byte ch2, ch3, ch4;
switch (end - src) {
case 1:
break;
case 2:
ch2 = *(src + 1);
if (ch2 == ByteDot) {
return true;
}
break;
case 3:
ch2 = *(src + 1);
ch3 = *(src + 2);
if ((ch2 == ByteDot && ch3 == ByteDot) ||
(ch2 == ByteDot && ch3 == ByteSlash)) {
return true;
}
break;
default:
ch2 = *(src + 1);
ch3 = *(src + 2);
ch4 = *(src + 3);
if ((ch2 == ByteDot && ch3 == ByteDot && ch4 == ByteSlash) ||
(ch2 == ByteDot && ch3 == ByteSlash)) {
return true;
}
break;
}
do {
ch1 = *++src;
} while (src < end && ch1 != ByteSlash);
}
return false;
}
}
}
| |
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="DList.cs" company="Redpoint Software">
// The MIT License (MIT)
//
// Copyright (c) 2013 James Rhodes
//
// 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>
// <summary>
// Defines the distributed list type.
// </summary>
// --------------------------------------------------------------------------------------------------------------------
namespace Dx.Runtime
{
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
[SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Reviewed. Suppression is OK here.")]
[Distributed]
public class DList<T> : IList<T>, ITransparent
{
private List<T> m_List = new List<T>();
public DList()
{
DpmEntrypoint.Construct(this);
}
public DList(int capacity)
{
DpmEntrypoint.Construct(this);
this.m_List = new List<T>(capacity);
}
public DList(IEnumerable<T> collection)
{
DpmEntrypoint.Construct(this);
this.m_List = new List<T>(collection);
}
#region ITransparent Members
public string NetworkName
{
get;
set;
}
public bool LocallyOwned
{
get;
set;
}
public ILocalNode Node
{
get;
set;
}
public int Count
{
get
{
if (this.InvokeLocally)
{
return this._Count();
}
return (int)this.Owner.Invoke(this.NetworkName, "_Count", new Type[0], new object[] { });
}
}
public bool IsReadOnly
{
get
{
if (this.InvokeLocally)
{
return this._IsReadOnly();
}
return (bool)this.Owner.Invoke(this.NetworkName, "_IsReadOnly", new Type[0], new object[] { });
}
}
private ILocalNode Owner
{
get
{
return this.Node;
}
}
private bool InvokeLocally
{
get
{
return this.LocallyOwned || this.NetworkName == null;
}
}
#endregion
public T this[int index]
{
get
{
if (this.InvokeLocally)
{
return this._GetItemInternal(index);
}
return (T)this.Owner.Invoke(this.NetworkName, "_GetItemInternal", new Type[0], new object[] { index });
}
set
{
if (this.InvokeLocally)
{
this._SetItemInternal(index, value);
}
else
{
this.Owner.Invoke(this.NetworkName, "_SetItemInternal", new Type[0], new object[] { index, value });
}
}
}
#region Public Methods (automatically remoted)
#region IList<T> Members
public int IndexOf(T item)
{
if (this.InvokeLocally)
{
return this._IndexOf(item);
}
return (int)this.Owner.Invoke(this.NetworkName, "_IndexOf", new Type[0], new object[] { item });
}
public void Insert(int index, T item)
{
if (this.InvokeLocally)
{
this._Insert(index, item);
}
else
{
this.Owner.Invoke(this.NetworkName, "_Insert", new Type[0], new object[] { index, item });
}
}
public void RemoveAt(int index)
{
if (this.InvokeLocally)
{
this._RemoveAt(index);
}
else
{
this.Owner.Invoke(this.NetworkName, "_RemoveAt", new Type[0], new object[] { index });
}
}
#endregion
#region ICollection<T> Members
public void Add(T item)
{
if (this.InvokeLocally)
{
this._Add(item);
}
else
{
this.Owner.Invoke(this.NetworkName, "_Add", new Type[0], new object[] { item });
}
}
public void Clear()
{
if (this.InvokeLocally)
{
this._Clear();
}
else
{
this.Owner.Invoke(this.NetworkName, "_Clear", new Type[0], new object[] { });
}
}
public bool Contains(T item)
{
if (this.InvokeLocally)
{
return this._Contains(item);
}
return (bool)this.Owner.Invoke(this.NetworkName, "_Contains", new Type[0], new object[] { item });
}
public void CopyTo(T[] array, int arrayIndex)
{
if (this.InvokeLocally)
{
this._CopyTo(array, arrayIndex);
}
else
{
this.Owner.Invoke(this.NetworkName, "_CopyTo", new Type[0], new object[] { array, arrayIndex });
}
}
public bool Remove(T item)
{
if (this.InvokeLocally)
{
return this._Remove(item);
}
return (bool)this.Owner.Invoke(this.NetworkName, "_Remove", new Type[0], new object[] { item });
}
#endregion
#region IEnumerable<T> Members
public IEnumerator<T> GetEnumerator()
{
if (this.InvokeLocally)
{
return this._GetEnumerator();
}
return (IEnumerator<T>)this.Owner.Invoke(this.NetworkName, "_GetEnumerator", new Type[0], new object[] { });
}
#endregion
#region IEnumerable Members
IEnumerator IEnumerable.GetEnumerator()
{
if (this.InvokeLocally)
{
return this._IGetEnumerator();
}
return (IEnumerator)this.Owner.Invoke(this.NetworkName, "_IGetEnumerator", new Type[0], new object[] { });
}
#endregion
#endregion
#region Private Methods (operate locally)
#region IList<T> Members
private int _IndexOf(T item)
{
return this.m_List.IndexOf(item);
}
private void _Insert(int index, T item)
{
this.m_List.Insert(index, item);
}
private void _RemoveAt(int index)
{
this.m_List.RemoveAt(index);
}
private T _GetItemInternal(int index)
{
return this.m_List[index];
}
private void _SetItemInternal(int index, T value)
{
this.m_List[index] = value;
}
#endregion
#region ICollection<T> Members
private void _Add(T item)
{
// Protobuf deserializes the list by calling Add(), which means
// we need to set up the local field correctly.
if (this.m_List == null)
{
this.m_List = new List<T>();
}
this.m_List.Add(item);
}
private void _Clear()
{
this.m_List.Clear();
}
private bool _Contains(T item)
{
return this.m_List.Contains(item);
}
private void _CopyTo(T[] array, int arrayIndex)
{
this.m_List.CopyTo(array, arrayIndex);
}
private int _Count()
{
return this.m_List.Count;
}
private bool _IsReadOnly()
{
return false;
}
private bool _Remove(T item)
{
return this.m_List.Remove(item);
}
#endregion
#region IEnumerable<T> Members
private IEnumerator<T> _GetEnumerator()
{
return this.m_List.GetEnumerator();
}
#endregion
#region IEnumerable Members
private IEnumerator _IGetEnumerator()
{
return (this.m_List as IEnumerable).GetEnumerator();
}
#endregion
#endregion
}
}
| |
namespace Xilium.CefGlue
{
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Runtime.InteropServices;
using Xilium.CefGlue.Interop;
/// <summary>
/// Class used to implement render process callbacks. The methods of this class
/// will be called on the render process main thread (TID_RENDERER) unless
/// otherwise indicated.
/// </summary>
public abstract unsafe partial class CefRenderProcessHandler
{
private void on_render_thread_created(cef_render_process_handler_t* self, cef_list_value_t* extra_info)
{
CheckSelf(self);
var mExtraInfo = CefListValue.FromNative(extra_info);
OnRenderThreadCreated(mExtraInfo);
mExtraInfo.Dispose();
}
/// <summary>
/// Called after the render process main thread has been created.
/// </summary>
protected virtual void OnRenderThreadCreated(CefListValue extraInfo)
{
}
private void on_web_kit_initialized(cef_render_process_handler_t* self)
{
CheckSelf(self);
OnWebKitInitialized();
}
/// <summary>
/// Called after WebKit has been initialized.
/// </summary>
protected virtual void OnWebKitInitialized()
{
}
private void on_browser_created(cef_render_process_handler_t* self, cef_browser_t* browser)
{
CheckSelf(self);
var m_browser = CefBrowser.FromNative(browser);
OnBrowserCreated(m_browser);
}
/// <summary>
/// Called after a browser has been created. When browsing cross-origin a new
/// browser will be created before the old browser with the same identifier is
/// destroyed.
/// </summary>
protected virtual void OnBrowserCreated(CefBrowser browser)
{
}
private void on_browser_destroyed(cef_render_process_handler_t* self, cef_browser_t* browser)
{
CheckSelf(self);
var m_browser = CefBrowser.FromNative(browser);
OnBrowserDestroyed(m_browser);
}
/// <summary>
/// Called before a browser is destroyed.
/// </summary>
protected virtual void OnBrowserDestroyed(CefBrowser browser)
{
}
private cef_load_handler_t* get_load_handler(cef_render_process_handler_t* self)
{
CheckSelf(self);
var result = GetLoadHandler();
return result != null ? result.ToNative() : null;
}
/// <summary>
/// Return the handler for browser load status events.
/// </summary>
protected virtual CefLoadHandler GetLoadHandler()
{
return null;
}
private int on_before_navigation(cef_render_process_handler_t* self, cef_browser_t* browser, cef_frame_t* frame, cef_request_t* request, CefNavigationType navigation_type, int is_redirect)
{
CheckSelf(self);
var m_browser = CefBrowser.FromNative(browser);
var m_frame = CefFrame.FromNative(frame);
var m_request = CefRequest.FromNative(request);
var result = OnBeforeNavigation(m_browser, m_frame, m_request, navigation_type, is_redirect != 0);
return result ? 1 : 0;
}
/// <summary>
/// Called before browser navigation. Return true to cancel the navigation or
/// false to allow the navigation to proceed. The |request| object cannot be
/// modified in this callback.
/// </summary>
protected virtual bool OnBeforeNavigation(CefBrowser browser, CefFrame frame, CefRequest request, CefNavigationType navigation_type, bool isRedirect)
{
return false;
}
private void on_context_created(cef_render_process_handler_t* self, cef_browser_t* browser, cef_frame_t* frame, cef_v8context_t* context)
{
CheckSelf(self);
var m_browser = CefBrowser.FromNative(browser);
var m_frame = CefFrame.FromNative(frame);
var m_context = CefV8Context.FromNative(context);
OnContextCreated(m_browser, m_frame, m_context);
}
/// <summary>
/// Called immediately after the V8 context for a frame has been created. To
/// retrieve the JavaScript 'window' object use the CefV8Context::GetGlobal()
/// method. V8 handles can only be accessed from the thread on which they are
/// created. A task runner for posting tasks on the associated thread can be
/// retrieved via the CefV8Context::GetTaskRunner() method.
/// </summary>
protected virtual void OnContextCreated(CefBrowser browser, CefFrame frame, CefV8Context context)
{
}
private void on_context_released(cef_render_process_handler_t* self, cef_browser_t* browser, cef_frame_t* frame, cef_v8context_t* context)
{
CheckSelf(self);
var m_browser = CefBrowser.FromNative(browser);
var m_frame = CefFrame.FromNative(frame);
var m_context = CefV8Context.FromNative(context);
OnContextReleased(m_browser, m_frame, m_context);
}
/// <summary>
/// Called immediately before the V8 context for a frame is released. No
/// references to the context should be kept after this method is called.
/// </summary>
protected virtual void OnContextReleased(CefBrowser browser, CefFrame frame, CefV8Context context)
{
}
private void on_uncaught_exception(cef_render_process_handler_t* self, cef_browser_t* browser, cef_frame_t* frame, cef_v8context_t* context, cef_v8exception_t* exception, cef_v8stack_trace_t* stackTrace)
{
CheckSelf(self);
var mBrowser = CefBrowser.FromNative(browser);
var mFrame = CefFrame.FromNative(frame);
var mContext = CefV8Context.FromNative(context);
var mException = CefV8Exception.FromNative(exception);
var mStackTrace = CefV8StackTrace.FromNative(stackTrace);
OnUncaughtException(mBrowser, mFrame, mContext, mException, mStackTrace);
}
/// <summary>
/// Called for global uncaught exceptions in a frame. Execution of this
/// callback is disabled by default. To enable set
/// CefSettings.uncaught_exception_stack_size > 0.
/// </summary>
protected virtual void OnUncaughtException(CefBrowser browser, CefFrame frame, CefV8Context context, CefV8Exception exception, CefV8StackTrace stackTrace)
{
}
private void on_focused_node_changed(cef_render_process_handler_t* self, cef_browser_t* browser, cef_frame_t* frame, cef_domnode_t* node)
{
CheckSelf(self);
var m_browser = CefBrowser.FromNative(browser);
var m_frame = CefFrame.FromNative(frame);
var m_node = CefDomNode.FromNativeOrNull(node);
OnFocusedNodeChanged(m_browser, m_frame, m_node);
if (m_node != null) m_node.Dispose();
}
/// <summary>
/// Called when a new node in the the browser gets focus. The |node| value may
/// be empty if no specific node has gained focus. The node object passed to
/// this method represents a snapshot of the DOM at the time this method is
/// executed. DOM objects are only valid for the scope of this method. Do not
/// keep references to or attempt to access any DOM objects outside the scope
/// of this method.
/// </summary>
protected virtual void OnFocusedNodeChanged(CefBrowser browser, CefFrame frame, CefDomNode node)
{
}
private int on_process_message_received(cef_render_process_handler_t* self, cef_browser_t* browser, CefProcessId source_process, cef_process_message_t* message)
{
CheckSelf(self);
var m_browser = CefBrowser.FromNative(browser);
var m_message = CefProcessMessage.FromNative(message);
var result = OnProcessMessageReceived(m_browser, source_process, m_message);
m_message.Dispose();
return result ? 1 : 0;
}
/// <summary>
/// Called when a new message is received from a different process. Return true
/// if the message was handled or false otherwise. Do not keep a reference to
/// or attempt to access the message outside of this callback.
/// </summary>
protected virtual bool OnProcessMessageReceived(CefBrowser browser, CefProcessId sourceProcess, CefProcessMessage message)
{
return false;
}
}
}
| |
#region Apache License
//
// 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.
//
#endregion
using System;
using System.Globalization;
using System.Net;
using System.Net.Sockets;
using System.Text;
using Ctrip.Layout;
using Ctrip.Core;
using Ctrip.Util;
namespace Ctrip.Appender
{
/// <summary>
/// Sends logging events as connectionless UDP datagrams to a remote host or a
/// multicast group using an <see cref="UdpClient" />.
/// </summary>
/// <remarks>
/// <para>
/// UDP guarantees neither that messages arrive, nor that they arrive in the correct order.
/// </para>
/// <para>
/// To view the logging results, a custom application can be developed that listens for logging
/// events.
/// </para>
/// <para>
/// When decoding events send via this appender remember to use the same encoding
/// to decode the events as was used to send the events. See the <see cref="Encoding"/>
/// property to specify the encoding to use.
/// </para>
/// </remarks>
/// <example>
/// This example shows how to log receive logging events that are sent
/// on IP address 244.0.0.1 and port 8080 to the console. The event is
/// encoded in the packet as a unicode string and it is decoded as such.
/// <code lang="C#">
/// IPEndPoint remoteEndPoint = new IPEndPoint(IPAddress.Any, 0);
/// UdpClient udpClient;
/// byte[] buffer;
/// string loggingEvent;
///
/// try
/// {
/// udpClient = new UdpClient(8080);
///
/// while(true)
/// {
/// buffer = udpClient.Receive(ref remoteEndPoint);
/// loggingEvent = System.Text.Encoding.Unicode.GetString(buffer);
/// Console.WriteLine(loggingEvent);
/// }
/// }
/// catch(Exception e)
/// {
/// Console.WriteLine(e.ToString());
/// }
/// </code>
/// <code lang="Visual Basic">
/// Dim remoteEndPoint as IPEndPoint
/// Dim udpClient as UdpClient
/// Dim buffer as Byte()
/// Dim loggingEvent as String
///
/// Try
/// remoteEndPoint = new IPEndPoint(IPAddress.Any, 0)
/// udpClient = new UdpClient(8080)
///
/// While True
/// buffer = udpClient.Receive(ByRef remoteEndPoint)
/// loggingEvent = System.Text.Encoding.Unicode.GetString(buffer)
/// Console.WriteLine(loggingEvent)
/// Wend
/// Catch e As Exception
/// Console.WriteLine(e.ToString())
/// End Try
/// </code>
/// <para>
/// An example configuration section to log information using this appender to the
/// IP 224.0.0.1 on port 8080:
/// </para>
/// <code lang="XML" escaped="true">
/// <appender name="UdpAppender" type="Ctrip.Appender.UdpAppender">
/// <remoteAddress value="224.0.0.1" />
/// <remotePort value="8080" />
/// <layout type="Ctrip.Layout.PatternLayout" value="%-5level %logger [%ndc] - %message%newline" />
/// </appender>
/// </code>
/// </example>
/// <author>Gert Driesen</author>
/// <author>Nicko Cadell</author>
public class UdpAppender : AppenderSkeleton
{
#region Public Instance Constructors
/// <summary>
/// Initializes a new instance of the <see cref="UdpAppender" /> class.
/// </summary>
/// <remarks>
/// The default constructor initializes all fields to their default values.
/// </remarks>
public UdpAppender()
{
}
#endregion Public Instance Constructors
#region Public Instance Properties
/// <summary>
/// Gets or sets the IP address of the remote host or multicast group to which
/// the underlying <see cref="UdpClient" /> should sent the logging event.
/// </summary>
/// <value>
/// The IP address of the remote host or multicast group to which the logging event
/// will be sent.
/// </value>
/// <remarks>
/// <para>
/// Multicast addresses are identified by IP class <b>D</b> addresses (in the range 224.0.0.0 to
/// 239.255.255.255). Multicast packets can pass across different networks through routers, so
/// it is possible to use multicasts in an Internet scenario as long as your network provider
/// supports multicasting.
/// </para>
/// <para>
/// Hosts that want to receive particular multicast messages must register their interest by joining
/// the multicast group. Multicast messages are not sent to networks where no host has joined
/// the multicast group. Class <b>D</b> IP addresses are used for multicast groups, to differentiate
/// them from normal host addresses, allowing nodes to easily detect if a message is of interest.
/// </para>
/// <para>
/// Static multicast addresses that are needed globally are assigned by IANA. A few examples are listed in the table below:
/// </para>
/// <para>
/// <list type="table">
/// <listheader>
/// <term>IP Address</term>
/// <description>Description</description>
/// </listheader>
/// <item>
/// <term>224.0.0.1</term>
/// <description>
/// <para>
/// Sends a message to all system on the subnet.
/// </para>
/// </description>
/// </item>
/// <item>
/// <term>224.0.0.2</term>
/// <description>
/// <para>
/// Sends a message to all routers on the subnet.
/// </para>
/// </description>
/// </item>
/// <item>
/// <term>224.0.0.12</term>
/// <description>
/// <para>
/// The DHCP server answers messages on the IP address 224.0.0.12, but only on a subnet.
/// </para>
/// </description>
/// </item>
/// </list>
/// </para>
/// <para>
/// A complete list of actually reserved multicast addresses and their owners in the ranges
/// defined by RFC 3171 can be found at the <A href="http://www.iana.org/assignments/multicast-addresses">IANA web site</A>.
/// </para>
/// <para>
/// The address range 239.0.0.0 to 239.255.255.255 is reserved for administrative scope-relative
/// addresses. These addresses can be reused with other local groups. Routers are typically
/// configured with filters to prevent multicast traffic in this range from flowing outside
/// of the local network.
/// </para>
/// </remarks>
public IPAddress RemoteAddress
{
get { return m_remoteAddress; }
set { m_remoteAddress = value; }
}
/// <summary>
/// Gets or sets the TCP port number of the remote host or multicast group to which
/// the underlying <see cref="UdpClient" /> should sent the logging event.
/// </summary>
/// <value>
/// An integer value in the range <see cref="IPEndPoint.MinPort" /> to <see cref="IPEndPoint.MaxPort" />
/// indicating the TCP port number of the remote host or multicast group to which the logging event
/// will be sent.
/// </value>
/// <remarks>
/// The underlying <see cref="UdpClient" /> will send messages to this TCP port number
/// on the remote host or multicast group.
/// </remarks>
/// <exception cref="ArgumentOutOfRangeException">The value specified is less than <see cref="IPEndPoint.MinPort" /> or greater than <see cref="IPEndPoint.MaxPort" />.</exception>
public int RemotePort
{
get { return m_remotePort; }
set
{
if (value < IPEndPoint.MinPort || value > IPEndPoint.MaxPort)
{
throw Ctrip.Util.SystemInfo.CreateArgumentOutOfRangeException("value", (object)value,
"The value specified is less than " +
IPEndPoint.MinPort.ToString(NumberFormatInfo.InvariantInfo) +
" or greater than " +
IPEndPoint.MaxPort.ToString(NumberFormatInfo.InvariantInfo) + ".");
}
else
{
m_remotePort = value;
}
}
}
/// <summary>
/// Gets or sets the TCP port number from which the underlying <see cref="UdpClient" /> will communicate.
/// </summary>
/// <value>
/// An integer value in the range <see cref="IPEndPoint.MinPort" /> to <see cref="IPEndPoint.MaxPort" />
/// indicating the TCP port number from which the underlying <see cref="UdpClient" /> will communicate.
/// </value>
/// <remarks>
/// <para>
/// The underlying <see cref="UdpClient" /> will bind to this port for sending messages.
/// </para>
/// <para>
/// Setting the value to 0 (the default) will cause the udp client not to bind to
/// a local port.
/// </para>
/// </remarks>
/// <exception cref="ArgumentOutOfRangeException">The value specified is less than <see cref="IPEndPoint.MinPort" /> or greater than <see cref="IPEndPoint.MaxPort" />.</exception>
public int LocalPort
{
get { return m_localPort; }
set
{
if (value != 0 && (value < IPEndPoint.MinPort || value > IPEndPoint.MaxPort))
{
throw Ctrip.Util.SystemInfo.CreateArgumentOutOfRangeException("value", (object)value,
"The value specified is less than " +
IPEndPoint.MinPort.ToString(NumberFormatInfo.InvariantInfo) +
" or greater than " +
IPEndPoint.MaxPort.ToString(NumberFormatInfo.InvariantInfo) + ".");
}
else
{
m_localPort = value;
}
}
}
/// <summary>
/// Gets or sets <see cref="Encoding"/> used to write the packets.
/// </summary>
/// <value>
/// The <see cref="Encoding"/> used to write the packets.
/// </value>
/// <remarks>
/// <para>
/// The <see cref="Encoding"/> used to write the packets.
/// </para>
/// </remarks>
public Encoding Encoding
{
get { return m_encoding; }
set { m_encoding = value; }
}
#endregion Public Instance Properties
#region Protected Instance Properties
/// <summary>
/// Gets or sets the underlying <see cref="UdpClient" />.
/// </summary>
/// <value>
/// The underlying <see cref="UdpClient" />.
/// </value>
/// <remarks>
/// <see cref="UdpAppender" /> creates a <see cref="UdpClient" /> to send logging events
/// over a network. Classes deriving from <see cref="UdpAppender" /> can use this
/// property to get or set this <see cref="UdpClient" />. Use the underlying <see cref="UdpClient" />
/// returned from <see cref="Client" /> if you require access beyond that which
/// <see cref="UdpAppender" /> provides.
/// </remarks>
protected UdpClient Client
{
get { return this.m_client; }
set { this.m_client = value; }
}
/// <summary>
/// Gets or sets the cached remote endpoint to which the logging events should be sent.
/// </summary>
/// <value>
/// The cached remote endpoint to which the logging events will be sent.
/// </value>
/// <remarks>
/// The <see cref="ActivateOptions" /> method will initialize the remote endpoint
/// with the values of the <see cref="RemoteAddress" /> and <see cref="RemotePort"/>
/// properties.
/// </remarks>
protected IPEndPoint RemoteEndPoint
{
get { return this.m_remoteEndPoint; }
set { this.m_remoteEndPoint = value; }
}
#endregion Protected Instance Properties
#region Implementation of IOptionHandler
/// <summary>
/// Initialize the appender based on the options set.
/// </summary>
/// <remarks>
/// <para>
/// This is part of the <see cref="IOptionHandler"/> delayed object
/// activation scheme. The <see cref="ActivateOptions"/> method must
/// be called on this object after the configuration properties have
/// been set. Until <see cref="ActivateOptions"/> is called this
/// object is in an undefined state and must not be used.
/// </para>
/// <para>
/// If any of the configuration properties are modified then
/// <see cref="ActivateOptions"/> must be called again.
/// </para>
/// <para>
/// The appender will be ignored if no <see cref="RemoteAddress" /> was specified or
/// an invalid remote or local TCP port number was specified.
/// </para>
/// </remarks>
/// <exception cref="ArgumentNullException">The required property <see cref="RemoteAddress" /> was not specified.</exception>
/// <exception cref="ArgumentOutOfRangeException">The TCP port number assigned to <see cref="LocalPort" /> or <see cref="RemotePort" /> is less than <see cref="IPEndPoint.MinPort" /> or greater than <see cref="IPEndPoint.MaxPort" />.</exception>
public override void ActivateOptions()
{
base.ActivateOptions();
if (this.RemoteAddress == null)
{
throw new ArgumentNullException("The required property 'Address' was not specified.");
}
else if (this.RemotePort < IPEndPoint.MinPort || this.RemotePort > IPEndPoint.MaxPort)
{
throw Ctrip.Util.SystemInfo.CreateArgumentOutOfRangeException("this.RemotePort", (object)this.RemotePort,
"The RemotePort is less than " +
IPEndPoint.MinPort.ToString(NumberFormatInfo.InvariantInfo) +
" or greater than " +
IPEndPoint.MaxPort.ToString(NumberFormatInfo.InvariantInfo) + ".");
}
else if (this.LocalPort != 0 && (this.LocalPort < IPEndPoint.MinPort || this.LocalPort > IPEndPoint.MaxPort))
{
throw Ctrip.Util.SystemInfo.CreateArgumentOutOfRangeException("this.LocalPort", (object)this.LocalPort,
"The LocalPort is less than " +
IPEndPoint.MinPort.ToString(NumberFormatInfo.InvariantInfo) +
" or greater than " +
IPEndPoint.MaxPort.ToString(NumberFormatInfo.InvariantInfo) + ".");
}
else
{
this.RemoteEndPoint = new IPEndPoint(this.RemoteAddress, this.RemotePort);
this.InitializeClientConnection();
}
}
#endregion
#region Override implementation of AppenderSkeleton
/// <summary>
/// This method is called by the <see cref="M:AppenderSkeleton.DoAppend(LoggingEvent)"/> method.
/// </summary>
/// <param name="loggingEvent">The event to log.</param>
/// <remarks>
/// <para>
/// Sends the event using an UDP datagram.
/// </para>
/// <para>
/// Exceptions are passed to the <see cref="AppenderSkeleton.ErrorHandler"/>.
/// </para>
/// </remarks>
protected override void Append(LoggingEvent loggingEvent)
{
try
{
Byte [] buffer = m_encoding.GetBytes(RenderLoggingEvent(loggingEvent).ToCharArray());
this.Client.Send(buffer, buffer.Length, this.RemoteEndPoint);
}
catch (Exception ex)
{
ErrorHandler.Error(
"Unable to send logging event to remote host " +
this.RemoteAddress.ToString() +
" on port " +
this.RemotePort + ".",
ex,
ErrorCode.WriteFailure);
}
}
/// <summary>
/// This appender requires a <see cref="Layout"/> to be set.
/// </summary>
/// <value><c>true</c></value>
/// <remarks>
/// <para>
/// This appender requires a <see cref="Layout"/> to be set.
/// </para>
/// </remarks>
override protected bool RequiresLayout
{
get { return true; }
}
/// <summary>
/// Closes the UDP connection and releases all resources associated with
/// this <see cref="UdpAppender" /> instance.
/// </summary>
/// <remarks>
/// <para>
/// Disables the underlying <see cref="UdpClient" /> and releases all managed
/// and unmanaged resources associated with the <see cref="UdpAppender" />.
/// </para>
/// </remarks>
override protected void OnClose()
{
base.OnClose();
if (this.Client != null)
{
this.Client.Close();
this.Client = null;
}
}
#endregion Override implementation of AppenderSkeleton
#region Protected Instance Methods
/// <summary>
/// Initializes the underlying <see cref="UdpClient" /> connection.
/// </summary>
/// <remarks>
/// <para>
/// The underlying <see cref="UdpClient"/> is initialized and binds to the
/// port number from which you intend to communicate.
/// </para>
/// <para>
/// Exceptions are passed to the <see cref="AppenderSkeleton.ErrorHandler"/>.
/// </para>
/// </remarks>
protected virtual void InitializeClientConnection()
{
try
{
if (this.LocalPort == 0)
{
#if NETCF || NET_1_0 || SSCLI_1_0 || CLI_1_0
this.Client = new UdpClient();
#else
this.Client = new UdpClient(RemoteAddress.AddressFamily);
#endif
}
else
{
#if NETCF || NET_1_0 || SSCLI_1_0 || CLI_1_0
this.Client = new UdpClient(this.LocalPort);
#else
this.Client = new UdpClient(this.LocalPort, RemoteAddress.AddressFamily);
#endif
}
}
catch (Exception ex)
{
ErrorHandler.Error(
"Could not initialize the UdpClient connection on port " +
this.LocalPort.ToString(NumberFormatInfo.InvariantInfo) + ".",
ex,
ErrorCode.GenericFailure);
this.Client = null;
}
}
#endregion Protected Instance Methods
#region Private Instance Fields
/// <summary>
/// The IP address of the remote host or multicast group to which
/// the logging event will be sent.
/// </summary>
private IPAddress m_remoteAddress;
/// <summary>
/// The TCP port number of the remote host or multicast group to
/// which the logging event will be sent.
/// </summary>
private int m_remotePort;
/// <summary>
/// The cached remote endpoint to which the logging events will be sent.
/// </summary>
private IPEndPoint m_remoteEndPoint;
/// <summary>
/// The TCP port number from which the <see cref="UdpClient" /> will communicate.
/// </summary>
private int m_localPort;
/// <summary>
/// The <see cref="UdpClient" /> instance that will be used for sending the
/// logging events.
/// </summary>
private UdpClient m_client;
/// <summary>
/// The encoding to use for the packet.
/// </summary>
private Encoding m_encoding = Encoding.Default;
#endregion Private Instance Fields
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.